1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2013, 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_event_trigger.h"
53 #include "catalog/pg_largeobject.h"
54 #include "catalog/pg_largeobject_metadata.h"
55 #include "catalog/pg_proc.h"
56 #include "catalog/pg_trigger.h"
57 #include "catalog/pg_type.h"
58 #include "libpq/libpq-fs.h"
60 #include "pg_backup_archiver.h"
61 #include "pg_backup_db.h"
62 #include "dumputils.h"
71 const char *descr; /* comment for an object */
72 Oid classoid; /* object class (catalog OID) */
73 Oid objoid; /* object OID */
74 int objsubid; /* subobject (table column #) */
79 const char *provider; /* label provider of this security label */
80 const char *label; /* security label for an object */
81 Oid classoid; /* object class (catalog OID) */
82 Oid objoid; /* object OID */
83 int objsubid; /* subobject (table column #) */
87 bool g_verbose; /* User wants verbose narration of our
90 /* various user-settable parameters */
93 int dumpSections; /* bitmask of chosen sections */
95 const char *lockWaitTimeout;
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
100 /* obsolete as of 7.3: */
101 static Oid g_last_builtin_oid; /* value of the last builtin oid */
104 * Object inclusion/exclusion lists
106 * The string lists record the patterns given by command-line switches,
107 * which we then convert to lists of OIDs of matching objects.
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
118 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
119 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
121 /* default, if no "inclusion" switches appear, is to dump everything */
122 static bool include_everything = true;
124 char g_opaque_type[10]; /* name for the opaque type */
126 /* placeholders for the delimiters for comments */
127 char g_comment_start[10];
128 char g_comment_end[10];
130 static const CatalogId nilCatalogId = {0, 0};
132 /* flags for various command-line long options */
133 static int binary_upgrade = 0;
134 static int disable_dollar_quoting = 0;
135 static int dump_inserts = 0;
136 static int column_inserts = 0;
137 static int no_security_labels = 0;
138 static int no_unlogged_table_data = 0;
139 static int serializable_deferrable = 0;
142 static void help(const char *progname);
143 static void setup_connection(Archive *AH, const char *dumpencoding,
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(Archive *fout,
147 SimpleStringList *patterns,
148 SimpleOidList *oids);
149 static void expand_table_name_patterns(Archive *fout,
150 SimpleStringList *patterns,
151 SimpleOidList *oids);
152 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
153 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
154 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
155 static void dumpComment(Archive *fout, const char *target,
156 const char *namespace, const char *owner,
157 CatalogId catalogId, int subid, DumpId dumpId);
158 static int findComments(Archive *fout, Oid classoid, Oid objoid,
159 CommentItem **items);
160 static int collectComments(Archive *fout, CommentItem **items);
161 static void dumpSecLabel(Archive *fout, const char *target,
162 const char *namespace, const char *owner,
163 CatalogId catalogId, int subid, DumpId dumpId);
164 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
165 SecLabelItem **items);
166 static int collectSecLabels(Archive *fout, SecLabelItem **items);
167 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
168 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
169 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
170 static void dumpType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
175 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
177 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
178 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
179 static void dumpFunc(Archive *fout, FuncInfo *finfo);
180 static void dumpCast(Archive *fout, CastInfo *cast);
181 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
182 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
183 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
184 static void dumpCollation(Archive *fout, CollInfo *convinfo);
185 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
186 static void dumpRule(Archive *fout, RuleInfo *rinfo);
187 static void dumpAgg(Archive *fout, AggInfo *agginfo);
188 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
189 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
190 static void dumpTable(Archive *fout, TableInfo *tbinfo);
191 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
192 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
193 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
194 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
195 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
196 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
197 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
198 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
199 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
200 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
201 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
202 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
203 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
204 static void dumpUserMappings(Archive *fout,
205 const char *servername, const char *namespace,
206 const char *owner, CatalogId catalogId, DumpId dumpId);
207 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
209 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
210 const char *type, const char *name, const char *subname,
211 const char *tag, const char *nspname, const char *owner,
214 static void getDependencies(Archive *fout);
215 static void BuildArchiveDependencies(Archive *fout);
216 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
217 DumpId **dependencies, int *nDeps, int *allocDeps);
219 static DumpableObject *createBoundaryObjects(void);
220 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
221 DumpableObject *boundaryObjs);
223 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
224 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
225 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
226 static void getTableDataFKConstraints(void);
227 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
228 static char *format_function_arguments_old(Archive *fout,
229 FuncInfo *finfo, int nallargs,
233 static char *format_function_signature(Archive *fout,
234 FuncInfo *finfo, bool honor_quotes);
235 static const char *convertRegProcReference(Archive *fout,
237 static const char *convertOperatorReference(Archive *fout, const char *opr);
238 static const char *convertTSFunction(Archive *fout, Oid funcOid);
239 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
240 static Oid findLastBuiltinOid_V70(Archive *fout);
241 static void selectSourceSchema(Archive *fout, const char *schemaName);
242 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
243 static char *myFormatType(const char *typname, int32 typmod);
244 static const char *fmtQualifiedId(Archive *fout,
245 const char *schema, const char *id);
246 static void getBlobs(Archive *fout);
247 static void dumpBlob(Archive *fout, BlobInfo *binfo);
248 static int dumpBlobs(Archive *fout, void *arg);
249 static void dumpDatabase(Archive *AH);
250 static void dumpEncoding(Archive *AH);
251 static void dumpStdStrings(Archive *AH);
252 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
253 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
254 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
255 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
256 static void binary_upgrade_set_pg_class_oids(Archive *fout,
257 PQExpBuffer upgrade_buffer,
258 Oid pg_class_oid, bool is_index);
259 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
260 DumpableObject *dobj,
261 const char *objlabel);
262 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
263 static const char *fmtCopyColumnList(const TableInfo *ti);
264 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
268 main(int argc, char **argv)
271 const char *filename = NULL;
272 const char *format = "p";
273 const char *dbname = NULL;
274 const char *pghost = NULL;
275 const char *pgport = NULL;
276 const char *username = NULL;
277 const char *dumpencoding = NULL;
281 DumpableObject **dobjs;
283 DumpableObject *boundaryObjs;
285 enum trivalue prompt_password = TRI_DEFAULT;
286 int compressLevel = -1;
289 int outputCreateDB = 0;
290 bool outputBlobs = false;
291 int outputNoOwner = 0;
292 char *outputSuperuser = NULL;
293 char *use_role = NULL;
296 RestoreOptions *ropt;
297 ArchiveFormat archiveFormat = archUnknown;
298 ArchiveMode archiveMode;
299 Archive *fout; /* the script file */
301 static int disable_triggers = 0;
302 static int outputNoTablespaces = 0;
303 static int use_setsessauth = 0;
305 static struct option long_options[] = {
306 {"data-only", no_argument, NULL, 'a'},
307 {"blobs", no_argument, NULL, 'b'},
308 {"clean", no_argument, NULL, 'c'},
309 {"create", no_argument, NULL, 'C'},
310 {"file", required_argument, NULL, 'f'},
311 {"format", required_argument, NULL, 'F'},
312 {"host", required_argument, NULL, 'h'},
313 {"ignore-version", no_argument, NULL, 'i'},
314 {"no-reconnect", no_argument, NULL, 'R'},
315 {"oids", no_argument, NULL, 'o'},
316 {"no-owner", no_argument, NULL, 'O'},
317 {"port", required_argument, NULL, 'p'},
318 {"schema", required_argument, NULL, 'n'},
319 {"exclude-schema", required_argument, NULL, 'N'},
320 {"schema-only", no_argument, NULL, 's'},
321 {"superuser", required_argument, NULL, 'S'},
322 {"table", required_argument, NULL, 't'},
323 {"exclude-table", required_argument, NULL, 'T'},
324 {"no-password", no_argument, NULL, 'w'},
325 {"password", no_argument, NULL, 'W'},
326 {"username", required_argument, NULL, 'U'},
327 {"verbose", no_argument, NULL, 'v'},
328 {"no-privileges", no_argument, NULL, 'x'},
329 {"no-acl", no_argument, NULL, 'x'},
330 {"compress", required_argument, NULL, 'Z'},
331 {"encoding", required_argument, NULL, 'E'},
332 {"help", no_argument, NULL, '?'},
333 {"version", no_argument, NULL, 'V'},
336 * the following options don't have an equivalent short option letter
338 {"attribute-inserts", no_argument, &column_inserts, 1},
339 {"binary-upgrade", no_argument, &binary_upgrade, 1},
340 {"column-inserts", no_argument, &column_inserts, 1},
341 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
342 {"disable-triggers", no_argument, &disable_triggers, 1},
343 {"exclude-table-data", required_argument, NULL, 4},
344 {"inserts", no_argument, &dump_inserts, 1},
345 {"lock-wait-timeout", required_argument, NULL, 2},
346 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
347 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
348 {"role", required_argument, NULL, 3},
349 {"section", required_argument, NULL, 5},
350 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
351 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
352 {"no-security-labels", no_argument, &no_security_labels, 1},
353 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
358 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
362 strcpy(g_comment_start, "-- ");
363 g_comment_end[0] = '\0';
364 strcpy(g_opaque_type, "opaque");
366 dataOnly = schemaOnly = false;
367 dumpSections = DUMP_UNSECTIONED;
368 lockWaitTimeout = NULL;
370 progname = get_progname(argv[0]);
372 /* Set default options based on progname */
373 if (strcmp(progname, "pg_backup") == 0)
378 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
383 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
385 puts("pg_dump (PostgreSQL) " PG_VERSION);
390 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
391 long_options, &optindex)) != -1)
395 case 'a': /* Dump data only */
399 case 'b': /* Dump blobs */
403 case 'c': /* clean (i.e., drop) schema prior to create */
407 case 'C': /* Create DB */
411 case 'E': /* Dump encoding */
412 dumpencoding = pg_strdup(optarg);
416 filename = pg_strdup(optarg);
420 format = pg_strdup(optarg);
423 case 'h': /* server host */
424 pghost = pg_strdup(optarg);
428 /* ignored, deprecated option */
431 case 'n': /* include schema(s) */
432 simple_string_list_append(&schema_include_patterns, optarg);
433 include_everything = false;
436 case 'N': /* exclude schema(s) */
437 simple_string_list_append(&schema_exclude_patterns, optarg);
440 case 'o': /* Dump oids */
444 case 'O': /* Don't reconnect to match owner */
448 case 'p': /* server port */
449 pgport = pg_strdup(optarg);
453 /* no-op, still accepted for backwards compatibility */
456 case 's': /* dump schema only */
460 case 'S': /* Username for superuser in plain text output */
461 outputSuperuser = pg_strdup(optarg);
464 case 't': /* include table(s) */
465 simple_string_list_append(&table_include_patterns, optarg);
466 include_everything = false;
469 case 'T': /* exclude table(s) */
470 simple_string_list_append(&table_exclude_patterns, optarg);
474 username = pg_strdup(optarg);
477 case 'v': /* verbose */
482 prompt_password = TRI_NO;
486 prompt_password = TRI_YES;
489 case 'x': /* skip ACL dump */
493 case 'Z': /* Compression Level */
494 compressLevel = atoi(optarg);
498 /* This covers the long options. */
501 case 2: /* lock-wait-timeout */
502 lockWaitTimeout = pg_strdup(optarg);
505 case 3: /* SET ROLE */
506 use_role = pg_strdup(optarg);
509 case 4: /* exclude table(s) data */
510 simple_string_list_append(&tabledata_exclude_patterns, optarg);
513 case 5: /* section */
514 set_dump_section(optarg, &dumpSections);
518 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
523 /* Get database name from command line */
525 dbname = argv[optind++];
527 /* Complain if any arguments remain */
530 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
531 progname, argv[optind]);
532 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
537 /* --column-inserts implies --inserts */
541 if (dataOnly && schemaOnly)
542 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
544 if (dataOnly && outputClean)
545 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
547 if (dump_inserts && oids)
549 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
550 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
554 /* Identify archive format to emit */
555 archiveFormat = parseArchiveFormat(format, &archiveMode);
557 /* archiveFormat specific setup */
558 if (archiveFormat == archNull)
561 /* Custom and directory formats are compressed by default, others not */
562 if (compressLevel == -1)
564 if (archiveFormat == archCustom || archiveFormat == archDirectory)
565 compressLevel = Z_DEFAULT_COMPRESSION;
570 /* Open the output file */
571 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
573 /* Register the cleanup hook */
574 on_exit_close_archive(fout);
577 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
579 /* Let the archiver know how noisy to be */
580 fout->verbose = g_verbose;
582 my_version = parse_version(PG_VERSION);
584 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
587 * We allow the server to be back to 7.0, and up to any minor release of
588 * our own major version. (See also version check in pg_dumpall.c.)
590 fout->minRemoteVersion = 70000;
591 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
594 * Open the database using the Archiver, so it knows about it. Errors mean
597 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
598 setup_connection(fout, dumpencoding, use_role);
601 * Disable security label support if server version < v9.1.x (prevents
602 * access to nonexistent pg_seclabel catalog)
604 if (fout->remoteVersion < 90100)
605 no_security_labels = 1;
608 * When running against 9.0 or later, check if we are in recovery mode,
609 * which means we are on a hot standby.
611 if (fout->remoteVersion >= 90000)
613 PGresult *res = ExecuteSqlQueryForSingleRow(fout, "SELECT pg_catalog.pg_is_in_recovery()");
614 if (strcmp(PQgetvalue(res, 0, 0), "t") == 0)
617 * On hot standby slaves, never try to dump unlogged table data,
618 * since it will just throw an error.
620 no_unlogged_table_data = true;
626 * Start transaction-snapshot mode transaction to dump consistent data.
628 ExecuteSqlStatement(fout, "BEGIN");
629 if (fout->remoteVersion >= 90100)
631 if (serializable_deferrable)
632 ExecuteSqlStatement(fout,
633 "SET TRANSACTION ISOLATION LEVEL "
634 "SERIALIZABLE, READ ONLY, DEFERRABLE");
636 ExecuteSqlStatement(fout,
637 "SET TRANSACTION ISOLATION LEVEL "
638 "REPEATABLE READ, READ ONLY");
640 else if (fout->remoteVersion >= 70400)
642 /* note: comma was not accepted in SET TRANSACTION before 8.0 */
643 ExecuteSqlStatement(fout,
644 "SET TRANSACTION ISOLATION LEVEL "
645 "SERIALIZABLE READ ONLY");
648 ExecuteSqlStatement(fout,
649 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
651 /* Select the appropriate subquery to convert user IDs to names */
652 if (fout->remoteVersion >= 80100)
653 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
654 else if (fout->remoteVersion >= 70300)
655 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
657 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
659 /* Find the last built-in OID, if needed */
660 if (fout->remoteVersion < 70300)
662 if (fout->remoteVersion >= 70100)
663 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
664 PQdb(GetConnection(fout)));
666 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
668 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
671 /* Expand schema selection patterns into OID lists */
672 if (schema_include_patterns.head != NULL)
674 expand_schema_name_patterns(fout, &schema_include_patterns,
675 &schema_include_oids);
676 if (schema_include_oids.head == NULL)
677 exit_horribly(NULL, "No matching schemas were found\n");
679 expand_schema_name_patterns(fout, &schema_exclude_patterns,
680 &schema_exclude_oids);
681 /* non-matching exclusion patterns aren't an error */
683 /* Expand table selection patterns into OID lists */
684 if (table_include_patterns.head != NULL)
686 expand_table_name_patterns(fout, &table_include_patterns,
687 &table_include_oids);
688 if (table_include_oids.head == NULL)
689 exit_horribly(NULL, "No matching tables were found\n");
691 expand_table_name_patterns(fout, &table_exclude_patterns,
692 &table_exclude_oids);
694 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
695 &tabledata_exclude_oids);
697 /* non-matching exclusion patterns aren't an error */
700 * Dumping blobs is now default unless we saw an inclusion switch or -s
701 * ... but even if we did see one of these, -b turns it back on.
703 if (include_everything && !schemaOnly)
707 * Now scan the database and create DumpableObject structs for all the
708 * objects we intend to dump.
710 tblinfo = getSchemaData(fout, &numTables);
712 if (fout->remoteVersion < 80400)
713 guessConstraintInheritance(tblinfo, numTables);
717 getTableData(tblinfo, numTables, oids);
719 getTableDataFKConstraints();
726 * Collect dependency data to assist in ordering the objects.
728 getDependencies(fout);
730 /* Lastly, create dummy objects to represent the section boundaries */
731 boundaryObjs = createBoundaryObjects();
733 /* Get pointers to all the known DumpableObjects */
734 getDumpableObjects(&dobjs, &numObjs);
737 * Add dummy dependencies to enforce the dump section ordering.
739 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
742 * Sort the objects into a safe dump order (no forward references).
744 * In 7.3 or later, we can rely on dependency information to help us
745 * determine a safe order, so the initial sort is mostly for cosmetic
746 * purposes: we sort by name to ensure that logically identical schemas
747 * will dump identically. Before 7.3 we don't have dependencies and we
748 * use OID ordering as an (unreliable) guide to creation order.
750 if (fout->remoteVersion >= 70300)
751 sortDumpableObjectsByTypeName(dobjs, numObjs);
753 sortDumpableObjectsByTypeOid(dobjs, numObjs);
755 sortDumpableObjects(dobjs, numObjs,
756 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
759 * Create archive TOC entries for all the objects to be dumped, in a safe
763 /* First the special ENCODING and STDSTRINGS entries. */
765 dumpStdStrings(fout);
767 /* The database item is always next, unless we don't want it at all */
768 if (include_everything && !dataOnly)
771 /* Now the rearrangeable objects. */
772 for (i = 0; i < numObjs; i++)
773 dumpDumpableObject(fout, dobjs[i]);
776 * Set up options info to ensure we dump what we want.
778 ropt = NewRestoreOptions();
779 ropt->filename = filename;
780 ropt->dropSchema = outputClean;
781 ropt->dataOnly = dataOnly;
782 ropt->schemaOnly = schemaOnly;
783 ropt->dumpSections = dumpSections;
784 ropt->aclsSkip = aclsSkip;
785 ropt->superuser = outputSuperuser;
786 ropt->createDB = outputCreateDB;
787 ropt->noOwner = outputNoOwner;
788 ropt->noTablespace = outputNoTablespaces;
789 ropt->disable_triggers = disable_triggers;
790 ropt->use_setsessauth = use_setsessauth;
792 if (compressLevel == -1)
793 ropt->compression = 0;
795 ropt->compression = compressLevel;
797 ropt->suppressDumpWarnings = true; /* We've already shown them */
799 SetArchiveRestoreOptions(fout, ropt);
802 * The archive's TOC entries are now marked as to which ones will
803 * actually be output, so we can set up their dependency lists properly.
804 * This isn't necessary for plain-text output, though.
807 BuildArchiveDependencies(fout);
810 * And finally we can do the actual output.
812 * Note: for non-plain-text output formats, the output file is written
813 * inside CloseArchive(). This is, um, bizarre; but not worth changing
817 RestoreArchive(fout);
826 help(const char *progname)
828 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
829 printf(_("Usage:\n"));
830 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
832 printf(_("\nGeneral options:\n"));
833 printf(_(" -f, --file=FILENAME output file or directory name\n"));
834 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
835 " plain text (default))\n"));
836 printf(_(" -v, --verbose verbose mode\n"));
837 printf(_(" -V, --version output version information, then exit\n"));
838 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
839 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
840 printf(_(" -?, --help show this help, then exit\n"));
842 printf(_("\nOptions controlling the output content:\n"));
843 printf(_(" -a, --data-only dump only the data, not the schema\n"));
844 printf(_(" -b, --blobs include large objects in dump\n"));
845 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
846 printf(_(" -C, --create include commands to create database in dump\n"));
847 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
848 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
849 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
850 printf(_(" -o, --oids include OIDs in dump\n"));
851 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
852 " plain-text format\n"));
853 printf(_(" -s, --schema-only dump only the schema, no data\n"));
854 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
855 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
856 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
857 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
858 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
859 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
860 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
861 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
862 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
863 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
864 printf(_(" --no-security-labels do not dump security label assignments\n"));
865 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
866 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
867 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
868 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
869 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
870 printf(_(" --use-set-session-authorization\n"
871 " use SET SESSION AUTHORIZATION commands instead of\n"
872 " ALTER OWNER commands to set ownership\n"));
874 printf(_("\nConnection options:\n"));
875 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
876 printf(_(" -p, --port=PORT database server port number\n"));
877 printf(_(" -U, --username=NAME connect as specified database user\n"));
878 printf(_(" -w, --no-password never prompt for password\n"));
879 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
880 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
882 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
883 "variable value is used.\n\n"));
884 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
888 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
890 PGconn *conn = GetConnection(AH);
891 const char *std_strings;
893 /* Set the client encoding if requested */
896 if (PQsetClientEncoding(conn, dumpencoding) < 0)
897 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
902 * Get the active encoding and the standard_conforming_strings setting, so
903 * we know how to escape strings.
905 AH->encoding = PQclientEncoding(conn);
907 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
908 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
910 /* Set the role if requested */
911 if (use_role && AH->remoteVersion >= 80100)
913 PQExpBuffer query = createPQExpBuffer();
915 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
916 ExecuteSqlStatement(AH, query->data);
917 destroyPQExpBuffer(query);
920 /* Set the datestyle to ISO to ensure the dump's portability */
921 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
923 /* Likewise, avoid using sql_standard intervalstyle */
924 if (AH->remoteVersion >= 80400)
925 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
928 * If supported, set extra_float_digits so that we can dump float data
929 * exactly (given correctly implemented float I/O code, anyway)
931 if (AH->remoteVersion >= 90000)
932 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
933 else if (AH->remoteVersion >= 70400)
934 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
937 * If synchronized scanning is supported, disable it, to prevent
938 * unpredictable changes in row ordering across a dump and reload.
940 if (AH->remoteVersion >= 80300)
941 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
944 * Disable timeouts if supported.
946 if (AH->remoteVersion >= 70300)
947 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
950 * Quote all identifiers, if requested.
952 if (quote_all_identifiers && AH->remoteVersion >= 90100)
953 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
957 parseArchiveFormat(const char *format, ArchiveMode *mode)
959 ArchiveFormat archiveFormat;
961 *mode = archModeWrite;
963 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
965 /* This is used by pg_dumpall, and is not documented */
966 archiveFormat = archNull;
967 *mode = archModeAppend;
969 else if (pg_strcasecmp(format, "c") == 0)
970 archiveFormat = archCustom;
971 else if (pg_strcasecmp(format, "custom") == 0)
972 archiveFormat = archCustom;
973 else if (pg_strcasecmp(format, "d") == 0)
974 archiveFormat = archDirectory;
975 else if (pg_strcasecmp(format, "directory") == 0)
976 archiveFormat = archDirectory;
977 else if (pg_strcasecmp(format, "p") == 0)
978 archiveFormat = archNull;
979 else if (pg_strcasecmp(format, "plain") == 0)
980 archiveFormat = archNull;
981 else if (pg_strcasecmp(format, "t") == 0)
982 archiveFormat = archTar;
983 else if (pg_strcasecmp(format, "tar") == 0)
984 archiveFormat = archTar;
986 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
987 return archiveFormat;
991 * Find the OIDs of all schemas matching the given list of patterns,
992 * and append them to the given OID list.
995 expand_schema_name_patterns(Archive *fout,
996 SimpleStringList *patterns,
1001 SimpleStringListCell *cell;
1004 if (patterns->head == NULL)
1005 return; /* nothing to do */
1007 if (fout->remoteVersion < 70300)
1008 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1010 query = createPQExpBuffer();
1013 * We use UNION ALL rather than UNION; this might sometimes result in
1014 * duplicate entries in the OID list, but we don't care.
1017 for (cell = patterns->head; cell; cell = cell->next)
1019 if (cell != patterns->head)
1020 appendPQExpBuffer(query, "UNION ALL\n");
1021 appendPQExpBuffer(query,
1022 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1023 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1024 false, NULL, "n.nspname", NULL, NULL);
1027 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1029 for (i = 0; i < PQntuples(res); i++)
1031 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1035 destroyPQExpBuffer(query);
1039 * Find the OIDs of all tables matching the given list of patterns,
1040 * and append them to the given OID list.
1043 expand_table_name_patterns(Archive *fout,
1044 SimpleStringList *patterns, SimpleOidList *oids)
1048 SimpleStringListCell *cell;
1051 if (patterns->head == NULL)
1052 return; /* nothing to do */
1054 query = createPQExpBuffer();
1057 * We use UNION ALL rather than UNION; this might sometimes result in
1058 * duplicate entries in the OID list, but we don't care.
1061 for (cell = patterns->head; cell; cell = cell->next)
1063 if (cell != patterns->head)
1064 appendPQExpBuffer(query, "UNION ALL\n");
1065 appendPQExpBuffer(query,
1067 "\nFROM pg_catalog.pg_class c"
1068 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1069 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1070 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1071 RELKIND_FOREIGN_TABLE);
1072 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1073 false, "n.nspname", "c.relname", NULL,
1074 "pg_catalog.pg_table_is_visible(c.oid)");
1077 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1079 for (i = 0; i < PQntuples(res); i++)
1081 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1085 destroyPQExpBuffer(query);
1089 * selectDumpableNamespace: policy-setting subroutine
1090 * Mark a namespace as to be dumped or not
1093 selectDumpableNamespace(NamespaceInfo *nsinfo)
1096 * If specific tables are being dumped, do not dump any complete
1097 * namespaces. If specific namespaces are being dumped, dump just those
1098 * namespaces. Otherwise, dump all non-system namespaces.
1100 if (table_include_oids.head != NULL)
1101 nsinfo->dobj.dump = false;
1102 else if (schema_include_oids.head != NULL)
1103 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1104 nsinfo->dobj.catId.oid);
1105 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1106 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1107 nsinfo->dobj.dump = false;
1109 nsinfo->dobj.dump = true;
1112 * In any case, a namespace can be excluded by an exclusion switch
1114 if (nsinfo->dobj.dump &&
1115 simple_oid_list_member(&schema_exclude_oids,
1116 nsinfo->dobj.catId.oid))
1117 nsinfo->dobj.dump = false;
1121 * selectDumpableTable: policy-setting subroutine
1122 * Mark a table as to be dumped or not
1125 selectDumpableTable(TableInfo *tbinfo)
1128 * If specific tables are being dumped, dump just those tables; else, dump
1129 * according to the parent namespace's dump flag.
1131 if (table_include_oids.head != NULL)
1132 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1133 tbinfo->dobj.catId.oid);
1135 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1138 * In any case, a table can be excluded by an exclusion switch
1140 if (tbinfo->dobj.dump &&
1141 simple_oid_list_member(&table_exclude_oids,
1142 tbinfo->dobj.catId.oid))
1143 tbinfo->dobj.dump = false;
1147 * selectDumpableType: policy-setting subroutine
1148 * Mark a type as to be dumped or not
1150 * If it's a table's rowtype or an autogenerated array type, we also apply a
1151 * special type code to facilitate sorting into the desired order. (We don't
1152 * want to consider those to be ordinary types because that would bring tables
1153 * up into the datatype part of the dump order.) We still set the object's
1154 * dump flag; that's not going to cause the dummy type to be dumped, but we
1155 * need it so that casts involving such types will be dumped correctly -- see
1156 * dumpCast. This means the flag should be set the same as for the underlying
1157 * object (the table or base type).
1160 selectDumpableType(TypeInfo *tyinfo)
1162 /* skip complex types, except for standalone composite types */
1163 if (OidIsValid(tyinfo->typrelid) &&
1164 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1166 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1168 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1169 if (tytable != NULL)
1170 tyinfo->dobj.dump = tytable->dobj.dump;
1172 tyinfo->dobj.dump = false;
1176 /* skip auto-generated array types */
1177 if (tyinfo->isArray)
1179 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1182 * Fall through to set the dump flag; we assume that the subsequent
1183 * rules will do the same thing as they would for the array's base
1184 * type. (We cannot reliably look up the base type here, since
1185 * getTypes may not have processed it yet.)
1189 /* dump only types in dumpable namespaces */
1190 if (!tyinfo->dobj.namespace->dobj.dump)
1191 tyinfo->dobj.dump = false;
1193 /* skip undefined placeholder types */
1194 else if (!tyinfo->isDefined)
1195 tyinfo->dobj.dump = false;
1198 tyinfo->dobj.dump = true;
1202 * selectDumpableDefaultACL: policy-setting subroutine
1203 * Mark a default ACL as to be dumped or not
1205 * For per-schema default ACLs, dump if the schema is to be dumped.
1206 * Otherwise dump if we are dumping "everything". Note that dataOnly
1207 * and aclsSkip are checked separately.
1210 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1212 if (dinfo->dobj.namespace)
1213 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1215 dinfo->dobj.dump = include_everything;
1219 * selectDumpableExtension: policy-setting subroutine
1220 * Mark an extension as to be dumped or not
1222 * Normally, we dump all extensions, or none of them if include_everything
1223 * is false (i.e., a --schema or --table switch was given). However, in
1224 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1225 * assume those will already be installed in the target database. We identify
1226 * such extensions by their having OIDs in the range reserved for initdb.
1229 selectDumpableExtension(ExtensionInfo *extinfo)
1231 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1232 extinfo->dobj.dump = false;
1234 extinfo->dobj.dump = include_everything;
1238 * selectDumpableObject: policy-setting subroutine
1239 * Mark a generic dumpable object as to be dumped or not
1241 * Use this only for object types without a special-case routine above.
1244 selectDumpableObject(DumpableObject *dobj)
1247 * Default policy is to dump if parent namespace is dumpable, or always
1248 * for non-namespace-associated items.
1250 if (dobj->namespace)
1251 dobj->dump = dobj->namespace->dobj.dump;
1257 * Dump a table's contents for loading using the COPY command
1258 * - this routine is called by the Archiver when it wants the table
1263 dumpTableData_copy(Archive *fout, void *dcontext)
1265 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1266 TableInfo *tbinfo = tdinfo->tdtable;
1267 const char *classname = tbinfo->dobj.name;
1268 const bool hasoids = tbinfo->hasoids;
1269 const bool oids = tdinfo->oids;
1270 PQExpBuffer q = createPQExpBuffer();
1271 PGconn *conn = GetConnection(fout);
1275 const char *column_list;
1278 write_msg(NULL, "dumping contents of table %s\n", classname);
1281 * Make sure we are in proper schema. We will qualify the table name
1282 * below anyway (in case its name conflicts with a pg_catalog table); but
1283 * this ensures reproducible results in case the table contains regproc,
1284 * regclass, etc columns.
1286 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1289 * If possible, specify the column list explicitly so that we have no
1290 * possibility of retrieving data in the wrong column order. (The default
1291 * column ordering of COPY will not be what we want in certain corner
1292 * cases involving ADD COLUMN and inheritance.)
1294 if (fout->remoteVersion >= 70300)
1295 column_list = fmtCopyColumnList(tbinfo);
1297 column_list = ""; /* can't select columns in COPY */
1299 if (oids && hasoids)
1301 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1302 fmtQualifiedId(fout,
1303 tbinfo->dobj.namespace->dobj.name,
1307 else if (tdinfo->filtercond)
1309 /* Note: this syntax is only supported in 8.2 and up */
1310 appendPQExpBufferStr(q, "COPY (SELECT ");
1311 /* klugery to get rid of parens in column list */
1312 if (strlen(column_list) > 2)
1314 appendPQExpBufferStr(q, column_list + 1);
1315 q->data[q->len - 1] = ' ';
1318 appendPQExpBufferStr(q, "* ");
1319 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1320 fmtQualifiedId(fout,
1321 tbinfo->dobj.namespace->dobj.name,
1323 tdinfo->filtercond);
1327 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1328 fmtQualifiedId(fout,
1329 tbinfo->dobj.namespace->dobj.name,
1333 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1338 ret = PQgetCopyData(conn, ©buf, 0);
1341 break; /* done or error */
1345 WriteData(fout, copybuf, ret);
1352 * There was considerable discussion in late July, 2000 regarding
1353 * slowing down pg_dump when backing up large tables. Users with both
1354 * slow & fast (multi-processor) machines experienced performance
1355 * degradation when doing a backup.
1357 * Initial attempts based on sleeping for a number of ms for each ms
1358 * of work were deemed too complex, then a simple 'sleep in each loop'
1359 * implementation was suggested. The latter failed because the loop
1360 * was too tight. Finally, the following was implemented:
1362 * If throttle is non-zero, then
1363 * See how long since the last sleep.
1364 * Work out how long to sleep (based on ratio).
1365 * If sleep is more than 100ms, then
1371 * where the throttle value was the number of ms to sleep per ms of
1372 * work. The calculation was done in each loop.
1374 * Most of the hard work is done in the backend, and this solution
1375 * still did not work particularly well: on slow machines, the ratio
1376 * was 50:1, and on medium paced machines, 1:1, and on fast
1377 * multi-processor machines, it had little or no effect, for reasons
1378 * that were unclear.
1380 * Further discussion ensued, and the proposal was dropped.
1382 * For those people who want this feature, it can be implemented using
1383 * gettimeofday in each loop, calculating the time since last sleep,
1384 * multiplying that by the sleep ratio, then if the result is more
1385 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1386 * function to sleep for a subsecond period ie.
1388 * select(0, NULL, NULL, NULL, &tvi);
1390 * This will return after the interval specified in the structure tvi.
1391 * Finally, call gettimeofday again to save the 'last sleep time'.
1395 archprintf(fout, "\\.\n\n\n");
1399 /* copy data transfer failed */
1400 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1401 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1402 write_msg(NULL, "The command was: %s\n", q->data);
1406 /* Check command status and return to normal libpq state */
1407 res = PQgetResult(conn);
1408 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1410 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1411 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1412 write_msg(NULL, "The command was: %s\n", q->data);
1417 destroyPQExpBuffer(q);
1422 * Dump table data using INSERT commands.
1424 * Caution: when we restore from an archive file direct to database, the
1425 * INSERT commands emitted by this function have to be parsed by
1426 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1427 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1430 dumpTableData_insert(Archive *fout, void *dcontext)
1432 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1433 TableInfo *tbinfo = tdinfo->tdtable;
1434 const char *classname = tbinfo->dobj.name;
1435 PQExpBuffer q = createPQExpBuffer();
1442 * Make sure we are in proper schema. We will qualify the table name
1443 * below anyway (in case its name conflicts with a pg_catalog table); but
1444 * this ensures reproducible results in case the table contains regproc,
1445 * regclass, etc columns.
1447 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1449 if (fout->remoteVersion >= 70100)
1451 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1452 "SELECT * FROM ONLY %s",
1453 fmtQualifiedId(fout,
1454 tbinfo->dobj.namespace->dobj.name,
1459 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1461 fmtQualifiedId(fout,
1462 tbinfo->dobj.namespace->dobj.name,
1465 if (tdinfo->filtercond)
1466 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1468 ExecuteSqlStatement(fout, q->data);
1472 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1474 nfields = PQnfields(res);
1475 for (tuple = 0; tuple < PQntuples(res); tuple++)
1477 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1480 /* corner case for zero-column table */
1481 archprintf(fout, "DEFAULT VALUES;\n");
1486 resetPQExpBuffer(q);
1487 appendPQExpBuffer(q, "(");
1488 for (field = 0; field < nfields; field++)
1491 appendPQExpBuffer(q, ", ");
1492 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1494 appendPQExpBuffer(q, ") ");
1495 archputs(q->data, fout);
1497 archprintf(fout, "VALUES (");
1498 for (field = 0; field < nfields; field++)
1501 archprintf(fout, ", ");
1502 if (PQgetisnull(res, tuple, field))
1504 archprintf(fout, "NULL");
1508 /* XXX This code is partially duplicated in ruleutils.c */
1509 switch (PQftype(res, field))
1520 * These types are printed without quotes unless
1521 * they contain values that aren't accepted by the
1522 * scanner unquoted (e.g., 'NaN'). Note that
1523 * strtod() and friends might accept NaN, so we
1524 * can't use that to test.
1526 * In reality we only need to defend against
1527 * infinity and NaN, so we need not get too crazy
1528 * about pattern matching here.
1530 const char *s = PQgetvalue(res, tuple, field);
1532 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1533 archprintf(fout, "%s", s);
1535 archprintf(fout, "'%s'", s);
1541 archprintf(fout, "B'%s'",
1542 PQgetvalue(res, tuple, field));
1546 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1547 archprintf(fout, "true");
1549 archprintf(fout, "false");
1553 /* All other types are printed as string literals. */
1554 resetPQExpBuffer(q);
1555 appendStringLiteralAH(q,
1556 PQgetvalue(res, tuple, field),
1558 archputs(q->data, fout);
1562 archprintf(fout, ");\n");
1565 if (PQntuples(res) <= 0)
1573 archprintf(fout, "\n\n");
1575 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1577 destroyPQExpBuffer(q);
1584 * dump the contents of a single table
1586 * Actually, this just makes an ArchiveEntry for the table contents.
1589 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1591 TableInfo *tbinfo = tdinfo->tdtable;
1592 PQExpBuffer copyBuf = createPQExpBuffer();
1593 DataDumperPtr dumpFn;
1598 /* Dump/restore using COPY */
1599 dumpFn = dumpTableData_copy;
1600 /* must use 2 steps here 'cause fmtId is nonreentrant */
1601 appendPQExpBuffer(copyBuf, "COPY %s ",
1602 fmtId(tbinfo->dobj.name));
1603 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1604 fmtCopyColumnList(tbinfo),
1605 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1606 copyStmt = copyBuf->data;
1610 /* Restore using INSERT */
1611 dumpFn = dumpTableData_insert;
1616 * Note: although the TableDataInfo is a full DumpableObject, we treat its
1617 * dependency on its table as "special" and pass it to ArchiveEntry now.
1618 * See comments for BuildArchiveDependencies.
1620 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1621 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1622 NULL, tbinfo->rolname,
1623 false, "TABLE DATA", SECTION_DATA,
1625 &(tbinfo->dobj.dumpId), 1,
1628 destroyPQExpBuffer(copyBuf);
1633 * set up dumpable objects representing the contents of tables
1636 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1640 for (i = 0; i < numTables; i++)
1642 if (tblinfo[i].dobj.dump)
1643 makeTableDataInfo(&(tblinfo[i]), oids);
1648 * Make a dumpable object for the data of this specific table
1650 * Note: we make a TableDataInfo if and only if we are going to dump the
1651 * table data; the "dump" flag in such objects isn't used.
1654 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1656 TableDataInfo *tdinfo;
1659 * Nothing to do if we already decided to dump the table. This will
1660 * happen for "config" tables.
1662 if (tbinfo->dataObj != NULL)
1665 /* Skip VIEWs (no data to dump) */
1666 if (tbinfo->relkind == RELKIND_VIEW)
1668 /* Skip FOREIGN TABLEs (no data to dump) */
1669 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1672 /* Don't dump data in unlogged tables, if so requested */
1673 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1674 no_unlogged_table_data)
1677 /* Check that the data is not explicitly excluded */
1678 if (simple_oid_list_member(&tabledata_exclude_oids,
1679 tbinfo->dobj.catId.oid))
1682 /* OK, let's dump it */
1683 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1685 tdinfo->dobj.objType = DO_TABLE_DATA;
1688 * Note: use tableoid 0 so that this object won't be mistaken for
1689 * something that pg_depend entries apply to.
1691 tdinfo->dobj.catId.tableoid = 0;
1692 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1693 AssignDumpId(&tdinfo->dobj);
1694 tdinfo->dobj.name = tbinfo->dobj.name;
1695 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1696 tdinfo->tdtable = tbinfo;
1697 tdinfo->oids = oids;
1698 tdinfo->filtercond = NULL; /* might get set later */
1699 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1701 tbinfo->dataObj = tdinfo;
1705 * getTableDataFKConstraints -
1706 * add dump-order dependencies reflecting foreign key constraints
1708 * This code is executed only in a data-only dump --- in schema+data dumps
1709 * we handle foreign key issues by not creating the FK constraints until
1710 * after the data is loaded. In a data-only dump, however, we want to
1711 * order the table data objects in such a way that a table's referenced
1712 * tables are restored first. (In the presence of circular references or
1713 * self-references this may be impossible; we'll detect and complain about
1714 * that during the dependency sorting step.)
1717 getTableDataFKConstraints(void)
1719 DumpableObject **dobjs;
1723 /* Search through all the dumpable objects for FK constraints */
1724 getDumpableObjects(&dobjs, &numObjs);
1725 for (i = 0; i < numObjs; i++)
1727 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1729 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1732 /* Not interesting unless both tables are to be dumped */
1733 if (cinfo->contable == NULL ||
1734 cinfo->contable->dataObj == NULL)
1736 ftable = findTableByOid(cinfo->confrelid);
1737 if (ftable == NULL ||
1738 ftable->dataObj == NULL)
1742 * Okay, make referencing table's TABLE_DATA object depend on the
1743 * referenced table's TABLE_DATA object.
1745 addObjectDependency(&cinfo->contable->dataObj->dobj,
1746 ftable->dataObj->dobj.dumpId);
1754 * guessConstraintInheritance:
1755 * In pre-8.4 databases, we can't tell for certain which constraints
1756 * are inherited. We assume a CHECK constraint is inherited if its name
1757 * matches the name of any constraint in the parent. Originally this code
1758 * tried to compare the expression texts, but that can fail for various
1759 * reasons --- for example, if the parent and child tables are in different
1760 * schemas, reverse-listing of function calls may produce different text
1761 * (schema-qualified or not) depending on search path.
1763 * In 8.4 and up we can rely on the conislocal field to decide which
1764 * constraints must be dumped; much safer.
1766 * This function assumes all conislocal flags were initialized to TRUE.
1767 * It clears the flag on anything that seems to be inherited.
1770 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1776 for (i = 0; i < numTables; i++)
1778 TableInfo *tbinfo = &(tblinfo[i]);
1780 TableInfo **parents;
1783 /* Sequences and views never have parents */
1784 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1785 tbinfo->relkind == RELKIND_VIEW)
1788 /* Don't bother computing anything for non-target tables, either */
1789 if (!tbinfo->dobj.dump)
1792 numParents = tbinfo->numParents;
1793 parents = tbinfo->parents;
1795 if (numParents == 0)
1796 continue; /* nothing to see here, move along */
1798 /* scan for inherited CHECK constraints */
1799 for (j = 0; j < tbinfo->ncheck; j++)
1801 ConstraintInfo *constr;
1803 constr = &(tbinfo->checkexprs[j]);
1805 for (k = 0; k < numParents; k++)
1809 parent = parents[k];
1810 for (l = 0; l < parent->ncheck; l++)
1812 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1814 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1816 constr->conislocal = false;
1820 if (!constr->conislocal)
1830 * dump the database definition
1833 dumpDatabase(Archive *fout)
1835 PQExpBuffer dbQry = createPQExpBuffer();
1836 PQExpBuffer delQry = createPQExpBuffer();
1837 PQExpBuffer creaQry = createPQExpBuffer();
1838 PGconn *conn = GetConnection(fout);
1850 const char *datname,
1858 datname = PQdb(conn);
1861 write_msg(NULL, "saving database definition\n");
1863 /* Make sure we are in proper schema */
1864 selectSourceSchema(fout, "pg_catalog");
1866 /* Get the database owner and parameters from pg_database */
1867 if (fout->remoteVersion >= 80400)
1869 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1870 "(%s datdba) AS dba, "
1871 "pg_encoding_to_char(encoding) AS encoding, "
1872 "datcollate, datctype, datfrozenxid, "
1873 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1874 "shobj_description(oid, 'pg_database') AS description "
1879 appendStringLiteralAH(dbQry, datname, fout);
1881 else if (fout->remoteVersion >= 80200)
1883 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1884 "(%s datdba) AS dba, "
1885 "pg_encoding_to_char(encoding) AS encoding, "
1886 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1887 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1888 "shobj_description(oid, 'pg_database') AS description "
1893 appendStringLiteralAH(dbQry, datname, fout);
1895 else if (fout->remoteVersion >= 80000)
1897 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1898 "(%s datdba) AS dba, "
1899 "pg_encoding_to_char(encoding) AS encoding, "
1900 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1901 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1905 appendStringLiteralAH(dbQry, datname, fout);
1907 else if (fout->remoteVersion >= 70100)
1909 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1910 "(%s datdba) AS dba, "
1911 "pg_encoding_to_char(encoding) AS encoding, "
1912 "NULL AS datcollate, NULL AS datctype, "
1913 "0 AS datfrozenxid, "
1914 "NULL AS tablespace "
1918 appendStringLiteralAH(dbQry, datname, fout);
1922 appendPQExpBuffer(dbQry, "SELECT "
1923 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1925 "(%s datdba) AS dba, "
1926 "pg_encoding_to_char(encoding) AS encoding, "
1927 "NULL AS datcollate, NULL AS datctype, "
1928 "0 AS datfrozenxid, "
1929 "NULL AS tablespace "
1933 appendStringLiteralAH(dbQry, datname, fout);
1936 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
1938 i_tableoid = PQfnumber(res, "tableoid");
1939 i_oid = PQfnumber(res, "oid");
1940 i_dba = PQfnumber(res, "dba");
1941 i_encoding = PQfnumber(res, "encoding");
1942 i_collate = PQfnumber(res, "datcollate");
1943 i_ctype = PQfnumber(res, "datctype");
1944 i_frozenxid = PQfnumber(res, "datfrozenxid");
1945 i_tablespace = PQfnumber(res, "tablespace");
1947 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1948 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1949 dba = PQgetvalue(res, 0, i_dba);
1950 encoding = PQgetvalue(res, 0, i_encoding);
1951 collate = PQgetvalue(res, 0, i_collate);
1952 ctype = PQgetvalue(res, 0, i_ctype);
1953 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1954 tablespace = PQgetvalue(res, 0, i_tablespace);
1956 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1958 if (strlen(encoding) > 0)
1960 appendPQExpBuffer(creaQry, " ENCODING = ");
1961 appendStringLiteralAH(creaQry, encoding, fout);
1963 if (strlen(collate) > 0)
1965 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1966 appendStringLiteralAH(creaQry, collate, fout);
1968 if (strlen(ctype) > 0)
1970 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1971 appendStringLiteralAH(creaQry, ctype, fout);
1973 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1974 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1976 appendPQExpBuffer(creaQry, ";\n");
1980 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1981 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1982 "SET datfrozenxid = '%u'\n"
1985 appendStringLiteralAH(creaQry, datname, fout);
1986 appendPQExpBuffer(creaQry, ";\n");
1990 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1993 dbDumpId = createDumpId();
1996 dbCatId, /* catalog ID */
1997 dbDumpId, /* dump ID */
1999 NULL, /* Namespace */
2000 NULL, /* Tablespace */
2002 false, /* with oids */
2003 "DATABASE", /* Desc */
2004 SECTION_PRE_DATA, /* Section */
2005 creaQry->data, /* Create */
2006 delQry->data, /* Del */
2011 NULL); /* Dumper Arg */
2014 * pg_largeobject and pg_largeobject_metadata come from the old system
2015 * intact, so set their relfrozenxids.
2020 PQExpBuffer loFrozenQry = createPQExpBuffer();
2021 PQExpBuffer loOutQry = createPQExpBuffer();
2027 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2028 "FROM pg_catalog.pg_class\n"
2029 "WHERE oid = %u;\n",
2030 LargeObjectRelationId);
2032 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2034 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2036 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2037 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2038 "SET relfrozenxid = '%u'\n"
2039 "WHERE oid = %u;\n",
2040 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2041 LargeObjectRelationId);
2042 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2043 "pg_largeobject", NULL, NULL, "",
2044 false, "pg_largeobject", SECTION_PRE_DATA,
2045 loOutQry->data, "", NULL,
2052 * pg_largeobject_metadata
2054 if (fout->remoteVersion >= 90000)
2056 resetPQExpBuffer(loFrozenQry);
2057 resetPQExpBuffer(loOutQry);
2059 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2060 "FROM pg_catalog.pg_class\n"
2061 "WHERE oid = %u;\n",
2062 LargeObjectMetadataRelationId);
2064 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2066 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2068 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2069 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2070 "SET relfrozenxid = '%u'\n"
2071 "WHERE oid = %u;\n",
2072 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2073 LargeObjectMetadataRelationId);
2074 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2075 "pg_largeobject_metadata", NULL, NULL, "",
2076 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2077 loOutQry->data, "", NULL,
2084 destroyPQExpBuffer(loFrozenQry);
2085 destroyPQExpBuffer(loOutQry);
2088 /* Dump DB comment if any */
2089 if (fout->remoteVersion >= 80200)
2092 * 8.2 keeps comments on shared objects in a shared table, so we
2093 * cannot use the dumpComment used for other database objects.
2095 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2097 if (comment && strlen(comment))
2099 resetPQExpBuffer(dbQry);
2102 * Generates warning when loaded into a differently-named
2105 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2106 appendStringLiteralAH(dbQry, comment, fout);
2107 appendPQExpBuffer(dbQry, ";\n");
2109 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2110 dba, false, "COMMENT", SECTION_NONE,
2111 dbQry->data, "", NULL,
2112 &dbDumpId, 1, NULL, NULL);
2117 resetPQExpBuffer(dbQry);
2118 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2119 dumpComment(fout, dbQry->data, NULL, "",
2120 dbCatId, 0, dbDumpId);
2125 /* Dump shared security label. */
2126 if (!no_security_labels && fout->remoteVersion >= 90200)
2128 PQExpBuffer seclabelQry = createPQExpBuffer();
2130 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2131 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2132 resetPQExpBuffer(seclabelQry);
2133 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2134 if (strlen(seclabelQry->data))
2135 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2136 dba, false, "SECURITY LABEL", SECTION_NONE,
2137 seclabelQry->data, "", NULL,
2138 &dbDumpId, 1, NULL, NULL);
2139 destroyPQExpBuffer(seclabelQry);
2142 destroyPQExpBuffer(dbQry);
2143 destroyPQExpBuffer(delQry);
2144 destroyPQExpBuffer(creaQry);
2149 * dumpEncoding: put the correct encoding into the archive
2152 dumpEncoding(Archive *AH)
2154 const char *encname = pg_encoding_to_char(AH->encoding);
2155 PQExpBuffer qry = createPQExpBuffer();
2158 write_msg(NULL, "saving encoding = %s\n", encname);
2160 appendPQExpBuffer(qry, "SET client_encoding = ");
2161 appendStringLiteralAH(qry, encname, AH);
2162 appendPQExpBuffer(qry, ";\n");
2164 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2165 "ENCODING", NULL, NULL, "",
2166 false, "ENCODING", SECTION_PRE_DATA,
2167 qry->data, "", NULL,
2171 destroyPQExpBuffer(qry);
2176 * dumpStdStrings: put the correct escape string behavior into the archive
2179 dumpStdStrings(Archive *AH)
2181 const char *stdstrings = AH->std_strings ? "on" : "off";
2182 PQExpBuffer qry = createPQExpBuffer();
2185 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2188 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2191 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2192 "STDSTRINGS", NULL, NULL, "",
2193 false, "STDSTRINGS", SECTION_PRE_DATA,
2194 qry->data, "", NULL,
2198 destroyPQExpBuffer(qry);
2204 * Collect schema-level data about large objects
2207 getBlobs(Archive *fout)
2209 PQExpBuffer blobQry = createPQExpBuffer();
2211 DumpableObject *bdata;
2216 /* Verbose message */
2218 write_msg(NULL, "reading large objects\n");
2220 /* Make sure we are in proper schema */
2221 selectSourceSchema(fout, "pg_catalog");
2223 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2224 if (fout->remoteVersion >= 90000)
2225 appendPQExpBuffer(blobQry,
2226 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2227 " FROM pg_largeobject_metadata",
2229 else if (fout->remoteVersion >= 70100)
2230 appendPQExpBuffer(blobQry,
2231 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2232 " FROM pg_largeobject");
2234 appendPQExpBuffer(blobQry,
2235 "SELECT oid, NULL::oid, NULL::oid"
2236 " FROM pg_class WHERE relkind = 'l'");
2238 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2240 ntups = PQntuples(res);
2244 * Each large object has its own BLOB archive entry.
2246 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2248 for (i = 0; i < ntups; i++)
2250 binfo[i].dobj.objType = DO_BLOB;
2251 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2252 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2253 AssignDumpId(&binfo[i].dobj);
2255 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2256 if (!PQgetisnull(res, i, 1))
2257 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2259 binfo[i].rolname = "";
2260 if (!PQgetisnull(res, i, 2))
2261 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2263 binfo[i].blobacl = NULL;
2267 * If we have any large objects, a "BLOBS" archive entry is needed.
2268 * This is just a placeholder for sorting; it carries no data now.
2270 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2271 bdata->objType = DO_BLOB_DATA;
2272 bdata->catId = nilCatalogId;
2273 AssignDumpId(bdata);
2274 bdata->name = pg_strdup("BLOBS");
2278 destroyPQExpBuffer(blobQry);
2284 * dump the definition (metadata) of the given large object
2287 dumpBlob(Archive *fout, BlobInfo *binfo)
2289 PQExpBuffer cquery = createPQExpBuffer();
2290 PQExpBuffer dquery = createPQExpBuffer();
2292 appendPQExpBuffer(cquery,
2293 "SELECT pg_catalog.lo_create('%s');\n",
2296 appendPQExpBuffer(dquery,
2297 "SELECT pg_catalog.lo_unlink('%s');\n",
2300 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2303 binfo->rolname, false,
2304 "BLOB", SECTION_PRE_DATA,
2305 cquery->data, dquery->data, NULL,
2309 /* set up tag for comment and/or ACL */
2310 resetPQExpBuffer(cquery);
2311 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2313 /* Dump comment if any */
2314 dumpComment(fout, cquery->data,
2315 NULL, binfo->rolname,
2316 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2318 /* Dump security label if any */
2319 dumpSecLabel(fout, cquery->data,
2320 NULL, binfo->rolname,
2321 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2323 /* Dump ACL if any */
2325 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2326 binfo->dobj.name, NULL, cquery->data,
2327 NULL, binfo->rolname, binfo->blobacl);
2329 destroyPQExpBuffer(cquery);
2330 destroyPQExpBuffer(dquery);
2335 * dump the data contents of all large objects
2338 dumpBlobs(Archive *fout, void *arg)
2340 const char *blobQry;
2341 const char *blobFetchQry;
2342 PGconn *conn = GetConnection(fout);
2344 char buf[LOBBUFSIZE];
2350 write_msg(NULL, "saving large objects\n");
2352 /* Make sure we are in proper schema */
2353 selectSourceSchema(fout, "pg_catalog");
2356 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2357 * the already-in-memory dumpable objects instead...
2359 if (fout->remoteVersion >= 90000)
2360 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2361 else if (fout->remoteVersion >= 70100)
2362 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2364 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2366 ExecuteSqlStatement(fout, blobQry);
2368 /* Command to fetch from cursor */
2369 blobFetchQry = "FETCH 1000 IN bloboid";
2374 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2376 /* Process the tuples, if any */
2377 ntups = PQntuples(res);
2378 for (i = 0; i < ntups; i++)
2383 blobOid = atooid(PQgetvalue(res, i, 0));
2385 loFd = lo_open(conn, blobOid, INV_READ);
2387 exit_horribly(NULL, "could not open large object %u: %s",
2388 blobOid, PQerrorMessage(conn));
2390 StartBlob(fout, blobOid);
2392 /* Now read it in chunks, sending data to archive */
2395 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2397 exit_horribly(NULL, "error reading large object %u: %s",
2398 blobOid, PQerrorMessage(conn));
2400 WriteData(fout, buf, cnt);
2403 lo_close(conn, loFd);
2405 EndBlob(fout, blobOid);
2409 } while (ntups > 0);
2415 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2416 PQExpBuffer upgrade_buffer,
2419 PQExpBuffer upgrade_query = createPQExpBuffer();
2420 PGresult *upgrade_res;
2421 Oid pg_type_array_oid;
2423 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2424 appendPQExpBuffer(upgrade_buffer,
2425 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2428 /* we only support old >= 8.3 for binary upgrades */
2429 appendPQExpBuffer(upgrade_query,
2431 "FROM pg_catalog.pg_type "
2432 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2435 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2437 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2439 if (OidIsValid(pg_type_array_oid))
2441 appendPQExpBuffer(upgrade_buffer,
2442 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2443 appendPQExpBuffer(upgrade_buffer,
2444 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2448 PQclear(upgrade_res);
2449 destroyPQExpBuffer(upgrade_query);
2453 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2454 PQExpBuffer upgrade_buffer,
2457 PQExpBuffer upgrade_query = createPQExpBuffer();
2458 PGresult *upgrade_res;
2460 bool toast_set = false;
2462 /* we only support old >= 8.3 for binary upgrades */
2463 appendPQExpBuffer(upgrade_query,
2464 "SELECT c.reltype AS crel, t.reltype AS trel "
2465 "FROM pg_catalog.pg_class c "
2466 "LEFT JOIN pg_catalog.pg_class t ON "
2467 " (c.reltoastrelid = t.oid) "
2468 "WHERE c.oid = '%u'::pg_catalog.oid;",
2471 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2473 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2475 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2478 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2480 /* Toast tables do not have pg_type array rows */
2481 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2482 PQfnumber(upgrade_res, "trel")));
2484 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2485 appendPQExpBuffer(upgrade_buffer,
2486 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2492 PQclear(upgrade_res);
2493 destroyPQExpBuffer(upgrade_query);
2499 binary_upgrade_set_pg_class_oids(Archive *fout,
2500 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2503 PQExpBuffer upgrade_query = createPQExpBuffer();
2504 PGresult *upgrade_res;
2505 Oid pg_class_reltoastrelid;
2506 Oid pg_class_reltoastidxid;
2508 appendPQExpBuffer(upgrade_query,
2509 "SELECT c.reltoastrelid, t.reltoastidxid "
2510 "FROM pg_catalog.pg_class c LEFT JOIN "
2511 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2512 "WHERE c.oid = '%u'::pg_catalog.oid;",
2515 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2517 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2518 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2520 appendPQExpBuffer(upgrade_buffer,
2521 "\n-- For binary upgrade, must preserve pg_class oids\n");
2525 appendPQExpBuffer(upgrade_buffer,
2526 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2528 /* only tables have toast tables, not indexes */
2529 if (OidIsValid(pg_class_reltoastrelid))
2532 * One complexity is that the table definition might not require
2533 * the creation of a TOAST table, and the TOAST table might have
2534 * been created long after table creation, when the table was
2535 * loaded with wide data. By setting the TOAST oid we force
2536 * creation of the TOAST heap and TOAST index by the backend so we
2537 * can cleanly copy the files during binary upgrade.
2540 appendPQExpBuffer(upgrade_buffer,
2541 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2542 pg_class_reltoastrelid);
2544 /* every toast table has an index */
2545 appendPQExpBuffer(upgrade_buffer,
2546 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2547 pg_class_reltoastidxid);
2551 appendPQExpBuffer(upgrade_buffer,
2552 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2555 appendPQExpBuffer(upgrade_buffer, "\n");
2557 PQclear(upgrade_res);
2558 destroyPQExpBuffer(upgrade_query);
2562 * If the DumpableObject is a member of an extension, add a suitable
2563 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2566 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2567 DumpableObject *dobj,
2568 const char *objlabel)
2570 DumpableObject *extobj = NULL;
2573 if (!dobj->ext_member)
2577 * Find the parent extension. We could avoid this search if we wanted to
2578 * add a link field to DumpableObject, but the space costs of that would
2579 * be considerable. We assume that member objects could only have a
2580 * direct dependency on their own extension, not any others.
2582 for (i = 0; i < dobj->nDeps; i++)
2584 extobj = findObjectByDumpId(dobj->dependencies[i]);
2585 if (extobj && extobj->objType == DO_EXTENSION)
2590 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2592 appendPQExpBuffer(upgrade_buffer,
2593 "\n-- For binary upgrade, handle extension membership the hard way\n");
2594 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2595 fmtId(extobj->name),
2601 * read all namespaces in the system catalogs and return them in the
2602 * NamespaceInfo* structure
2604 * numNamespaces is set to the number of namespaces read in
2607 getNamespaces(Archive *fout, int *numNamespaces)
2613 NamespaceInfo *nsinfo;
2621 * Before 7.3, there are no real namespaces; create two dummy entries, one
2622 * for user stuff and one for system stuff.
2624 if (fout->remoteVersion < 70300)
2626 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2628 nsinfo[0].dobj.objType = DO_NAMESPACE;
2629 nsinfo[0].dobj.catId.tableoid = 0;
2630 nsinfo[0].dobj.catId.oid = 0;
2631 AssignDumpId(&nsinfo[0].dobj);
2632 nsinfo[0].dobj.name = pg_strdup("public");
2633 nsinfo[0].rolname = pg_strdup("");
2634 nsinfo[0].nspacl = pg_strdup("");
2636 selectDumpableNamespace(&nsinfo[0]);
2638 nsinfo[1].dobj.objType = DO_NAMESPACE;
2639 nsinfo[1].dobj.catId.tableoid = 0;
2640 nsinfo[1].dobj.catId.oid = 1;
2641 AssignDumpId(&nsinfo[1].dobj);
2642 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2643 nsinfo[1].rolname = pg_strdup("");
2644 nsinfo[1].nspacl = pg_strdup("");
2646 selectDumpableNamespace(&nsinfo[1]);
2653 query = createPQExpBuffer();
2655 /* Make sure we are in proper schema */
2656 selectSourceSchema(fout, "pg_catalog");
2659 * we fetch all namespaces including system ones, so that every object we
2660 * read in can be linked to a containing namespace.
2662 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2663 "(%s nspowner) AS rolname, "
2664 "nspacl FROM pg_namespace",
2667 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2669 ntups = PQntuples(res);
2671 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2673 i_tableoid = PQfnumber(res, "tableoid");
2674 i_oid = PQfnumber(res, "oid");
2675 i_nspname = PQfnumber(res, "nspname");
2676 i_rolname = PQfnumber(res, "rolname");
2677 i_nspacl = PQfnumber(res, "nspacl");
2679 for (i = 0; i < ntups; i++)
2681 nsinfo[i].dobj.objType = DO_NAMESPACE;
2682 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2683 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2684 AssignDumpId(&nsinfo[i].dobj);
2685 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2686 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2687 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2689 /* Decide whether to dump this namespace */
2690 selectDumpableNamespace(&nsinfo[i]);
2692 if (strlen(nsinfo[i].rolname) == 0)
2693 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2694 nsinfo[i].dobj.name);
2698 destroyPQExpBuffer(query);
2700 *numNamespaces = ntups;
2707 * given a namespace OID and an object OID, look up the info read by
2710 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2711 * a system object or not. In 7.3 and later there is no guessing, and we
2712 * don't use objoid at all.
2714 static NamespaceInfo *
2715 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2717 NamespaceInfo *nsinfo;
2719 if (fout->remoteVersion >= 70300)
2721 nsinfo = findNamespaceByOid(nsoid);
2725 /* This code depends on the dummy objects set up by getNamespaces. */
2728 if (objoid > g_last_builtin_oid)
2729 i = 0; /* user object */
2731 i = 1; /* system object */
2732 nsinfo = findNamespaceByOid(i);
2736 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2743 * read all extensions in the system catalogs and return them in the
2744 * ExtensionInfo* structure
2746 * numExtensions is set to the number of extensions read in
2749 getExtensions(Archive *fout, int *numExtensions)
2755 ExtensionInfo *extinfo;
2760 int i_extrelocatable;
2766 * Before 9.1, there are no extensions.
2768 if (fout->remoteVersion < 90100)
2774 query = createPQExpBuffer();
2776 /* Make sure we are in proper schema */
2777 selectSourceSchema(fout, "pg_catalog");
2779 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2780 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2781 "FROM pg_extension x "
2782 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2784 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2786 ntups = PQntuples(res);
2788 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2790 i_tableoid = PQfnumber(res, "tableoid");
2791 i_oid = PQfnumber(res, "oid");
2792 i_extname = PQfnumber(res, "extname");
2793 i_nspname = PQfnumber(res, "nspname");
2794 i_extrelocatable = PQfnumber(res, "extrelocatable");
2795 i_extversion = PQfnumber(res, "extversion");
2796 i_extconfig = PQfnumber(res, "extconfig");
2797 i_extcondition = PQfnumber(res, "extcondition");
2799 for (i = 0; i < ntups; i++)
2801 extinfo[i].dobj.objType = DO_EXTENSION;
2802 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2803 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2804 AssignDumpId(&extinfo[i].dobj);
2805 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2806 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2807 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2808 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2809 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2810 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2812 /* Decide whether we want to dump it */
2813 selectDumpableExtension(&(extinfo[i]));
2817 destroyPQExpBuffer(query);
2819 *numExtensions = ntups;
2826 * read all types in the system catalogs and return them in the
2827 * TypeInfo* structure
2829 * numTypes is set to the number of types read in
2831 * NB: this must run after getFuncs() because we assume we can do
2835 getTypes(Archive *fout, int *numTypes)
2840 PQExpBuffer query = createPQExpBuffer();
2842 ShellTypeInfo *stinfo;
2859 * we include even the built-in types because those may be used as array
2860 * elements by user-defined types
2862 * we filter out the built-in types when we dump out the types
2864 * same approach for undefined (shell) types and array types
2866 * Note: as of 8.3 we can reliably detect whether a type is an
2867 * auto-generated array type by checking the element type's typarray.
2868 * (Before that the test is capable of generating false positives.) We
2869 * still check for name beginning with '_', though, so as to avoid the
2870 * cost of the subselect probe for all standard types. This would have to
2871 * be revisited if the backend ever allows renaming of array types.
2874 /* Make sure we are in proper schema */
2875 selectSourceSchema(fout, "pg_catalog");
2877 if (fout->remoteVersion >= 90200)
2879 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2880 "typnamespace, typacl, "
2881 "(%s typowner) AS rolname, "
2882 "typinput::oid AS typinput, "
2883 "typoutput::oid AS typoutput, typelem, typrelid, "
2884 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2885 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2886 "typtype, typisdefined, "
2887 "typname[0] = '_' AND typelem != 0 AND "
2888 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2892 else if (fout->remoteVersion >= 80300)
2894 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2895 "typnamespace, '{=U}' AS typacl, "
2896 "(%s typowner) AS rolname, "
2897 "typinput::oid AS typinput, "
2898 "typoutput::oid AS typoutput, typelem, typrelid, "
2899 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2900 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2901 "typtype, typisdefined, "
2902 "typname[0] = '_' AND typelem != 0 AND "
2903 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2907 else if (fout->remoteVersion >= 70300)
2909 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2910 "typnamespace, '{=U}' AS typacl, "
2911 "(%s typowner) AS rolname, "
2912 "typinput::oid AS typinput, "
2913 "typoutput::oid AS typoutput, typelem, typrelid, "
2914 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2915 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2916 "typtype, typisdefined, "
2917 "typname[0] = '_' AND typelem != 0 AS isarray "
2921 else if (fout->remoteVersion >= 70100)
2923 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2924 "0::oid AS typnamespace, '{=U}' AS typacl, "
2925 "(%s typowner) AS rolname, "
2926 "typinput::oid AS typinput, "
2927 "typoutput::oid AS typoutput, typelem, typrelid, "
2928 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2929 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2930 "typtype, typisdefined, "
2931 "typname[0] = '_' AND typelem != 0 AS isarray "
2937 appendPQExpBuffer(query, "SELECT "
2938 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2940 "0::oid AS typnamespace, '{=U}' AS typacl, "
2941 "(%s typowner) AS rolname, "
2942 "typinput::oid AS typinput, "
2943 "typoutput::oid AS typoutput, typelem, typrelid, "
2944 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2945 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2946 "typtype, typisdefined, "
2947 "typname[0] = '_' AND typelem != 0 AS isarray "
2952 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2954 ntups = PQntuples(res);
2956 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2958 i_tableoid = PQfnumber(res, "tableoid");
2959 i_oid = PQfnumber(res, "oid");
2960 i_typname = PQfnumber(res, "typname");
2961 i_typnamespace = PQfnumber(res, "typnamespace");
2962 i_typacl = PQfnumber(res, "typacl");
2963 i_rolname = PQfnumber(res, "rolname");
2964 i_typinput = PQfnumber(res, "typinput");
2965 i_typoutput = PQfnumber(res, "typoutput");
2966 i_typelem = PQfnumber(res, "typelem");
2967 i_typrelid = PQfnumber(res, "typrelid");
2968 i_typrelkind = PQfnumber(res, "typrelkind");
2969 i_typtype = PQfnumber(res, "typtype");
2970 i_typisdefined = PQfnumber(res, "typisdefined");
2971 i_isarray = PQfnumber(res, "isarray");
2973 for (i = 0; i < ntups; i++)
2975 tyinfo[i].dobj.objType = DO_TYPE;
2976 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2977 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2978 AssignDumpId(&tyinfo[i].dobj);
2979 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2980 tyinfo[i].dobj.namespace =
2982 atooid(PQgetvalue(res, i, i_typnamespace)),
2983 tyinfo[i].dobj.catId.oid);
2984 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2985 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
2986 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2987 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2988 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2989 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2990 tyinfo[i].shellType = NULL;
2992 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2993 tyinfo[i].isDefined = true;
2995 tyinfo[i].isDefined = false;
2997 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2998 tyinfo[i].isArray = true;
3000 tyinfo[i].isArray = false;
3002 /* Decide whether we want to dump it */
3003 selectDumpableType(&tyinfo[i]);
3006 * If it's a domain, fetch info about its constraints, if any
3008 tyinfo[i].nDomChecks = 0;
3009 tyinfo[i].domChecks = NULL;
3010 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3011 getDomainConstraints(fout, &(tyinfo[i]));
3014 * If it's a base type, make a DumpableObject representing a shell
3015 * definition of the type. We will need to dump that ahead of the I/O
3016 * functions for the type. Similarly, range types need a shell
3017 * definition in case they have a canonicalize function.
3019 * Note: the shell type doesn't have a catId. You might think it
3020 * should copy the base type's catId, but then it might capture the
3021 * pg_depend entries for the type, which we don't want.
3023 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3024 tyinfo[i].typtype == TYPTYPE_RANGE))
3026 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3027 stinfo->dobj.objType = DO_SHELL_TYPE;
3028 stinfo->dobj.catId = nilCatalogId;
3029 AssignDumpId(&stinfo->dobj);
3030 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3031 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3032 stinfo->baseType = &(tyinfo[i]);
3033 tyinfo[i].shellType = stinfo;
3036 * Initially mark the shell type as not to be dumped. We'll only
3037 * dump it if the I/O or canonicalize functions need to be dumped;
3038 * this is taken care of while sorting dependencies.
3040 stinfo->dobj.dump = false;
3043 * However, if dumping from pre-7.3, there will be no dependency
3044 * info so we have to fake it here. We only need to worry about
3045 * typinput and typoutput since the other functions only exist
3048 if (fout->remoteVersion < 70300)
3054 typinput = atooid(PQgetvalue(res, i, i_typinput));
3055 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3057 funcInfo = findFuncByOid(typinput);
3058 if (funcInfo && funcInfo->dobj.dump)
3060 /* base type depends on function */
3061 addObjectDependency(&tyinfo[i].dobj,
3062 funcInfo->dobj.dumpId);
3063 /* function depends on shell type */
3064 addObjectDependency(&funcInfo->dobj,
3065 stinfo->dobj.dumpId);
3066 /* mark shell type as to be dumped */
3067 stinfo->dobj.dump = true;
3070 funcInfo = findFuncByOid(typoutput);
3071 if (funcInfo && funcInfo->dobj.dump)
3073 /* base type depends on function */
3074 addObjectDependency(&tyinfo[i].dobj,
3075 funcInfo->dobj.dumpId);
3076 /* function depends on shell type */
3077 addObjectDependency(&funcInfo->dobj,
3078 stinfo->dobj.dumpId);
3079 /* mark shell type as to be dumped */
3080 stinfo->dobj.dump = true;
3085 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3086 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3087 tyinfo[i].dobj.name);
3094 destroyPQExpBuffer(query);
3101 * read all operators in the system catalogs and return them in the
3102 * OprInfo* structure
3104 * numOprs is set to the number of operators read in
3107 getOperators(Archive *fout, int *numOprs)
3112 PQExpBuffer query = createPQExpBuffer();
3123 * find all operators, including builtin operators; we filter out
3124 * system-defined operators at dump-out time.
3127 /* Make sure we are in proper schema */
3128 selectSourceSchema(fout, "pg_catalog");
3130 if (fout->remoteVersion >= 70300)
3132 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3134 "(%s oprowner) AS rolname, "
3136 "oprcode::oid AS oprcode "
3140 else if (fout->remoteVersion >= 70100)
3142 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3143 "0::oid AS oprnamespace, "
3144 "(%s oprowner) AS rolname, "
3146 "oprcode::oid AS oprcode "
3152 appendPQExpBuffer(query, "SELECT "
3153 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3155 "0::oid AS oprnamespace, "
3156 "(%s oprowner) AS rolname, "
3158 "oprcode::oid AS oprcode "
3163 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3165 ntups = PQntuples(res);
3168 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3170 i_tableoid = PQfnumber(res, "tableoid");
3171 i_oid = PQfnumber(res, "oid");
3172 i_oprname = PQfnumber(res, "oprname");
3173 i_oprnamespace = PQfnumber(res, "oprnamespace");
3174 i_rolname = PQfnumber(res, "rolname");
3175 i_oprkind = PQfnumber(res, "oprkind");
3176 i_oprcode = PQfnumber(res, "oprcode");
3178 for (i = 0; i < ntups; i++)
3180 oprinfo[i].dobj.objType = DO_OPERATOR;
3181 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3182 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3183 AssignDumpId(&oprinfo[i].dobj);
3184 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3185 oprinfo[i].dobj.namespace =
3187 atooid(PQgetvalue(res, i, i_oprnamespace)),
3188 oprinfo[i].dobj.catId.oid);
3189 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3190 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3191 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3193 /* Decide whether we want to dump it */
3194 selectDumpableObject(&(oprinfo[i].dobj));
3196 if (strlen(oprinfo[i].rolname) == 0)
3197 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3198 oprinfo[i].dobj.name);
3203 destroyPQExpBuffer(query);
3210 * read all collations in the system catalogs and return them in the
3211 * CollInfo* structure
3213 * numCollations is set to the number of collations read in
3216 getCollations(Archive *fout, int *numCollations)
3226 int i_collnamespace;
3229 /* Collations didn't exist pre-9.1 */
3230 if (fout->remoteVersion < 90100)
3236 query = createPQExpBuffer();
3239 * find all collations, including builtin collations; we filter out
3240 * system-defined collations at dump-out time.
3243 /* Make sure we are in proper schema */
3244 selectSourceSchema(fout, "pg_catalog");
3246 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3248 "(%s collowner) AS rolname "
3249 "FROM pg_collation",
3252 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3254 ntups = PQntuples(res);
3255 *numCollations = ntups;
3257 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3259 i_tableoid = PQfnumber(res, "tableoid");
3260 i_oid = PQfnumber(res, "oid");
3261 i_collname = PQfnumber(res, "collname");
3262 i_collnamespace = PQfnumber(res, "collnamespace");
3263 i_rolname = PQfnumber(res, "rolname");
3265 for (i = 0; i < ntups; i++)
3267 collinfo[i].dobj.objType = DO_COLLATION;
3268 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3269 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3270 AssignDumpId(&collinfo[i].dobj);
3271 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3272 collinfo[i].dobj.namespace =
3274 atooid(PQgetvalue(res, i, i_collnamespace)),
3275 collinfo[i].dobj.catId.oid);
3276 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3278 /* Decide whether we want to dump it */
3279 selectDumpableObject(&(collinfo[i].dobj));
3284 destroyPQExpBuffer(query);
3291 * read all conversions in the system catalogs and return them in the
3292 * ConvInfo* structure
3294 * numConversions is set to the number of conversions read in
3297 getConversions(Archive *fout, int *numConversions)
3302 PQExpBuffer query = createPQExpBuffer();
3310 /* Conversions didn't exist pre-7.3 */
3311 if (fout->remoteVersion < 70300)
3313 *numConversions = 0;
3318 * find all conversions, including builtin conversions; we filter out
3319 * system-defined conversions at dump-out time.
3322 /* Make sure we are in proper schema */
3323 selectSourceSchema(fout, "pg_catalog");
3325 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3327 "(%s conowner) AS rolname "
3328 "FROM pg_conversion",
3331 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3333 ntups = PQntuples(res);
3334 *numConversions = ntups;
3336 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3338 i_tableoid = PQfnumber(res, "tableoid");
3339 i_oid = PQfnumber(res, "oid");
3340 i_conname = PQfnumber(res, "conname");
3341 i_connamespace = PQfnumber(res, "connamespace");
3342 i_rolname = PQfnumber(res, "rolname");
3344 for (i = 0; i < ntups; i++)
3346 convinfo[i].dobj.objType = DO_CONVERSION;
3347 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3348 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3349 AssignDumpId(&convinfo[i].dobj);
3350 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3351 convinfo[i].dobj.namespace =
3353 atooid(PQgetvalue(res, i, i_connamespace)),
3354 convinfo[i].dobj.catId.oid);
3355 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3357 /* Decide whether we want to dump it */
3358 selectDumpableObject(&(convinfo[i].dobj));
3363 destroyPQExpBuffer(query);
3370 * read all opclasses in the system catalogs and return them in the
3371 * OpclassInfo* structure
3373 * numOpclasses is set to the number of opclasses read in
3376 getOpclasses(Archive *fout, int *numOpclasses)
3381 PQExpBuffer query = createPQExpBuffer();
3382 OpclassInfo *opcinfo;
3390 * find all opclasses, including builtin opclasses; we filter out
3391 * system-defined opclasses at dump-out time.
3394 /* Make sure we are in proper schema */
3395 selectSourceSchema(fout, "pg_catalog");
3397 if (fout->remoteVersion >= 70300)
3399 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3401 "(%s opcowner) AS rolname "
3405 else if (fout->remoteVersion >= 70100)
3407 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3408 "0::oid AS opcnamespace, "
3409 "''::name AS rolname "
3414 appendPQExpBuffer(query, "SELECT "
3415 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3417 "0::oid AS opcnamespace, "
3418 "''::name AS rolname "
3422 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3424 ntups = PQntuples(res);
3425 *numOpclasses = ntups;
3427 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3429 i_tableoid = PQfnumber(res, "tableoid");
3430 i_oid = PQfnumber(res, "oid");
3431 i_opcname = PQfnumber(res, "opcname");
3432 i_opcnamespace = PQfnumber(res, "opcnamespace");
3433 i_rolname = PQfnumber(res, "rolname");
3435 for (i = 0; i < ntups; i++)
3437 opcinfo[i].dobj.objType = DO_OPCLASS;
3438 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3439 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3440 AssignDumpId(&opcinfo[i].dobj);
3441 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3442 opcinfo[i].dobj.namespace =
3444 atooid(PQgetvalue(res, i, i_opcnamespace)),
3445 opcinfo[i].dobj.catId.oid);
3446 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3448 /* Decide whether we want to dump it */
3449 selectDumpableObject(&(opcinfo[i].dobj));
3451 if (fout->remoteVersion >= 70300)
3453 if (strlen(opcinfo[i].rolname) == 0)
3454 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3455 opcinfo[i].dobj.name);
3461 destroyPQExpBuffer(query);
3468 * read all opfamilies in the system catalogs and return them in the
3469 * OpfamilyInfo* structure
3471 * numOpfamilies is set to the number of opfamilies read in
3474 getOpfamilies(Archive *fout, int *numOpfamilies)
3480 OpfamilyInfo *opfinfo;
3487 /* Before 8.3, there is no separate concept of opfamilies */
3488 if (fout->remoteVersion < 80300)
3494 query = createPQExpBuffer();
3497 * find all opfamilies, including builtin opfamilies; we filter out
3498 * system-defined opfamilies at dump-out time.
3501 /* Make sure we are in proper schema */
3502 selectSourceSchema(fout, "pg_catalog");
3504 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3506 "(%s opfowner) AS rolname "
3510 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3512 ntups = PQntuples(res);
3513 *numOpfamilies = ntups;
3515 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3517 i_tableoid = PQfnumber(res, "tableoid");
3518 i_oid = PQfnumber(res, "oid");
3519 i_opfname = PQfnumber(res, "opfname");
3520 i_opfnamespace = PQfnumber(res, "opfnamespace");
3521 i_rolname = PQfnumber(res, "rolname");
3523 for (i = 0; i < ntups; i++)
3525 opfinfo[i].dobj.objType = DO_OPFAMILY;
3526 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3527 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3528 AssignDumpId(&opfinfo[i].dobj);
3529 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3530 opfinfo[i].dobj.namespace =
3532 atooid(PQgetvalue(res, i, i_opfnamespace)),
3533 opfinfo[i].dobj.catId.oid);
3534 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3536 /* Decide whether we want to dump it */
3537 selectDumpableObject(&(opfinfo[i].dobj));
3539 if (fout->remoteVersion >= 70300)
3541 if (strlen(opfinfo[i].rolname) == 0)
3542 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3543 opfinfo[i].dobj.name);
3549 destroyPQExpBuffer(query);
3556 * read all the user-defined aggregates in the system catalogs and
3557 * return them in the AggInfo* structure
3559 * numAggs is set to the number of aggregates read in
3562 getAggregates(Archive *fout, int *numAggs)
3567 PQExpBuffer query = createPQExpBuffer();
3579 /* Make sure we are in proper schema */
3580 selectSourceSchema(fout, "pg_catalog");
3583 * Find all user-defined aggregates. See comment in getFuncs() for the
3584 * rationale behind the filtering logic.
3587 if (fout->remoteVersion >= 80400)
3589 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3590 "pronamespace AS aggnamespace, "
3591 "pronargs, proargtypes, "
3592 "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3593 "(%s proowner) AS rolname, "
3596 "WHERE proisagg AND ("
3598 "(SELECT oid FROM pg_namespace "
3599 "WHERE nspname = 'pg_catalog')",
3601 if (binary_upgrade && fout->remoteVersion >= 90100)
3602 appendPQExpBuffer(query,
3603 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3604 "classid = 'pg_proc'::regclass AND "
3605 "objid = p.oid AND "
3606 "refclassid = 'pg_extension'::regclass AND "
3608 appendPQExpBuffer(query, ")");
3610 else if (fout->remoteVersion >= 80200)
3612 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3613 "pronamespace AS aggnamespace, "
3614 "pronargs, proargtypes, "
3615 "NULL::text AS proiargs,"
3616 "(%s proowner) AS rolname, "
3619 "WHERE proisagg AND ("
3621 "(SELECT oid FROM pg_namespace "
3622 "WHERE nspname = 'pg_catalog'))",
3625 else if (fout->remoteVersion >= 70300)
3627 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3628 "pronamespace AS aggnamespace, "
3629 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3631 "NULL::text AS proiargs, "
3632 "(%s proowner) AS rolname, "
3636 "AND pronamespace != "
3637 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3640 else if (fout->remoteVersion >= 70100)
3642 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3643 "0::oid AS aggnamespace, "
3644 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3645 "aggbasetype AS proargtypes, "
3646 "NULL::text AS proiargs, "
3647 "(%s aggowner) AS rolname, "
3649 "FROM pg_aggregate "
3650 "where oid > '%u'::oid",
3652 g_last_builtin_oid);
3656 appendPQExpBuffer(query, "SELECT "
3657 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3659 "0::oid AS aggnamespace, "
3660 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3661 "aggbasetype AS proargtypes, "
3662 "NULL::text AS proiargs, "
3663 "(%s aggowner) AS rolname, "
3665 "FROM pg_aggregate "
3666 "where oid > '%u'::oid",
3668 g_last_builtin_oid);
3671 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3673 ntups = PQntuples(res);
3676 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3678 i_tableoid = PQfnumber(res, "tableoid");
3679 i_oid = PQfnumber(res, "oid");
3680 i_aggname = PQfnumber(res, "aggname");
3681 i_aggnamespace = PQfnumber(res, "aggnamespace");
3682 i_pronargs = PQfnumber(res, "pronargs");
3683 i_proargtypes = PQfnumber(res, "proargtypes");
3684 i_rolname = PQfnumber(res, "rolname");
3685 i_aggacl = PQfnumber(res, "aggacl");
3686 i_proiargs = PQfnumber(res, "proiargs");
3688 for (i = 0; i < ntups; i++)
3690 agginfo[i].aggfn.dobj.objType = DO_AGG;
3691 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3692 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3693 AssignDumpId(&agginfo[i].aggfn.dobj);
3694 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3695 agginfo[i].aggfn.dobj.namespace =
3697 atooid(PQgetvalue(res, i, i_aggnamespace)),
3698 agginfo[i].aggfn.dobj.catId.oid);
3699 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3700 if (strlen(agginfo[i].aggfn.rolname) == 0)
3701 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3702 agginfo[i].aggfn.dobj.name);
3703 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3704 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3705 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3706 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3707 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3708 if (agginfo[i].aggfn.nargs == 0)
3709 agginfo[i].aggfn.argtypes = NULL;
3712 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3713 if (fout->remoteVersion >= 70300)
3714 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3715 agginfo[i].aggfn.argtypes,
3716 agginfo[i].aggfn.nargs);
3718 /* it's just aggbasetype */
3719 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3722 /* Decide whether we want to dump it */
3723 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3728 destroyPQExpBuffer(query);
3735 * read all the user-defined functions in the system catalogs and
3736 * return them in the FuncInfo* structure
3738 * numFuncs is set to the number of functions read in
3741 getFuncs(Archive *fout, int *numFuncs)
3746 PQExpBuffer query = createPQExpBuffer();
3760 /* Make sure we are in proper schema */
3761 selectSourceSchema(fout, "pg_catalog");
3764 * Find all user-defined functions. Normally we can exclude functions in
3765 * pg_catalog, which is worth doing since there are several thousand of
3766 * 'em. However, there are some extensions that create functions in
3767 * pg_catalog. In normal dumps we can still ignore those --- but in
3768 * binary-upgrade mode, we must dump the member objects of the extension,
3769 * so be sure to fetch any such functions.
3771 * Also, in 9.2 and up, exclude functions that are internally dependent on
3772 * something else, since presumably those will be created as a result of
3773 * creating the something else. This currently only acts to suppress
3774 * constructor functions for range types. Note that this is OK only
3775 * because the constructors don't have any dependencies the range type
3776 * doesn't have; otherwise we might not get creation ordering correct.
3779 if (fout->remoteVersion >= 80400)
3781 appendPQExpBuffer(query,
3782 "SELECT tableoid, oid, proname, prolang, "
3783 "pronargs, proargtypes, prorettype, proacl, "
3785 "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3786 "(%s proowner) AS rolname "
3788 "WHERE NOT proisagg AND ("
3790 "(SELECT oid FROM pg_namespace "
3791 "WHERE nspname = 'pg_catalog')",
3793 if (fout->remoteVersion >= 90200)
3794 appendPQExpBuffer(query,
3795 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3796 "WHERE classid = 'pg_proc'::regclass AND "
3797 "objid = p.oid AND deptype = 'i')");
3798 if (binary_upgrade && fout->remoteVersion >= 90100)
3799 appendPQExpBuffer(query,
3800 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3801 "classid = 'pg_proc'::regclass AND "
3802 "objid = p.oid AND "
3803 "refclassid = 'pg_extension'::regclass AND "
3805 appendPQExpBuffer(query, ")");
3807 else if (fout->remoteVersion >= 70300)
3809 appendPQExpBuffer(query,
3810 "SELECT tableoid, oid, proname, prolang, "
3811 "pronargs, proargtypes, prorettype, proacl, "
3813 "NULL::text AS proiargs,"
3814 "(%s proowner) AS rolname "
3816 "WHERE NOT proisagg AND ("
3818 "(SELECT oid FROM pg_namespace "
3819 "WHERE nspname = 'pg_catalog'))",
3822 else if (fout->remoteVersion >= 70100)
3824 appendPQExpBuffer(query,
3825 "SELECT tableoid, oid, proname, prolang, "
3826 "pronargs, proargtypes, prorettype, "
3827 "'{=X}' AS proacl, "
3828 "0::oid AS pronamespace, "
3829 "NULL::text AS proiargs,"
3830 "(%s proowner) AS rolname "
3832 "WHERE pg_proc.oid > '%u'::oid",
3834 g_last_builtin_oid);
3838 appendPQExpBuffer(query,
3840 "(SELECT oid FROM pg_class "
3841 " WHERE relname = 'pg_proc') AS tableoid, "
3842 "oid, proname, prolang, "
3843 "pronargs, proargtypes, prorettype, "
3844 "'{=X}' AS proacl, "
3845 "0::oid AS pronamespace, "
3846 "NULL::text AS proiargs,"
3847 "(%s proowner) AS rolname "
3849 "where pg_proc.oid > '%u'::oid",
3851 g_last_builtin_oid);
3854 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3856 ntups = PQntuples(res);
3860 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
3862 i_tableoid = PQfnumber(res, "tableoid");
3863 i_oid = PQfnumber(res, "oid");
3864 i_proname = PQfnumber(res, "proname");
3865 i_pronamespace = PQfnumber(res, "pronamespace");
3866 i_rolname = PQfnumber(res, "rolname");
3867 i_prolang = PQfnumber(res, "prolang");
3868 i_pronargs = PQfnumber(res, "pronargs");
3869 i_proargtypes = PQfnumber(res, "proargtypes");
3870 i_prorettype = PQfnumber(res, "prorettype");
3871 i_proacl = PQfnumber(res, "proacl");
3872 i_proiargs = PQfnumber(res, "proiargs");
3874 for (i = 0; i < ntups; i++)
3876 finfo[i].dobj.objType = DO_FUNC;
3877 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3878 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3879 AssignDumpId(&finfo[i].dobj);
3880 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3881 finfo[i].dobj.namespace =
3883 atooid(PQgetvalue(res, i, i_pronamespace)),
3884 finfo[i].dobj.catId.oid);
3885 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3886 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3887 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3888 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3889 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3890 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3891 if (finfo[i].nargs == 0)
3892 finfo[i].argtypes = NULL;
3895 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3896 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3897 finfo[i].argtypes, finfo[i].nargs);
3900 /* Decide whether we want to dump it */
3901 selectDumpableObject(&(finfo[i].dobj));
3903 if (strlen(finfo[i].rolname) == 0)
3905 "WARNING: owner of function \"%s\" appears to be invalid\n",
3906 finfo[i].dobj.name);
3911 destroyPQExpBuffer(query);
3918 * read all the user-defined tables (no indexes, no catalogs)
3919 * in the system catalogs return them in the TableInfo* structure
3921 * numTables is set to the number of tables read in
3924 getTables(Archive *fout, int *numTables)
3929 PQExpBuffer query = createPQExpBuffer();
3939 int i_relhastriggers;
3945 int i_toastfrozenxid;
3946 int i_relpersistence;
3949 int i_reltablespace;
3951 int i_toastreloptions;
3954 /* Make sure we are in proper schema */
3955 selectSourceSchema(fout, "pg_catalog");
3958 * Find all the tables and table-like objects.
3960 * We include system catalogs, so that we can work if a user table is
3961 * defined to inherit from a system catalog (pretty weird, but...)
3963 * We ignore relations that are not ordinary tables, sequences, views,
3964 * composite types, or foreign tables.
3966 * Composite-type table entries won't be dumped as such, but we have to
3967 * make a DumpableObject for them so that we can track dependencies of the
3968 * composite type (pg_depend entries for columns of the composite type
3969 * link to the pg_class entry not the pg_type entry).
3971 * Note: in this phase we should collect only a minimal amount of
3972 * information about each table, basically just enough to decide if it is
3973 * interesting. We must fetch all tables in this phase because otherwise
3974 * we cannot correctly identify inherited columns, owned sequences, etc.
3977 if (fout->remoteVersion >= 90100)
3980 * Left join to pick up dependency info linking sequences to their
3981 * owning column, if any (note this dependency is AUTO as of 8.2)
3983 appendPQExpBuffer(query,
3984 "SELECT c.tableoid, c.oid, c.relname, "
3985 "c.relacl, c.relkind, c.relnamespace, "
3986 "(%s c.relowner) AS rolname, "
3987 "c.relchecks, c.relhastriggers, "
3988 "c.relhasindex, c.relhasrules, c.relhasoids, "
3989 "c.relfrozenxid, tc.oid AS toid, "
3990 "tc.relfrozenxid AS tfrozenxid, "
3991 "c.relpersistence, "
3992 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3993 "d.refobjid AS owning_tab, "
3994 "d.refobjsubid AS owning_col, "
3995 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3996 "array_to_string(c.reloptions, ', ') AS reloptions, "
3997 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3999 "LEFT JOIN pg_depend d ON "
4000 "(c.relkind = '%c' AND "
4001 "d.classid = c.tableoid AND d.objid = c.oid AND "
4002 "d.objsubid = 0 AND "
4003 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4004 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4005 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
4009 RELKIND_RELATION, RELKIND_SEQUENCE,
4010 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4011 RELKIND_FOREIGN_TABLE);
4013 else if (fout->remoteVersion >= 90000)
4016 * Left join to pick up dependency info linking sequences to their
4017 * owning column, if any (note this dependency is AUTO as of 8.2)
4019 appendPQExpBuffer(query,
4020 "SELECT c.tableoid, c.oid, c.relname, "
4021 "c.relacl, c.relkind, c.relnamespace, "
4022 "(%s c.relowner) AS rolname, "
4023 "c.relchecks, c.relhastriggers, "
4024 "c.relhasindex, c.relhasrules, c.relhasoids, "
4025 "c.relfrozenxid, tc.oid AS toid, "
4026 "tc.relfrozenxid AS tfrozenxid, "
4027 "'p' AS relpersistence, "
4028 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4029 "d.refobjid AS owning_tab, "
4030 "d.refobjsubid AS owning_col, "
4031 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4032 "array_to_string(c.reloptions, ', ') AS reloptions, "
4033 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4035 "LEFT JOIN pg_depend d ON "
4036 "(c.relkind = '%c' AND "
4037 "d.classid = c.tableoid AND d.objid = c.oid AND "
4038 "d.objsubid = 0 AND "
4039 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4040 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4041 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4045 RELKIND_RELATION, RELKIND_SEQUENCE,
4046 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4048 else if (fout->remoteVersion >= 80400)
4051 * Left join to pick up dependency info linking sequences to their
4052 * owning column, if any (note this dependency is AUTO as of 8.2)
4054 appendPQExpBuffer(query,
4055 "SELECT c.tableoid, c.oid, c.relname, "
4056 "c.relacl, c.relkind, c.relnamespace, "
4057 "(%s c.relowner) AS rolname, "
4058 "c.relchecks, c.relhastriggers, "
4059 "c.relhasindex, c.relhasrules, c.relhasoids, "
4060 "c.relfrozenxid, tc.oid AS toid, "
4061 "tc.relfrozenxid AS tfrozenxid, "
4062 "'p' AS relpersistence, "
4063 "NULL AS reloftype, "
4064 "d.refobjid AS owning_tab, "
4065 "d.refobjsubid AS owning_col, "
4066 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4067 "array_to_string(c.reloptions, ', ') AS reloptions, "
4068 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4070 "LEFT JOIN pg_depend d ON "
4071 "(c.relkind = '%c' AND "
4072 "d.classid = c.tableoid AND d.objid = c.oid AND "
4073 "d.objsubid = 0 AND "
4074 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4075 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4076 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4080 RELKIND_RELATION, RELKIND_SEQUENCE,
4081 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4083 else if (fout->remoteVersion >= 80200)
4086 * Left join to pick up dependency info linking sequences to their
4087 * owning column, if any (note this dependency is AUTO as of 8.2)
4089 appendPQExpBuffer(query,
4090 "SELECT c.tableoid, c.oid, c.relname, "
4091 "c.relacl, c.relkind, c.relnamespace, "
4092 "(%s c.relowner) AS rolname, "
4093 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4094 "c.relhasindex, c.relhasrules, c.relhasoids, "
4095 "c.relfrozenxid, tc.oid AS toid, "
4096 "tc.relfrozenxid AS tfrozenxid, "
4097 "'p' AS relpersistence, "
4098 "NULL AS reloftype, "
4099 "d.refobjid AS owning_tab, "
4100 "d.refobjsubid AS owning_col, "
4101 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4102 "array_to_string(c.reloptions, ', ') AS reloptions, "
4103 "NULL AS toast_reloptions "
4105 "LEFT JOIN pg_depend d ON "
4106 "(c.relkind = '%c' AND "
4107 "d.classid = c.tableoid AND d.objid = c.oid AND "
4108 "d.objsubid = 0 AND "
4109 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4110 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4111 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4115 RELKIND_RELATION, RELKIND_SEQUENCE,
4116 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4118 else if (fout->remoteVersion >= 80000)
4121 * Left join to pick up dependency info linking sequences to their
4122 * owning column, if any
4124 appendPQExpBuffer(query,
4125 "SELECT c.tableoid, c.oid, relname, "
4126 "relacl, relkind, relnamespace, "
4127 "(%s relowner) AS rolname, "
4128 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4129 "relhasindex, relhasrules, relhasoids, "
4130 "0 AS relfrozenxid, "
4133 "'p' AS relpersistence, "
4134 "NULL AS reloftype, "
4135 "d.refobjid AS owning_tab, "
4136 "d.refobjsubid AS owning_col, "
4137 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4138 "NULL AS reloptions, "
4139 "NULL AS toast_reloptions "
4141 "LEFT JOIN pg_depend d ON "
4142 "(c.relkind = '%c' AND "
4143 "d.classid = c.tableoid AND d.objid = c.oid AND "
4144 "d.objsubid = 0 AND "
4145 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4146 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4150 RELKIND_RELATION, RELKIND_SEQUENCE,
4151 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4153 else if (fout->remoteVersion >= 70300)
4156 * Left join to pick up dependency info linking sequences to their
4157 * owning column, if any
4159 appendPQExpBuffer(query,
4160 "SELECT c.tableoid, c.oid, relname, "
4161 "relacl, relkind, relnamespace, "
4162 "(%s relowner) AS rolname, "
4163 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4164 "relhasindex, relhasrules, relhasoids, "
4165 "0 AS relfrozenxid, "
4168 "'p' AS relpersistence, "
4169 "NULL AS reloftype, "
4170 "d.refobjid AS owning_tab, "
4171 "d.refobjsubid AS owning_col, "
4172 "NULL AS reltablespace, "
4173 "NULL AS reloptions, "
4174 "NULL AS toast_reloptions "
4176 "LEFT JOIN pg_depend d ON "
4177 "(c.relkind = '%c' AND "
4178 "d.classid = c.tableoid AND d.objid = c.oid AND "
4179 "d.objsubid = 0 AND "
4180 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4181 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4185 RELKIND_RELATION, RELKIND_SEQUENCE,
4186 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4188 else if (fout->remoteVersion >= 70200)
4190 appendPQExpBuffer(query,
4191 "SELECT tableoid, oid, relname, relacl, relkind, "
4192 "0::oid AS relnamespace, "
4193 "(%s relowner) AS rolname, "
4194 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4195 "relhasindex, relhasrules, relhasoids, "
4196 "0 AS relfrozenxid, "
4199 "'p' AS relpersistence, "
4200 "NULL AS reloftype, "
4201 "NULL::oid AS owning_tab, "
4202 "NULL::int4 AS owning_col, "
4203 "NULL AS reltablespace, "
4204 "NULL AS reloptions, "
4205 "NULL AS toast_reloptions "
4207 "WHERE relkind IN ('%c', '%c', '%c') "
4210 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4212 else if (fout->remoteVersion >= 70100)
4214 /* all tables have oids in 7.1 */
4215 appendPQExpBuffer(query,
4216 "SELECT tableoid, oid, relname, relacl, relkind, "
4217 "0::oid AS relnamespace, "
4218 "(%s relowner) AS rolname, "
4219 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4220 "relhasindex, relhasrules, "
4221 "'t'::bool AS relhasoids, "
4222 "0 AS relfrozenxid, "
4225 "'p' AS relpersistence, "
4226 "NULL AS reloftype, "
4227 "NULL::oid AS owning_tab, "
4228 "NULL::int4 AS owning_col, "
4229 "NULL AS reltablespace, "
4230 "NULL AS reloptions, "
4231 "NULL AS toast_reloptions "
4233 "WHERE relkind IN ('%c', '%c', '%c') "
4236 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4241 * Before 7.1, view relkind was not set to 'v', so we must check if we
4242 * have a view by looking for a rule in pg_rewrite.
4244 appendPQExpBuffer(query,
4246 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4247 "oid, relname, relacl, "
4248 "CASE WHEN relhasrules and relkind = 'r' "
4249 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4250 " r.ev_class = c.oid AND r.ev_type = '1') "
4251 "THEN '%c'::\"char\" "
4252 "ELSE relkind END AS relkind,"
4253 "0::oid AS relnamespace, "
4254 "(%s relowner) AS rolname, "
4255 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4256 "relhasindex, relhasrules, "
4257 "'t'::bool AS relhasoids, "
4258 "0 as relfrozenxid, "
4261 "'p' AS relpersistence, "
4262 "NULL AS reloftype, "
4263 "NULL::oid AS owning_tab, "
4264 "NULL::int4 AS owning_col, "
4265 "NULL AS reltablespace, "
4266 "NULL AS reloptions, "
4267 "NULL AS toast_reloptions "
4269 "WHERE relkind IN ('%c', '%c') "
4273 RELKIND_RELATION, RELKIND_SEQUENCE);
4276 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4278 ntups = PQntuples(res);
4283 * Extract data from result and lock dumpable tables. We do the locking
4284 * before anything else, to minimize the window wherein a table could
4285 * disappear under us.
4287 * Note that we have to save info about all tables here, even when dumping
4288 * only one, because we don't yet know which tables might be inheritance
4289 * ancestors of the target table.
4291 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4293 i_reltableoid = PQfnumber(res, "tableoid");
4294 i_reloid = PQfnumber(res, "oid");
4295 i_relname = PQfnumber(res, "relname");
4296 i_relnamespace = PQfnumber(res, "relnamespace");
4297 i_relacl = PQfnumber(res, "relacl");
4298 i_relkind = PQfnumber(res, "relkind");
4299 i_rolname = PQfnumber(res, "rolname");
4300 i_relchecks = PQfnumber(res, "relchecks");
4301 i_relhastriggers = PQfnumber(res, "relhastriggers");
4302 i_relhasindex = PQfnumber(res, "relhasindex");
4303 i_relhasrules = PQfnumber(res, "relhasrules");
4304 i_relhasoids = PQfnumber(res, "relhasoids");
4305 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4306 i_toastoid = PQfnumber(res, "toid");
4307 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4308 i_relpersistence = PQfnumber(res, "relpersistence");
4309 i_owning_tab = PQfnumber(res, "owning_tab");
4310 i_owning_col = PQfnumber(res, "owning_col");
4311 i_reltablespace = PQfnumber(res, "reltablespace");
4312 i_reloptions = PQfnumber(res, "reloptions");
4313 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4314 i_reloftype = PQfnumber(res, "reloftype");
4316 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4319 * Arrange to fail instead of waiting forever for a table lock.
4321 * NB: this coding assumes that the only queries issued within the
4322 * following loop are LOCK TABLEs; else the timeout may be undesirably
4323 * applied to other things too.
4325 resetPQExpBuffer(query);
4326 appendPQExpBuffer(query, "SET statement_timeout = ");
4327 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4328 ExecuteSqlStatement(fout, query->data);
4331 for (i = 0; i < ntups; i++)
4333 tblinfo[i].dobj.objType = DO_TABLE;
4334 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4335 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4336 AssignDumpId(&tblinfo[i].dobj);
4337 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4338 tblinfo[i].dobj.namespace =
4340 atooid(PQgetvalue(res, i, i_relnamespace)),
4341 tblinfo[i].dobj.catId.oid);
4342 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4343 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4344 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4345 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4346 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4347 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4348 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4349 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4350 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4351 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4352 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4353 if (PQgetisnull(res, i, i_reloftype))
4354 tblinfo[i].reloftype = NULL;
4356 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4357 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4358 if (PQgetisnull(res, i, i_owning_tab))
4360 tblinfo[i].owning_tab = InvalidOid;
4361 tblinfo[i].owning_col = 0;
4365 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4366 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4368 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4369 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4370 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4372 /* other fields were zeroed above */
4375 * Decide whether we want to dump this table.
4377 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4378 tblinfo[i].dobj.dump = false;
4380 selectDumpableTable(&tblinfo[i]);
4381 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4384 * Read-lock target tables to make sure they aren't DROPPED or altered
4385 * in schema before we get around to dumping them.
4387 * Note that we don't explicitly lock parents of the target tables; we
4388 * assume our lock on the child is enough to prevent schema
4389 * alterations to parent tables.
4391 * NOTE: it'd be kinda nice to lock other relations too, not only
4392 * plain tables, but the backend doesn't presently allow that.
4394 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4396 resetPQExpBuffer(query);
4397 appendPQExpBuffer(query,
4398 "LOCK TABLE %s IN ACCESS SHARE MODE",
4399 fmtQualifiedId(fout,
4400 tblinfo[i].dobj.namespace->dobj.name,
4401 tblinfo[i].dobj.name));
4402 ExecuteSqlStatement(fout, query->data);
4405 /* Emit notice if join for owner failed */
4406 if (strlen(tblinfo[i].rolname) == 0)
4407 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4408 tblinfo[i].dobj.name);
4411 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4413 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4418 destroyPQExpBuffer(query);
4425 * identify owned sequences and mark them as dumpable if owning table is
4427 * We used to do this in getTables(), but it's better to do it after the
4428 * index used by findTableByOid() has been set up.
4431 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4436 * Force sequences that are "owned" by table columns to be dumped whenever
4437 * their owning table is being dumped.
4439 for (i = 0; i < numTables; i++)
4441 TableInfo *seqinfo = &tblinfo[i];
4442 TableInfo *owning_tab;
4444 if (!OidIsValid(seqinfo->owning_tab))
4445 continue; /* not an owned sequence */
4446 if (seqinfo->dobj.dump)
4447 continue; /* no need to search */
4448 owning_tab = findTableByOid(seqinfo->owning_tab);
4449 if (owning_tab && owning_tab->dobj.dump)
4451 seqinfo->interesting = true;
4452 seqinfo->dobj.dump = true;
4459 * read all the inheritance information
4460 * from the system catalogs return them in the InhInfo* structure
4462 * numInherits is set to the number of pairs read in
4465 getInherits(Archive *fout, int *numInherits)
4470 PQExpBuffer query = createPQExpBuffer();
4476 /* Make sure we are in proper schema */
4477 selectSourceSchema(fout, "pg_catalog");
4479 /* find all the inheritance information */
4481 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4483 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4485 ntups = PQntuples(res);
4487 *numInherits = ntups;
4489 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4491 i_inhrelid = PQfnumber(res, "inhrelid");
4492 i_inhparent = PQfnumber(res, "inhparent");
4494 for (i = 0; i < ntups; i++)
4496 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4497 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4502 destroyPQExpBuffer(query);
4509 * get information about every index on a dumpable table
4511 * Note: index data is not returned directly to the caller, but it
4512 * does get entered into the DumpableObject tables.
4515 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4519 PQExpBuffer query = createPQExpBuffer();
4522 ConstraintInfo *constrinfo;
4541 for (i = 0; i < numTables; i++)
4543 TableInfo *tbinfo = &tblinfo[i];
4545 /* Only plain tables have indexes */
4546 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4549 /* Ignore indexes of tables not to be dumped */
4550 if (!tbinfo->dobj.dump)
4554 write_msg(NULL, "reading indexes for table \"%s\"\n",
4557 /* Make sure we are in proper schema so indexdef is right */
4558 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4561 * The point of the messy-looking outer join is to find a constraint
4562 * that is related by an internal dependency link to the index. If we
4563 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4564 * assume an index won't have more than one internal dependency.
4566 * As of 9.0 we don't need to look at pg_depend but can check for a
4567 * match to pg_constraint.conindid. The check on conrelid is
4568 * redundant but useful because that column is indexed while conindid
4571 resetPQExpBuffer(query);
4572 if (fout->remoteVersion >= 90000)
4574 appendPQExpBuffer(query,
4575 "SELECT t.tableoid, t.oid, "
4576 "t.relname AS indexname, "
4577 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4578 "t.relnatts AS indnkeys, "
4579 "i.indkey, i.indisclustered, "
4580 "c.contype, c.conname, "
4581 "c.condeferrable, c.condeferred, "
4582 "c.tableoid AS contableoid, "
4584 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4585 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4586 "array_to_string(t.reloptions, ', ') AS options "
4587 "FROM pg_catalog.pg_index i "
4588 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4589 "LEFT JOIN pg_catalog.pg_constraint c "
4590 "ON (i.indrelid = c.conrelid AND "
4591 "i.indexrelid = c.conindid AND "
4592 "c.contype IN ('p','u','x')) "
4593 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4594 "ORDER BY indexname",
4595 tbinfo->dobj.catId.oid);
4597 else if (fout->remoteVersion >= 80200)
4599 appendPQExpBuffer(query,
4600 "SELECT t.tableoid, t.oid, "
4601 "t.relname AS indexname, "
4602 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4603 "t.relnatts AS indnkeys, "
4604 "i.indkey, i.indisclustered, "
4605 "c.contype, c.conname, "
4606 "c.condeferrable, c.condeferred, "
4607 "c.tableoid AS contableoid, "
4610 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4611 "array_to_string(t.reloptions, ', ') AS options "
4612 "FROM pg_catalog.pg_index i "
4613 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4614 "LEFT JOIN pg_catalog.pg_depend d "
4615 "ON (d.classid = t.tableoid "
4616 "AND d.objid = t.oid "
4617 "AND d.deptype = 'i') "
4618 "LEFT JOIN pg_catalog.pg_constraint c "
4619 "ON (d.refclassid = c.tableoid "
4620 "AND d.refobjid = c.oid) "
4621 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4622 "ORDER BY indexname",
4623 tbinfo->dobj.catId.oid);
4625 else if (fout->remoteVersion >= 80000)
4627 appendPQExpBuffer(query,
4628 "SELECT t.tableoid, t.oid, "
4629 "t.relname AS indexname, "
4630 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4631 "t.relnatts AS indnkeys, "
4632 "i.indkey, i.indisclustered, "
4633 "c.contype, c.conname, "
4634 "c.condeferrable, c.condeferred, "
4635 "c.tableoid AS contableoid, "
4638 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4640 "FROM pg_catalog.pg_index i "
4641 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4642 "LEFT JOIN pg_catalog.pg_depend d "
4643 "ON (d.classid = t.tableoid "
4644 "AND d.objid = t.oid "
4645 "AND d.deptype = 'i') "
4646 "LEFT JOIN pg_catalog.pg_constraint c "
4647 "ON (d.refclassid = c.tableoid "
4648 "AND d.refobjid = c.oid) "
4649 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4650 "ORDER BY indexname",
4651 tbinfo->dobj.catId.oid);
4653 else if (fout->remoteVersion >= 70300)
4655 appendPQExpBuffer(query,
4656 "SELECT t.tableoid, t.oid, "
4657 "t.relname AS indexname, "
4658 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4659 "t.relnatts AS indnkeys, "
4660 "i.indkey, i.indisclustered, "
4661 "c.contype, c.conname, "
4662 "c.condeferrable, c.condeferred, "
4663 "c.tableoid AS contableoid, "
4666 "NULL AS tablespace, "
4668 "FROM pg_catalog.pg_index i "
4669 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4670 "LEFT JOIN pg_catalog.pg_depend d "
4671 "ON (d.classid = t.tableoid "
4672 "AND d.objid = t.oid "
4673 "AND d.deptype = 'i') "
4674 "LEFT JOIN pg_catalog.pg_constraint c "
4675 "ON (d.refclassid = c.tableoid "
4676 "AND d.refobjid = c.oid) "
4677 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4678 "ORDER BY indexname",
4679 tbinfo->dobj.catId.oid);
4681 else if (fout->remoteVersion >= 70100)
4683 appendPQExpBuffer(query,
4684 "SELECT t.tableoid, t.oid, "
4685 "t.relname AS indexname, "
4686 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4687 "t.relnatts AS indnkeys, "
4688 "i.indkey, false AS indisclustered, "
4689 "CASE WHEN i.indisprimary THEN 'p'::char "
4690 "ELSE '0'::char END AS contype, "
4691 "t.relname AS conname, "
4692 "false AS condeferrable, "
4693 "false AS condeferred, "
4694 "0::oid AS contableoid, "
4697 "NULL AS tablespace, "
4699 "FROM pg_index i, pg_class t "
4700 "WHERE t.oid = i.indexrelid "
4701 "AND i.indrelid = '%u'::oid "
4702 "ORDER BY indexname",
4703 tbinfo->dobj.catId.oid);
4707 appendPQExpBuffer(query,
4709 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4711 "t.relname AS indexname, "
4712 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4713 "t.relnatts AS indnkeys, "
4714 "i.indkey, false AS indisclustered, "
4715 "CASE WHEN i.indisprimary THEN 'p'::char "
4716 "ELSE '0'::char END AS contype, "
4717 "t.relname AS conname, "
4718 "false AS condeferrable, "
4719 "false AS condeferred, "
4720 "0::oid AS contableoid, "
4723 "NULL AS tablespace, "
4725 "FROM pg_index i, pg_class t "
4726 "WHERE t.oid = i.indexrelid "
4727 "AND i.indrelid = '%u'::oid "
4728 "ORDER BY indexname",
4729 tbinfo->dobj.catId.oid);
4732 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4734 ntups = PQntuples(res);
4736 i_tableoid = PQfnumber(res, "tableoid");
4737 i_oid = PQfnumber(res, "oid");
4738 i_indexname = PQfnumber(res, "indexname");
4739 i_indexdef = PQfnumber(res, "indexdef");
4740 i_indnkeys = PQfnumber(res, "indnkeys");
4741 i_indkey = PQfnumber(res, "indkey");
4742 i_indisclustered = PQfnumber(res, "indisclustered");
4743 i_contype = PQfnumber(res, "contype");
4744 i_conname = PQfnumber(res, "conname");
4745 i_condeferrable = PQfnumber(res, "condeferrable");
4746 i_condeferred = PQfnumber(res, "condeferred");
4747 i_contableoid = PQfnumber(res, "contableoid");
4748 i_conoid = PQfnumber(res, "conoid");
4749 i_condef = PQfnumber(res, "condef");
4750 i_tablespace = PQfnumber(res, "tablespace");
4751 i_options = PQfnumber(res, "options");
4753 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4754 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4756 for (j = 0; j < ntups; j++)
4760 indxinfo[j].dobj.objType = DO_INDEX;
4761 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4762 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4763 AssignDumpId(&indxinfo[j].dobj);
4764 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4765 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4766 indxinfo[j].indextable = tbinfo;
4767 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4768 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4769 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4770 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4773 * In pre-7.4 releases, indkeys may contain more entries than
4774 * indnkeys says (since indnkeys will be 1 for a functional
4775 * index). We don't actually care about this case since we don't
4776 * examine indkeys except for indexes associated with PRIMARY and
4777 * UNIQUE constraints, which are never functional indexes. But we
4778 * have to allocate enough space to keep parseOidArray from
4781 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4782 parseOidArray(PQgetvalue(res, j, i_indkey),
4783 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4784 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4785 contype = *(PQgetvalue(res, j, i_contype));
4787 if (contype == 'p' || contype == 'u' || contype == 'x')
4790 * If we found a constraint matching the index, create an
4793 * In a pre-7.3 database, we take this path iff the index was
4794 * marked indisprimary.
4796 constrinfo[j].dobj.objType = DO_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 = contype;
4806 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4808 constrinfo[j].condef = NULL;
4809 constrinfo[j].confrelid = InvalidOid;
4810 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4811 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4812 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4813 constrinfo[j].conislocal = true;
4814 constrinfo[j].separate = true;
4816 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4818 /* If pre-7.3 DB, better make sure table comes first */
4819 addObjectDependency(&constrinfo[j].dobj,
4820 tbinfo->dobj.dumpId);
4824 /* Plain secondary index */
4825 indxinfo[j].indexconstraint = 0;
4832 destroyPQExpBuffer(query);
4838 * Get info about constraints on dumpable tables.
4840 * Currently handles foreign keys only.
4841 * Unique and primary key constraints are handled with indexes,
4842 * while check constraints are processed in getTableAttrs().
4845 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4849 ConstraintInfo *constrinfo;
4859 /* pg_constraint was created in 7.3, so nothing to do if older */
4860 if (fout->remoteVersion < 70300)
4863 query = createPQExpBuffer();
4865 for (i = 0; i < numTables; i++)
4867 TableInfo *tbinfo = &tblinfo[i];
4869 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4873 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4877 * select table schema to ensure constraint expr is qualified if
4880 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4882 resetPQExpBuffer(query);
4883 appendPQExpBuffer(query,
4884 "SELECT tableoid, oid, conname, confrelid, "
4885 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4886 "FROM pg_catalog.pg_constraint "
4887 "WHERE conrelid = '%u'::pg_catalog.oid "
4888 "AND contype = 'f'",
4889 tbinfo->dobj.catId.oid);
4890 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4892 ntups = PQntuples(res);
4894 i_contableoid = PQfnumber(res, "tableoid");
4895 i_conoid = PQfnumber(res, "oid");
4896 i_conname = PQfnumber(res, "conname");
4897 i_confrelid = PQfnumber(res, "confrelid");
4898 i_condef = PQfnumber(res, "condef");
4900 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4902 for (j = 0; j < ntups; j++)
4904 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4905 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4906 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4907 AssignDumpId(&constrinfo[j].dobj);
4908 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4909 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4910 constrinfo[j].contable = tbinfo;
4911 constrinfo[j].condomain = NULL;
4912 constrinfo[j].contype = 'f';
4913 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4914 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4915 constrinfo[j].conindex = 0;
4916 constrinfo[j].condeferrable = false;
4917 constrinfo[j].condeferred = false;
4918 constrinfo[j].conislocal = true;
4919 constrinfo[j].separate = true;
4925 destroyPQExpBuffer(query);
4929 * getDomainConstraints
4931 * Get info about constraints on a domain.
4934 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4937 ConstraintInfo *constrinfo;
4946 /* pg_constraint was created in 7.3, so nothing to do if older */
4947 if (fout->remoteVersion < 70300)
4951 * select appropriate schema to ensure names in constraint are properly
4954 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4956 query = createPQExpBuffer();
4958 if (fout->remoteVersion >= 90100)
4959 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4960 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4962 "FROM pg_catalog.pg_constraint "
4963 "WHERE contypid = '%u'::pg_catalog.oid "
4965 tyinfo->dobj.catId.oid);
4967 else if (fout->remoteVersion >= 70400)
4968 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4969 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4970 "true as convalidated "
4971 "FROM pg_catalog.pg_constraint "
4972 "WHERE contypid = '%u'::pg_catalog.oid "
4974 tyinfo->dobj.catId.oid);
4976 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4977 "'CHECK (' || consrc || ')' AS consrc, "
4978 "true as convalidated "
4979 "FROM pg_catalog.pg_constraint "
4980 "WHERE contypid = '%u'::pg_catalog.oid "
4982 tyinfo->dobj.catId.oid);
4984 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4986 ntups = PQntuples(res);
4988 i_tableoid = PQfnumber(res, "tableoid");
4989 i_oid = PQfnumber(res, "oid");
4990 i_conname = PQfnumber(res, "conname");
4991 i_consrc = PQfnumber(res, "consrc");
4993 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4995 tyinfo->nDomChecks = ntups;
4996 tyinfo->domChecks = constrinfo;
4998 for (i = 0; i < ntups; i++)
5000 bool validated = PQgetvalue(res, i, 4)[0] == 't';
5002 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5003 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5004 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5005 AssignDumpId(&constrinfo[i].dobj);
5006 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5007 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5008 constrinfo[i].contable = NULL;
5009 constrinfo[i].condomain = tyinfo;
5010 constrinfo[i].contype = 'c';
5011 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5012 constrinfo[i].confrelid = InvalidOid;
5013 constrinfo[i].conindex = 0;
5014 constrinfo[i].condeferrable = false;
5015 constrinfo[i].condeferred = false;
5016 constrinfo[i].conislocal = true;
5018 constrinfo[i].separate = !validated;
5021 * Make the domain depend on the constraint, ensuring it won't be
5022 * output till any constraint dependencies are OK. If the constraint
5023 * has not been validated, it's going to be dumped after the domain
5024 * anyway, so this doesn't matter.
5027 addObjectDependency(&tyinfo->dobj,
5028 constrinfo[i].dobj.dumpId);
5033 destroyPQExpBuffer(query);
5038 * get basic information about every rule in the system
5040 * numRules is set to the number of rules read in
5043 getRules(Archive *fout, int *numRules)
5048 PQExpBuffer query = createPQExpBuffer();
5058 /* Make sure we are in proper schema */
5059 selectSourceSchema(fout, "pg_catalog");
5061 if (fout->remoteVersion >= 80300)
5063 appendPQExpBuffer(query, "SELECT "
5064 "tableoid, oid, rulename, "
5065 "ev_class AS ruletable, ev_type, is_instead, "
5070 else if (fout->remoteVersion >= 70100)
5072 appendPQExpBuffer(query, "SELECT "
5073 "tableoid, oid, rulename, "
5074 "ev_class AS ruletable, ev_type, is_instead, "
5075 "'O'::char AS ev_enabled "
5081 appendPQExpBuffer(query, "SELECT "
5082 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5084 "ev_class AS ruletable, ev_type, is_instead, "
5085 "'O'::char AS ev_enabled "
5090 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5092 ntups = PQntuples(res);
5096 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5098 i_tableoid = PQfnumber(res, "tableoid");
5099 i_oid = PQfnumber(res, "oid");
5100 i_rulename = PQfnumber(res, "rulename");
5101 i_ruletable = PQfnumber(res, "ruletable");
5102 i_ev_type = PQfnumber(res, "ev_type");
5103 i_is_instead = PQfnumber(res, "is_instead");
5104 i_ev_enabled = PQfnumber(res, "ev_enabled");
5106 for (i = 0; i < ntups; i++)
5110 ruleinfo[i].dobj.objType = DO_RULE;
5111 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5112 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5113 AssignDumpId(&ruleinfo[i].dobj);
5114 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5115 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5116 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5117 if (ruleinfo[i].ruletable == NULL)
5118 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5119 ruletableoid, ruleinfo[i].dobj.catId.oid);
5120 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5121 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5122 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5123 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5124 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5125 if (ruleinfo[i].ruletable)
5128 * If the table is a view, force its ON SELECT rule to be sorted
5129 * before the view itself --- this ensures that any dependencies
5130 * for the rule affect the table's positioning. Other rules are
5131 * forced to appear after their table.
5133 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5134 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5136 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5137 ruleinfo[i].dobj.dumpId);
5138 /* We'll merge the rule into CREATE VIEW, if possible */
5139 ruleinfo[i].separate = false;
5143 addObjectDependency(&ruleinfo[i].dobj,
5144 ruleinfo[i].ruletable->dobj.dumpId);
5145 ruleinfo[i].separate = true;
5149 ruleinfo[i].separate = true;
5152 * If we're forced to break a dependency loop by dumping a view as a
5153 * table and separate _RETURN rule, we'll move the view's reloptions
5154 * to the rule. (This is necessary because tables and views have
5155 * different valid reloptions, so we can't apply the options until the
5156 * backend knows it's a view.) Otherwise the rule's reloptions stay
5159 ruleinfo[i].reloptions = NULL;
5164 destroyPQExpBuffer(query);
5171 * get information about every trigger on a dumpable table
5173 * Note: trigger data is not returned directly to the caller, but it
5174 * does get entered into the DumpableObject tables.
5177 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5181 PQExpBuffer query = createPQExpBuffer();
5183 TriggerInfo *tginfo;
5201 for (i = 0; i < numTables; i++)
5203 TableInfo *tbinfo = &tblinfo[i];
5205 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5209 write_msg(NULL, "reading triggers for table \"%s\"\n",
5213 * select table schema to ensure regproc name is qualified if needed
5215 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5217 resetPQExpBuffer(query);
5218 if (fout->remoteVersion >= 90000)
5221 * NB: think not to use pretty=true in pg_get_triggerdef. It
5222 * could result in non-forward-compatible dumps of WHEN clauses
5223 * due to under-parenthesization.
5225 appendPQExpBuffer(query,
5227 "tgfoid::pg_catalog.regproc AS tgfname, "
5228 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5229 "tgenabled, tableoid, oid "
5230 "FROM pg_catalog.pg_trigger t "
5231 "WHERE tgrelid = '%u'::pg_catalog.oid "
5232 "AND NOT tgisinternal",
5233 tbinfo->dobj.catId.oid);
5235 else if (fout->remoteVersion >= 80300)
5238 * We ignore triggers that are tied to a foreign-key constraint
5240 appendPQExpBuffer(query,
5242 "tgfoid::pg_catalog.regproc AS tgfname, "
5243 "tgtype, tgnargs, tgargs, tgenabled, "
5244 "tgisconstraint, tgconstrname, tgdeferrable, "
5245 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5246 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5247 "FROM pg_catalog.pg_trigger t "
5248 "WHERE tgrelid = '%u'::pg_catalog.oid "
5249 "AND tgconstraint = 0",
5250 tbinfo->dobj.catId.oid);
5252 else if (fout->remoteVersion >= 70300)
5255 * We ignore triggers that are tied to a foreign-key constraint,
5256 * but in these versions we have to grovel through pg_constraint
5259 appendPQExpBuffer(query,
5261 "tgfoid::pg_catalog.regproc AS tgfname, "
5262 "tgtype, tgnargs, tgargs, tgenabled, "
5263 "tgisconstraint, tgconstrname, tgdeferrable, "
5264 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5265 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5266 "FROM pg_catalog.pg_trigger t "
5267 "WHERE tgrelid = '%u'::pg_catalog.oid "
5268 "AND (NOT tgisconstraint "
5270 " (SELECT 1 FROM pg_catalog.pg_depend d "
5271 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5272 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5273 tbinfo->dobj.catId.oid);
5275 else if (fout->remoteVersion >= 70100)
5277 appendPQExpBuffer(query,
5278 "SELECT tgname, tgfoid::regproc AS tgfname, "
5279 "tgtype, tgnargs, tgargs, tgenabled, "
5280 "tgisconstraint, tgconstrname, tgdeferrable, "
5281 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5282 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5283 " AS tgconstrrelname "
5285 "WHERE tgrelid = '%u'::oid",
5286 tbinfo->dobj.catId.oid);
5290 appendPQExpBuffer(query,
5291 "SELECT tgname, tgfoid::regproc AS tgfname, "
5292 "tgtype, tgnargs, tgargs, tgenabled, "
5293 "tgisconstraint, tgconstrname, tgdeferrable, "
5294 "tgconstrrelid, tginitdeferred, "
5295 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5297 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5298 " AS tgconstrrelname "
5300 "WHERE tgrelid = '%u'::oid",
5301 tbinfo->dobj.catId.oid);
5303 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5305 ntups = PQntuples(res);
5307 i_tableoid = PQfnumber(res, "tableoid");
5308 i_oid = PQfnumber(res, "oid");
5309 i_tgname = PQfnumber(res, "tgname");
5310 i_tgfname = PQfnumber(res, "tgfname");
5311 i_tgtype = PQfnumber(res, "tgtype");
5312 i_tgnargs = PQfnumber(res, "tgnargs");
5313 i_tgargs = PQfnumber(res, "tgargs");
5314 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5315 i_tgconstrname = PQfnumber(res, "tgconstrname");
5316 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5317 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5318 i_tgenabled = PQfnumber(res, "tgenabled");
5319 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5320 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5321 i_tgdef = PQfnumber(res, "tgdef");
5323 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5325 for (j = 0; j < ntups; j++)
5327 tginfo[j].dobj.objType = DO_TRIGGER;
5328 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5329 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5330 AssignDumpId(&tginfo[j].dobj);
5331 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5332 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5333 tginfo[j].tgtable = tbinfo;
5334 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5337 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5339 /* remaining fields are not valid if we have tgdef */
5340 tginfo[j].tgfname = NULL;
5341 tginfo[j].tgtype = 0;
5342 tginfo[j].tgnargs = 0;
5343 tginfo[j].tgargs = NULL;
5344 tginfo[j].tgisconstraint = false;
5345 tginfo[j].tgdeferrable = false;
5346 tginfo[j].tginitdeferred = false;
5347 tginfo[j].tgconstrname = NULL;
5348 tginfo[j].tgconstrrelid = InvalidOid;
5349 tginfo[j].tgconstrrelname = NULL;
5353 tginfo[j].tgdef = NULL;
5355 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5356 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5357 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5358 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5359 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5360 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5361 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5363 if (tginfo[j].tgisconstraint)
5365 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5366 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5367 if (OidIsValid(tginfo[j].tgconstrrelid))
5369 if (PQgetisnull(res, j, i_tgconstrrelname))
5370 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5371 tginfo[j].dobj.name,
5373 tginfo[j].tgconstrrelid);
5374 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5377 tginfo[j].tgconstrrelname = NULL;
5381 tginfo[j].tgconstrname = NULL;
5382 tginfo[j].tgconstrrelid = InvalidOid;
5383 tginfo[j].tgconstrrelname = NULL;
5391 destroyPQExpBuffer(query);
5396 * get information about event triggers
5399 getEventTriggers(Archive *fout, int *numEventTriggers)
5402 PQExpBuffer query = createPQExpBuffer();
5404 EventTriggerInfo *evtinfo;
5415 /* Before 9.3, there are no event triggers */
5416 if (fout->remoteVersion < 90300)
5418 *numEventTriggers = 0;
5422 /* Make sure we are in proper schema */
5423 selectSourceSchema(fout, "pg_catalog");
5425 appendPQExpBuffer(query,
5426 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5427 "evtevent, (%s evtowner) AS evtowner, "
5428 "array_to_string(array("
5429 "select quote_literal(x) "
5430 " from unnest(evttags) as t(x)), ', ') as evttags, "
5431 "e.evtfoid::regproc as evtfname "
5432 "FROM pg_event_trigger e "
5436 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5438 ntups = PQntuples(res);
5440 *numEventTriggers = ntups;
5442 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5444 i_tableoid = PQfnumber(res, "tableoid");
5445 i_oid = PQfnumber(res, "oid");
5446 i_evtname = PQfnumber(res, "evtname");
5447 i_evtevent = PQfnumber(res, "evtevent");
5448 i_evtowner = PQfnumber(res, "evtowner");
5449 i_evttags = PQfnumber(res, "evttags");
5450 i_evtfname = PQfnumber(res, "evtfname");
5451 i_evtenabled = PQfnumber(res, "evtenabled");
5453 for (i = 0; i < ntups; i++)
5455 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5456 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5457 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5458 AssignDumpId(&evtinfo[i].dobj);
5459 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5460 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5461 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5462 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5463 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5464 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5465 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5470 destroyPQExpBuffer(query);
5477 * get basic information about every procedural language in the system
5479 * numProcLangs is set to the number of langs read in
5481 * NB: this must run after getFuncs() because we assume we can do
5485 getProcLangs(Archive *fout, int *numProcLangs)
5490 PQExpBuffer query = createPQExpBuffer();
5491 ProcLangInfo *planginfo;
5496 int i_lanplcallfoid;
5502 /* Make sure we are in proper schema */
5503 selectSourceSchema(fout, "pg_catalog");
5505 if (fout->remoteVersion >= 90000)
5507 /* pg_language has a laninline column */
5508 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5509 "lanname, lanpltrusted, lanplcallfoid, "
5510 "laninline, lanvalidator, lanacl, "
5511 "(%s lanowner) AS lanowner "
5517 else if (fout->remoteVersion >= 80300)
5519 /* pg_language has a lanowner column */
5520 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5521 "lanname, lanpltrusted, lanplcallfoid, "
5522 "lanvalidator, lanacl, "
5523 "(%s lanowner) AS lanowner "
5529 else if (fout->remoteVersion >= 80100)
5531 /* Languages are owned by the bootstrap superuser, OID 10 */
5532 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5533 "(%s '10') AS lanowner "
5539 else if (fout->remoteVersion >= 70400)
5541 /* Languages are owned by the bootstrap superuser, sysid 1 */
5542 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5543 "(%s '1') AS lanowner "
5549 else if (fout->remoteVersion >= 70100)
5551 /* No clear notion of an owner at all before 7.4 ... */
5552 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5558 appendPQExpBuffer(query, "SELECT "
5559 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5560 "oid, * FROM pg_language "
5565 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5567 ntups = PQntuples(res);
5569 *numProcLangs = ntups;
5571 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5573 i_tableoid = PQfnumber(res, "tableoid");
5574 i_oid = PQfnumber(res, "oid");
5575 i_lanname = PQfnumber(res, "lanname");
5576 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5577 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5578 /* these may fail and return -1: */
5579 i_laninline = PQfnumber(res, "laninline");
5580 i_lanvalidator = PQfnumber(res, "lanvalidator");
5581 i_lanacl = PQfnumber(res, "lanacl");
5582 i_lanowner = PQfnumber(res, "lanowner");
5584 for (i = 0; i < ntups; i++)
5586 planginfo[i].dobj.objType = DO_PROCLANG;
5587 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5588 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5589 AssignDumpId(&planginfo[i].dobj);
5591 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5592 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5593 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5594 if (i_laninline >= 0)
5595 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5597 planginfo[i].laninline = InvalidOid;
5598 if (i_lanvalidator >= 0)
5599 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5601 planginfo[i].lanvalidator = InvalidOid;
5603 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5605 planginfo[i].lanacl = pg_strdup("{=U}");
5606 if (i_lanowner >= 0)
5607 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5609 planginfo[i].lanowner = pg_strdup("");
5611 if (fout->remoteVersion < 70300)
5614 * We need to make a dependency to ensure the function will be
5615 * dumped first. (In 7.3 and later the regular dependency
5616 * mechanism will handle this for us.)
5618 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5621 addObjectDependency(&planginfo[i].dobj,
5622 funcInfo->dobj.dumpId);
5628 destroyPQExpBuffer(query);
5635 * get basic information about every cast in the system
5637 * numCasts is set to the number of casts read in
5640 getCasts(Archive *fout, int *numCasts)
5645 PQExpBuffer query = createPQExpBuffer();
5655 /* Make sure we are in proper schema */
5656 selectSourceSchema(fout, "pg_catalog");
5658 if (fout->remoteVersion >= 80400)
5660 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5661 "castsource, casttarget, castfunc, castcontext, "
5663 "FROM pg_cast ORDER BY 3,4");
5665 else if (fout->remoteVersion >= 70300)
5667 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5668 "castsource, casttarget, castfunc, castcontext, "
5669 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5670 "FROM pg_cast ORDER BY 3,4");
5674 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5675 "t1.oid AS castsource, t2.oid AS casttarget, "
5676 "p.oid AS castfunc, 'e' AS castcontext, "
5677 "'f' AS castmethod "
5678 "FROM pg_type t1, pg_type t2, pg_proc p "
5679 "WHERE p.pronargs = 1 AND "
5680 "p.proargtypes[0] = t1.oid AND "
5681 "p.prorettype = t2.oid AND p.proname = t2.typname "
5685 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5687 ntups = PQntuples(res);
5691 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5693 i_tableoid = PQfnumber(res, "tableoid");
5694 i_oid = PQfnumber(res, "oid");
5695 i_castsource = PQfnumber(res, "castsource");
5696 i_casttarget = PQfnumber(res, "casttarget");
5697 i_castfunc = PQfnumber(res, "castfunc");
5698 i_castcontext = PQfnumber(res, "castcontext");
5699 i_castmethod = PQfnumber(res, "castmethod");
5701 for (i = 0; i < ntups; i++)
5703 PQExpBufferData namebuf;
5704 TypeInfo *sTypeInfo;
5705 TypeInfo *tTypeInfo;
5707 castinfo[i].dobj.objType = DO_CAST;
5708 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5709 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5710 AssignDumpId(&castinfo[i].dobj);
5711 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5712 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5713 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5714 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5715 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5718 * Try to name cast as concatenation of typnames. This is only used
5719 * for purposes of sorting. If we fail to find either type, the name
5720 * will be an empty string.
5722 initPQExpBuffer(&namebuf);
5723 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5724 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5725 if (sTypeInfo && tTypeInfo)
5726 appendPQExpBuffer(&namebuf, "%s %s",
5727 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5728 castinfo[i].dobj.name = namebuf.data;
5730 if (OidIsValid(castinfo[i].castfunc))
5733 * We need to make a dependency to ensure the function will be
5734 * dumped first. (In 7.3 and later the regular dependency
5735 * mechanism will handle this for us.)
5739 funcInfo = findFuncByOid(castinfo[i].castfunc);
5741 addObjectDependency(&castinfo[i].dobj,
5742 funcInfo->dobj.dumpId);
5748 destroyPQExpBuffer(query);
5755 * for each interesting table, read info about its attributes
5756 * (names, types, default values, CHECK constraints, etc)
5758 * This is implemented in a very inefficient way right now, looping
5759 * through the tblinfo and doing a join per table to find the attrs and their
5760 * types. However, because we want type names and so forth to be named
5761 * relative to the schema of each table, we couldn't do it in just one
5762 * query. (Maybe one query per schema?)
5767 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5771 PQExpBuffer q = createPQExpBuffer();
5776 int i_attstattarget;
5787 int i_attfdwoptions;
5792 for (i = 0; i < numTables; i++)
5794 TableInfo *tbinfo = &tblinfo[i];
5796 /* Don't bother to collect info for sequences */
5797 if (tbinfo->relkind == RELKIND_SEQUENCE)
5800 /* Don't bother with uninteresting tables, either */
5801 if (!tbinfo->interesting)
5805 * Make sure we are in proper schema for this table; this allows
5806 * correct retrieval of formatted type names and default exprs
5808 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5810 /* find all the user attributes and their types */
5813 * we must read the attribute names in attribute number order! because
5814 * we will use the attnum to index into the attnames array later. We
5815 * actually ask to order by "attrelid, attnum" because (at least up to
5816 * 7.3) the planner is not smart enough to realize it needn't re-sort
5817 * the output of an indexscan on pg_attribute_relid_attnum_index.
5820 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5823 resetPQExpBuffer(q);
5825 if (fout->remoteVersion >= 90200)
5828 * attfdwoptions is new in 9.2.
5830 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5831 "a.attstattarget, a.attstorage, t.typstorage, "
5832 "a.attnotnull, a.atthasdef, a.attisdropped, "
5833 "a.attlen, a.attalign, a.attislocal, "
5834 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5835 "array_to_string(a.attoptions, ', ') AS attoptions, "
5836 "CASE WHEN a.attcollation <> t.typcollation "
5837 "THEN a.attcollation ELSE 0 END AS attcollation, "
5838 "pg_catalog.array_to_string(ARRAY("
5839 "SELECT pg_catalog.quote_ident(option_name) || "
5840 "' ' || pg_catalog.quote_literal(option_value) "
5841 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5842 "ORDER BY option_name"
5843 "), E',\n ') AS attfdwoptions "
5844 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5845 "ON a.atttypid = t.oid "
5846 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5847 "AND a.attnum > 0::pg_catalog.int2 "
5848 "ORDER BY a.attrelid, a.attnum",
5849 tbinfo->dobj.catId.oid);
5851 else if (fout->remoteVersion >= 90100)
5854 * attcollation is new in 9.1. Since we only want to dump COLLATE
5855 * clauses for attributes whose collation is different from their
5856 * type's default, we use a CASE here to suppress uninteresting
5857 * attcollations cheaply.
5859 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5860 "a.attstattarget, a.attstorage, t.typstorage, "
5861 "a.attnotnull, a.atthasdef, a.attisdropped, "
5862 "a.attlen, a.attalign, a.attislocal, "
5863 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5864 "array_to_string(a.attoptions, ', ') AS attoptions, "
5865 "CASE WHEN a.attcollation <> t.typcollation "
5866 "THEN a.attcollation ELSE 0 END AS attcollation, "
5867 "NULL AS attfdwoptions "
5868 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5869 "ON a.atttypid = t.oid "
5870 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5871 "AND a.attnum > 0::pg_catalog.int2 "
5872 "ORDER BY a.attrelid, a.attnum",
5873 tbinfo->dobj.catId.oid);
5875 else if (fout->remoteVersion >= 90000)
5877 /* attoptions is new in 9.0 */
5878 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5879 "a.attstattarget, a.attstorage, t.typstorage, "
5880 "a.attnotnull, a.atthasdef, a.attisdropped, "
5881 "a.attlen, a.attalign, a.attislocal, "
5882 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5883 "array_to_string(a.attoptions, ', ') AS attoptions, "
5884 "0 AS attcollation, "
5885 "NULL AS attfdwoptions "
5886 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5887 "ON a.atttypid = t.oid "
5888 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5889 "AND a.attnum > 0::pg_catalog.int2 "
5890 "ORDER BY a.attrelid, a.attnum",
5891 tbinfo->dobj.catId.oid);
5893 else if (fout->remoteVersion >= 70300)
5895 /* need left join here to not fail on dropped columns ... */
5896 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5897 "a.attstattarget, a.attstorage, t.typstorage, "
5898 "a.attnotnull, a.atthasdef, a.attisdropped, "
5899 "a.attlen, a.attalign, a.attislocal, "
5900 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5901 "'' AS attoptions, 0 AS attcollation, "
5902 "NULL AS attfdwoptions "
5903 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5904 "ON a.atttypid = t.oid "
5905 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5906 "AND a.attnum > 0::pg_catalog.int2 "
5907 "ORDER BY a.attrelid, a.attnum",
5908 tbinfo->dobj.catId.oid);
5910 else if (fout->remoteVersion >= 70100)
5913 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5914 * we don't dump it because we can't tell whether it's been
5915 * explicitly set or was just a default.
5917 * attislocal doesn't exist before 7.3, either; in older databases
5918 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5920 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5921 "-1 AS attstattarget, a.attstorage, "
5922 "t.typstorage, a.attnotnull, a.atthasdef, "
5923 "false AS attisdropped, a.attlen, "
5924 "a.attalign, true AS attislocal, "
5925 "format_type(t.oid,a.atttypmod) AS atttypname, "
5926 "'' AS attoptions, 0 AS attcollation, "
5927 "NULL AS attfdwoptions "
5928 "FROM pg_attribute a LEFT JOIN pg_type t "
5929 "ON a.atttypid = t.oid "
5930 "WHERE a.attrelid = '%u'::oid "
5931 "AND a.attnum > 0::int2 "
5932 "ORDER BY a.attrelid, a.attnum",
5933 tbinfo->dobj.catId.oid);
5937 /* format_type not available before 7.1 */
5938 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5939 "-1 AS attstattarget, "
5940 "attstorage, attstorage AS typstorage, "
5941 "attnotnull, atthasdef, false AS attisdropped, "
5942 "attlen, attalign, "
5943 "true AS attislocal, "
5944 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5945 "'' AS attoptions, 0 AS attcollation, "
5946 "NULL AS attfdwoptions "
5947 "FROM pg_attribute a "
5948 "WHERE attrelid = '%u'::oid "
5949 "AND attnum > 0::int2 "
5950 "ORDER BY attrelid, attnum",
5951 tbinfo->dobj.catId.oid);
5954 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5956 ntups = PQntuples(res);
5958 i_attnum = PQfnumber(res, "attnum");
5959 i_attname = PQfnumber(res, "attname");
5960 i_atttypname = PQfnumber(res, "atttypname");
5961 i_atttypmod = PQfnumber(res, "atttypmod");
5962 i_attstattarget = PQfnumber(res, "attstattarget");
5963 i_attstorage = PQfnumber(res, "attstorage");
5964 i_typstorage = PQfnumber(res, "typstorage");
5965 i_attnotnull = PQfnumber(res, "attnotnull");
5966 i_atthasdef = PQfnumber(res, "atthasdef");
5967 i_attisdropped = PQfnumber(res, "attisdropped");
5968 i_attlen = PQfnumber(res, "attlen");
5969 i_attalign = PQfnumber(res, "attalign");
5970 i_attislocal = PQfnumber(res, "attislocal");
5971 i_attoptions = PQfnumber(res, "attoptions");
5972 i_attcollation = PQfnumber(res, "attcollation");
5973 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5975 tbinfo->numatts = ntups;
5976 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5977 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5978 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5979 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5980 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5981 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5982 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5983 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5984 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5985 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5986 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5987 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5988 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5989 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5990 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5991 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5992 hasdefaults = false;
5994 for (j = 0; j < ntups; j++)
5996 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5998 "invalid column numbering in table \"%s\"\n",
6000 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6001 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6002 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6003 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6004 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6005 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6006 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6007 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6008 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6009 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6010 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6011 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6012 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6013 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6014 tbinfo->attrdefs[j] = NULL; /* fix below */
6015 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6017 /* these flags will be set in flagInhAttrs() */
6018 tbinfo->inhNotNull[j] = false;
6024 * Get info about column defaults
6028 AttrDefInfo *attrdefs;
6032 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6035 resetPQExpBuffer(q);
6036 if (fout->remoteVersion >= 70300)
6038 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6039 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6040 "FROM pg_catalog.pg_attrdef "
6041 "WHERE adrelid = '%u'::pg_catalog.oid",
6042 tbinfo->dobj.catId.oid);
6044 else if (fout->remoteVersion >= 70200)
6046 /* 7.2 did not have OIDs in pg_attrdef */
6047 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6048 "pg_get_expr(adbin, adrelid) AS adsrc "
6050 "WHERE adrelid = '%u'::oid",
6051 tbinfo->dobj.catId.oid);
6053 else if (fout->remoteVersion >= 70100)
6055 /* no pg_get_expr, so must rely on adsrc */
6056 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6058 "WHERE adrelid = '%u'::oid",
6059 tbinfo->dobj.catId.oid);
6063 /* no pg_get_expr, no tableoid either */
6064 appendPQExpBuffer(q, "SELECT "
6065 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6066 "oid, adnum, adsrc "
6068 "WHERE adrelid = '%u'::oid",
6069 tbinfo->dobj.catId.oid);
6071 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6073 numDefaults = PQntuples(res);
6074 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6076 for (j = 0; j < numDefaults; j++)
6080 adnum = atoi(PQgetvalue(res, j, 2));
6082 if (adnum <= 0 || adnum > ntups)
6084 "invalid adnum value %d for table \"%s\"\n",
6085 adnum, tbinfo->dobj.name);
6088 * dropped columns shouldn't have defaults, but just in case,
6091 if (tbinfo->attisdropped[adnum - 1])
6094 attrdefs[j].dobj.objType = DO_ATTRDEF;
6095 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6096 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6097 AssignDumpId(&attrdefs[j].dobj);
6098 attrdefs[j].adtable = tbinfo;
6099 attrdefs[j].adnum = adnum;
6100 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6102 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6103 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6105 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6108 * Defaults on a VIEW must always be dumped as separate ALTER
6109 * TABLE commands. Defaults on regular tables are dumped as
6110 * part of the CREATE TABLE if possible, which it won't be if
6111 * the column is not going to be emitted explicitly.
6113 if (tbinfo->relkind == RELKIND_VIEW)
6115 attrdefs[j].separate = true;
6116 /* needed in case pre-7.3 DB: */
6117 addObjectDependency(&attrdefs[j].dobj,
6118 tbinfo->dobj.dumpId);
6120 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6122 /* column will be suppressed, print default separately */
6123 attrdefs[j].separate = true;
6124 /* needed in case pre-7.3 DB: */
6125 addObjectDependency(&attrdefs[j].dobj,
6126 tbinfo->dobj.dumpId);
6130 attrdefs[j].separate = false;
6133 * Mark the default as needing to appear before the table,
6134 * so that any dependencies it has must be emitted before
6135 * the CREATE TABLE. If this is not possible, we'll
6136 * change to "separate" mode while sorting dependencies.
6138 addObjectDependency(&tbinfo->dobj,
6139 attrdefs[j].dobj.dumpId);
6142 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6148 * Get info about table CHECK constraints
6150 if (tbinfo->ncheck > 0)
6152 ConstraintInfo *constrs;
6156 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6159 resetPQExpBuffer(q);
6160 if (fout->remoteVersion >= 90200)
6163 * convalidated is new in 9.2 (actually, it is there in 9.1,
6164 * but it wasn't ever false for check constraints until 9.2).
6166 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6167 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6168 "conislocal, convalidated "
6169 "FROM pg_catalog.pg_constraint "
6170 "WHERE conrelid = '%u'::pg_catalog.oid "
6171 " AND contype = 'c' "
6173 tbinfo->dobj.catId.oid);
6175 else if (fout->remoteVersion >= 80400)
6177 /* conislocal is new in 8.4 */
6178 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6179 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6180 "conislocal, true AS convalidated "
6181 "FROM pg_catalog.pg_constraint "
6182 "WHERE conrelid = '%u'::pg_catalog.oid "
6183 " AND contype = 'c' "
6185 tbinfo->dobj.catId.oid);
6187 else if (fout->remoteVersion >= 70400)
6189 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6190 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6191 "true AS conislocal, true AS convalidated "
6192 "FROM pg_catalog.pg_constraint "
6193 "WHERE conrelid = '%u'::pg_catalog.oid "
6194 " AND contype = 'c' "
6196 tbinfo->dobj.catId.oid);
6198 else if (fout->remoteVersion >= 70300)
6200 /* no pg_get_constraintdef, must use consrc */
6201 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6202 "'CHECK (' || consrc || ')' AS consrc, "
6203 "true AS conislocal, true AS convalidated "
6204 "FROM pg_catalog.pg_constraint "
6205 "WHERE conrelid = '%u'::pg_catalog.oid "
6206 " AND contype = 'c' "
6208 tbinfo->dobj.catId.oid);
6210 else if (fout->remoteVersion >= 70200)
6212 /* 7.2 did not have OIDs in pg_relcheck */
6213 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6214 "rcname AS conname, "
6215 "'CHECK (' || rcsrc || ')' AS consrc, "
6216 "true AS conislocal, true AS convalidated "
6218 "WHERE rcrelid = '%u'::oid "
6220 tbinfo->dobj.catId.oid);
6222 else if (fout->remoteVersion >= 70100)
6224 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6225 "rcname AS conname, "
6226 "'CHECK (' || rcsrc || ')' AS consrc, "
6227 "true AS conislocal, true AS convalidated "
6229 "WHERE rcrelid = '%u'::oid "
6231 tbinfo->dobj.catId.oid);
6235 /* no tableoid in 7.0 */
6236 appendPQExpBuffer(q, "SELECT "
6237 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6238 "oid, rcname AS conname, "
6239 "'CHECK (' || rcsrc || ')' AS consrc, "
6240 "true AS conislocal, true AS convalidated "
6242 "WHERE rcrelid = '%u'::oid "
6244 tbinfo->dobj.catId.oid);
6246 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6248 numConstrs = PQntuples(res);
6249 if (numConstrs != tbinfo->ncheck)
6251 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6252 "expected %d check constraints on table \"%s\" but found %d\n",
6254 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6255 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6259 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6260 tbinfo->checkexprs = constrs;
6262 for (j = 0; j < numConstrs; j++)
6264 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6266 constrs[j].dobj.objType = DO_CONSTRAINT;
6267 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6268 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6269 AssignDumpId(&constrs[j].dobj);
6270 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6271 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6272 constrs[j].contable = tbinfo;
6273 constrs[j].condomain = NULL;
6274 constrs[j].contype = 'c';
6275 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6276 constrs[j].confrelid = InvalidOid;
6277 constrs[j].conindex = 0;
6278 constrs[j].condeferrable = false;
6279 constrs[j].condeferred = false;
6280 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6283 * An unvalidated constraint needs to be dumped separately, so
6284 * that potentially-violating existing data is loaded before
6287 constrs[j].separate = !validated;
6289 constrs[j].dobj.dump = tbinfo->dobj.dump;
6292 * Mark the constraint as needing to appear before the table
6293 * --- this is so that any other dependencies of the
6294 * constraint will be emitted before we try to create the
6295 * table. If the constraint is to be dumped separately, it
6296 * will be dumped after data is loaded anyway, so don't do it.
6297 * (There's an automatic dependency in the opposite direction
6298 * anyway, so don't need to add one manually here.)
6300 if (!constrs[j].separate)
6301 addObjectDependency(&tbinfo->dobj,
6302 constrs[j].dobj.dumpId);
6305 * If the constraint is inherited, this will be detected later
6306 * (in pre-8.4 databases). We also detect later if the
6307 * constraint must be split out from the table definition.
6314 destroyPQExpBuffer(q);
6318 * Test whether a column should be printed as part of table's CREATE TABLE.
6319 * Column number is zero-based.
6321 * Normally this is always true, but it's false for dropped columns, as well
6322 * as those that were inherited without any local definition. (If we print
6323 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6324 * However, in binary_upgrade mode, we must print all such columns anyway and
6325 * fix the attislocal/attisdropped state later, so as to keep control of the
6326 * physical column order.
6328 * This function exists because there are scattered nonobvious places that
6329 * must be kept in sync with this decision.
6332 shouldPrintColumn(TableInfo *tbinfo, int colno)
6336 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6342 * read all text search parsers in the system catalogs and return them
6343 * in the TSParserInfo* structure
6345 * numTSParsers is set to the number of parsers read in
6348 getTSParsers(Archive *fout, int *numTSParsers)
6354 TSParserInfo *prsinfo;
6365 /* Before 8.3, there is no built-in text search support */
6366 if (fout->remoteVersion < 80300)
6372 query = createPQExpBuffer();
6375 * find all text search objects, including builtin ones; we filter out
6376 * system-defined objects at dump-out time.
6379 /* Make sure we are in proper schema */
6380 selectSourceSchema(fout, "pg_catalog");
6382 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6383 "prsstart::oid, prstoken::oid, "
6384 "prsend::oid, prsheadline::oid, prslextype::oid "
6385 "FROM pg_ts_parser");
6387 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6389 ntups = PQntuples(res);
6390 *numTSParsers = ntups;
6392 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6394 i_tableoid = PQfnumber(res, "tableoid");
6395 i_oid = PQfnumber(res, "oid");
6396 i_prsname = PQfnumber(res, "prsname");
6397 i_prsnamespace = PQfnumber(res, "prsnamespace");
6398 i_prsstart = PQfnumber(res, "prsstart");
6399 i_prstoken = PQfnumber(res, "prstoken");
6400 i_prsend = PQfnumber(res, "prsend");
6401 i_prsheadline = PQfnumber(res, "prsheadline");
6402 i_prslextype = PQfnumber(res, "prslextype");
6404 for (i = 0; i < ntups; i++)
6406 prsinfo[i].dobj.objType = DO_TSPARSER;
6407 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6408 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6409 AssignDumpId(&prsinfo[i].dobj);
6410 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6411 prsinfo[i].dobj.namespace =
6413 atooid(PQgetvalue(res, i, i_prsnamespace)),
6414 prsinfo[i].dobj.catId.oid);
6415 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6416 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6417 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6418 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6419 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6421 /* Decide whether we want to dump it */
6422 selectDumpableObject(&(prsinfo[i].dobj));
6427 destroyPQExpBuffer(query);
6433 * getTSDictionaries:
6434 * read all text search dictionaries in the system catalogs and return them
6435 * in the TSDictInfo* structure
6437 * numTSDicts is set to the number of dictionaries read in
6440 getTSDictionaries(Archive *fout, int *numTSDicts)
6446 TSDictInfo *dictinfo;
6450 int i_dictnamespace;
6453 int i_dictinitoption;
6455 /* Before 8.3, there is no built-in text search support */
6456 if (fout->remoteVersion < 80300)
6462 query = createPQExpBuffer();
6464 /* Make sure we are in proper schema */
6465 selectSourceSchema(fout, "pg_catalog");
6467 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6468 "dictnamespace, (%s dictowner) AS rolname, "
6469 "dicttemplate, dictinitoption "
6473 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6475 ntups = PQntuples(res);
6476 *numTSDicts = ntups;
6478 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6480 i_tableoid = PQfnumber(res, "tableoid");
6481 i_oid = PQfnumber(res, "oid");
6482 i_dictname = PQfnumber(res, "dictname");
6483 i_dictnamespace = PQfnumber(res, "dictnamespace");
6484 i_rolname = PQfnumber(res, "rolname");
6485 i_dictinitoption = PQfnumber(res, "dictinitoption");
6486 i_dicttemplate = PQfnumber(res, "dicttemplate");
6488 for (i = 0; i < ntups; i++)
6490 dictinfo[i].dobj.objType = DO_TSDICT;
6491 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6492 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6493 AssignDumpId(&dictinfo[i].dobj);
6494 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6495 dictinfo[i].dobj.namespace =
6497 atooid(PQgetvalue(res, i, i_dictnamespace)),
6498 dictinfo[i].dobj.catId.oid);
6499 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6500 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6501 if (PQgetisnull(res, i, i_dictinitoption))
6502 dictinfo[i].dictinitoption = NULL;
6504 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6506 /* Decide whether we want to dump it */
6507 selectDumpableObject(&(dictinfo[i].dobj));
6512 destroyPQExpBuffer(query);
6519 * read all text search templates in the system catalogs and return them
6520 * in the TSTemplateInfo* structure
6522 * numTSTemplates is set to the number of templates read in
6525 getTSTemplates(Archive *fout, int *numTSTemplates)
6531 TSTemplateInfo *tmplinfo;
6535 int i_tmplnamespace;
6539 /* Before 8.3, there is no built-in text search support */
6540 if (fout->remoteVersion < 80300)
6542 *numTSTemplates = 0;
6546 query = createPQExpBuffer();
6548 /* Make sure we are in proper schema */
6549 selectSourceSchema(fout, "pg_catalog");
6551 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6552 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6553 "FROM pg_ts_template");
6555 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6557 ntups = PQntuples(res);
6558 *numTSTemplates = ntups;
6560 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6562 i_tableoid = PQfnumber(res, "tableoid");
6563 i_oid = PQfnumber(res, "oid");
6564 i_tmplname = PQfnumber(res, "tmplname");
6565 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6566 i_tmplinit = PQfnumber(res, "tmplinit");
6567 i_tmpllexize = PQfnumber(res, "tmpllexize");
6569 for (i = 0; i < ntups; i++)
6571 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6572 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6573 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6574 AssignDumpId(&tmplinfo[i].dobj);
6575 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6576 tmplinfo[i].dobj.namespace =
6578 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6579 tmplinfo[i].dobj.catId.oid);
6580 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6581 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6583 /* Decide whether we want to dump it */
6584 selectDumpableObject(&(tmplinfo[i].dobj));
6589 destroyPQExpBuffer(query);
6595 * getTSConfigurations:
6596 * read all text search configurations in the system catalogs and return
6597 * them in the TSConfigInfo* structure
6599 * numTSConfigs is set to the number of configurations read in
6602 getTSConfigurations(Archive *fout, int *numTSConfigs)
6608 TSConfigInfo *cfginfo;
6616 /* Before 8.3, there is no built-in text search support */
6617 if (fout->remoteVersion < 80300)
6623 query = createPQExpBuffer();
6625 /* Make sure we are in proper schema */
6626 selectSourceSchema(fout, "pg_catalog");
6628 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6629 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6630 "FROM pg_ts_config",
6633 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6635 ntups = PQntuples(res);
6636 *numTSConfigs = ntups;
6638 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6640 i_tableoid = PQfnumber(res, "tableoid");
6641 i_oid = PQfnumber(res, "oid");
6642 i_cfgname = PQfnumber(res, "cfgname");
6643 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6644 i_rolname = PQfnumber(res, "rolname");
6645 i_cfgparser = PQfnumber(res, "cfgparser");
6647 for (i = 0; i < ntups; i++)
6649 cfginfo[i].dobj.objType = DO_TSCONFIG;
6650 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6651 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6652 AssignDumpId(&cfginfo[i].dobj);
6653 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6654 cfginfo[i].dobj.namespace =
6656 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6657 cfginfo[i].dobj.catId.oid);
6658 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6659 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6661 /* Decide whether we want to dump it */
6662 selectDumpableObject(&(cfginfo[i].dobj));
6667 destroyPQExpBuffer(query);
6673 * getForeignDataWrappers:
6674 * read all foreign-data wrappers in the system catalogs and return
6675 * them in the FdwInfo* structure
6677 * numForeignDataWrappers is set to the number of fdws read in
6680 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6685 PQExpBuffer query = createPQExpBuffer();
6696 /* Before 8.4, there are no foreign-data wrappers */
6697 if (fout->remoteVersion < 80400)
6699 *numForeignDataWrappers = 0;
6703 /* Make sure we are in proper schema */
6704 selectSourceSchema(fout, "pg_catalog");
6706 if (fout->remoteVersion >= 90100)
6708 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6709 "(%s fdwowner) AS rolname, "
6710 "fdwhandler::pg_catalog.regproc, "
6711 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6712 "array_to_string(ARRAY("
6713 "SELECT quote_ident(option_name) || ' ' || "
6714 "quote_literal(option_value) "
6715 "FROM pg_options_to_table(fdwoptions) "
6716 "ORDER BY option_name"
6717 "), E',\n ') AS fdwoptions "
6718 "FROM pg_foreign_data_wrapper",
6723 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6724 "(%s fdwowner) AS rolname, "
6725 "'-' AS fdwhandler, "
6726 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6727 "array_to_string(ARRAY("
6728 "SELECT quote_ident(option_name) || ' ' || "
6729 "quote_literal(option_value) "
6730 "FROM pg_options_to_table(fdwoptions) "
6731 "ORDER BY option_name"
6732 "), E',\n ') AS fdwoptions "
6733 "FROM pg_foreign_data_wrapper",
6737 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6739 ntups = PQntuples(res);
6740 *numForeignDataWrappers = ntups;
6742 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6744 i_tableoid = PQfnumber(res, "tableoid");
6745 i_oid = PQfnumber(res, "oid");
6746 i_fdwname = PQfnumber(res, "fdwname");
6747 i_rolname = PQfnumber(res, "rolname");
6748 i_fdwhandler = PQfnumber(res, "fdwhandler");
6749 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6750 i_fdwacl = PQfnumber(res, "fdwacl");
6751 i_fdwoptions = PQfnumber(res, "fdwoptions");
6753 for (i = 0; i < ntups; i++)
6755 fdwinfo[i].dobj.objType = DO_FDW;
6756 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6757 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6758 AssignDumpId(&fdwinfo[i].dobj);
6759 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6760 fdwinfo[i].dobj.namespace = NULL;
6761 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6762 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6763 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6764 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6765 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6767 /* Decide whether we want to dump it */
6768 selectDumpableObject(&(fdwinfo[i].dobj));
6773 destroyPQExpBuffer(query);
6779 * getForeignServers:
6780 * read all foreign servers in the system catalogs and return
6781 * them in the ForeignServerInfo * structure
6783 * numForeignServers is set to the number of servers read in
6786 getForeignServers(Archive *fout, int *numForeignServers)
6791 PQExpBuffer query = createPQExpBuffer();
6792 ForeignServerInfo *srvinfo;
6803 /* Before 8.4, there are no foreign servers */
6804 if (fout->remoteVersion < 80400)
6806 *numForeignServers = 0;
6810 /* Make sure we are in proper schema */
6811 selectSourceSchema(fout, "pg_catalog");
6813 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6814 "(%s srvowner) AS rolname, "
6815 "srvfdw, srvtype, srvversion, srvacl,"
6816 "array_to_string(ARRAY("
6817 "SELECT quote_ident(option_name) || ' ' || "
6818 "quote_literal(option_value) "
6819 "FROM pg_options_to_table(srvoptions) "
6820 "ORDER BY option_name"
6821 "), E',\n ') AS srvoptions "
6822 "FROM pg_foreign_server",
6825 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6827 ntups = PQntuples(res);
6828 *numForeignServers = ntups;
6830 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6832 i_tableoid = PQfnumber(res, "tableoid");
6833 i_oid = PQfnumber(res, "oid");
6834 i_srvname = PQfnumber(res, "srvname");
6835 i_rolname = PQfnumber(res, "rolname");
6836 i_srvfdw = PQfnumber(res, "srvfdw");
6837 i_srvtype = PQfnumber(res, "srvtype");
6838 i_srvversion = PQfnumber(res, "srvversion");
6839 i_srvacl = PQfnumber(res, "srvacl");
6840 i_srvoptions = PQfnumber(res, "srvoptions");
6842 for (i = 0; i < ntups; i++)
6844 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6845 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6846 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6847 AssignDumpId(&srvinfo[i].dobj);
6848 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6849 srvinfo[i].dobj.namespace = NULL;
6850 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6851 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6852 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6853 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6854 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6855 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6857 /* Decide whether we want to dump it */
6858 selectDumpableObject(&(srvinfo[i].dobj));
6863 destroyPQExpBuffer(query);
6870 * read all default ACL information in the system catalogs and return
6871 * them in the DefaultACLInfo structure
6873 * numDefaultACLs is set to the number of ACLs read in
6876 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6878 DefaultACLInfo *daclinfo;
6884 int i_defaclnamespace;
6885 int i_defaclobjtype;
6890 if (fout->remoteVersion < 90000)
6892 *numDefaultACLs = 0;
6896 query = createPQExpBuffer();
6898 /* Make sure we are in proper schema */
6899 selectSourceSchema(fout, "pg_catalog");
6901 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6902 "(%s defaclrole) AS defaclrole, "
6906 "FROM pg_default_acl",
6909 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6911 ntups = PQntuples(res);
6912 *numDefaultACLs = ntups;
6914 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6916 i_oid = PQfnumber(res, "oid");
6917 i_tableoid = PQfnumber(res, "tableoid");
6918 i_defaclrole = PQfnumber(res, "defaclrole");
6919 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6920 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6921 i_defaclacl = PQfnumber(res, "defaclacl");
6923 for (i = 0; i < ntups; i++)
6925 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6927 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6928 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6929 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6930 AssignDumpId(&daclinfo[i].dobj);
6931 /* cheesy ... is it worth coming up with a better object name? */
6932 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6934 if (nspid != InvalidOid)
6935 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6936 daclinfo[i].dobj.catId.oid);
6938 daclinfo[i].dobj.namespace = NULL;
6940 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6941 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6942 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6944 /* Decide whether we want to dump it */
6945 selectDumpableDefaultACL(&(daclinfo[i]));
6950 destroyPQExpBuffer(query);
6958 * This routine is used to dump any comments associated with the
6959 * object handed to this routine. The routine takes a constant character
6960 * string for the target part of the comment-creation command, plus
6961 * the namespace and owner of the object (for labeling the ArchiveEntry),
6962 * plus catalog ID and subid which are the lookup key for pg_description,
6963 * plus the dump ID for the object (for setting a dependency).
6964 * If a matching pg_description entry is found, it is dumped.
6966 * Note: although this routine takes a dumpId for dependency purposes,
6967 * that purpose is just to mark the dependency in the emitted dump file
6968 * for possible future use by pg_restore. We do NOT use it for determining
6969 * ordering of the comment in the dump file, because this routine is called
6970 * after dependency sorting occurs. This routine should be called just after
6971 * calling ArchiveEntry() for the specified object.
6974 dumpComment(Archive *fout, const char *target,
6975 const char *namespace, const char *owner,
6976 CatalogId catalogId, int subid, DumpId dumpId)
6978 CommentItem *comments;
6981 /* Comments are schema not data ... except blob comments are data */
6982 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6993 /* Search for comments associated with catalogId, using table */
6994 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6997 /* Is there one matching the subid? */
6998 while (ncomments > 0)
7000 if (comments->objsubid == subid)
7006 /* If a comment exists, build COMMENT ON statement */
7009 PQExpBuffer query = createPQExpBuffer();
7011 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7012 appendStringLiteralAH(query, comments->descr, fout);
7013 appendPQExpBuffer(query, ";\n");
7016 * We mark comments as SECTION_NONE because they really belong in the
7017 * same section as their parent, whether that is pre-data or
7020 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7021 target, namespace, NULL, owner,
7022 false, "COMMENT", SECTION_NONE,
7023 query->data, "", NULL,
7027 destroyPQExpBuffer(query);
7032 * dumpTableComment --
7034 * As above, but dump comments for both the specified table (or view)
7038 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7039 const char *reltypename)
7041 CommentItem *comments;
7046 /* Comments are SCHEMA not data */
7050 /* Search for comments associated with relation, using table */
7051 ncomments = findComments(fout,
7052 tbinfo->dobj.catId.tableoid,
7053 tbinfo->dobj.catId.oid,
7056 /* If comments exist, build COMMENT ON statements */
7060 query = createPQExpBuffer();
7061 target = createPQExpBuffer();
7063 while (ncomments > 0)
7065 const char *descr = comments->descr;
7066 int objsubid = comments->objsubid;
7070 resetPQExpBuffer(target);
7071 appendPQExpBuffer(target, "%s %s", reltypename,
7072 fmtId(tbinfo->dobj.name));
7074 resetPQExpBuffer(query);
7075 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7076 appendStringLiteralAH(query, descr, fout);
7077 appendPQExpBuffer(query, ";\n");
7079 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7081 tbinfo->dobj.namespace->dobj.name,
7082 NULL, tbinfo->rolname,
7083 false, "COMMENT", SECTION_NONE,
7084 query->data, "", NULL,
7085 &(tbinfo->dobj.dumpId), 1,
7088 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7090 resetPQExpBuffer(target);
7091 appendPQExpBuffer(target, "COLUMN %s.",
7092 fmtId(tbinfo->dobj.name));
7093 appendPQExpBuffer(target, "%s",
7094 fmtId(tbinfo->attnames[objsubid - 1]));
7096 resetPQExpBuffer(query);
7097 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7098 appendStringLiteralAH(query, descr, fout);
7099 appendPQExpBuffer(query, ";\n");
7101 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7103 tbinfo->dobj.namespace->dobj.name,
7104 NULL, tbinfo->rolname,
7105 false, "COMMENT", SECTION_NONE,
7106 query->data, "", NULL,
7107 &(tbinfo->dobj.dumpId), 1,
7115 destroyPQExpBuffer(query);
7116 destroyPQExpBuffer(target);
7122 * Find the comment(s), if any, associated with the given object. All the
7123 * objsubid values associated with the given classoid/objoid are found with
7127 findComments(Archive *fout, Oid classoid, Oid objoid,
7128 CommentItem **items)
7130 /* static storage for table of comments */
7131 static CommentItem *comments = NULL;
7132 static int ncomments = -1;
7134 CommentItem *middle = NULL;
7139 /* Get comments if we didn't already */
7141 ncomments = collectComments(fout, &comments);
7144 * Pre-7.2, pg_description does not contain classoid, so collectComments
7145 * just stores a zero. If there's a collision on object OID, well, you
7146 * get duplicate comments.
7148 if (fout->remoteVersion < 70200)
7152 * Do binary search to find some item matching the object.
7155 high = &comments[ncomments - 1];
7158 middle = low + (high - low) / 2;
7160 if (classoid < middle->classoid)
7162 else if (classoid > middle->classoid)
7164 else if (objoid < middle->objoid)
7166 else if (objoid > middle->objoid)
7169 break; /* found a match */
7172 if (low > high) /* no matches */
7179 * Now determine how many items match the object. The search loop
7180 * invariant still holds: only items between low and high inclusive could
7184 while (middle > low)
7186 if (classoid != middle[-1].classoid ||
7187 objoid != middle[-1].objoid)
7196 while (middle <= high)
7198 if (classoid != middle->classoid ||
7199 objoid != middle->objoid)
7209 * collectComments --
7211 * Construct a table of all comments available for database objects.
7212 * We used to do per-object queries for the comments, but it's much faster
7213 * to pull them all over at once, and on most databases the memory cost
7216 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7219 collectComments(Archive *fout, CommentItem **items)
7229 CommentItem *comments;
7232 * Note we do NOT change source schema here; preserve the caller's
7236 query = createPQExpBuffer();
7238 if (fout->remoteVersion >= 70300)
7240 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7241 "FROM pg_catalog.pg_description "
7242 "ORDER BY classoid, objoid, objsubid");
7244 else if (fout->remoteVersion >= 70200)
7246 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7247 "FROM pg_description "
7248 "ORDER BY classoid, objoid, objsubid");
7252 /* Note: this will fail to find attribute comments in pre-7.2... */
7253 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7254 "FROM pg_description "
7258 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7260 /* Construct lookup table containing OIDs in numeric form */
7262 i_description = PQfnumber(res, "description");
7263 i_classoid = PQfnumber(res, "classoid");
7264 i_objoid = PQfnumber(res, "objoid");
7265 i_objsubid = PQfnumber(res, "objsubid");
7267 ntups = PQntuples(res);
7269 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7271 for (i = 0; i < ntups; i++)
7273 comments[i].descr = PQgetvalue(res, i, i_description);
7274 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7275 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7276 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7279 /* Do NOT free the PGresult since we are keeping pointers into it */
7280 destroyPQExpBuffer(query);
7287 * dumpDumpableObject
7289 * This routine and its subsidiaries are responsible for creating
7290 * ArchiveEntries (TOC objects) for each object to be dumped.
7293 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7295 switch (dobj->objType)
7298 dumpNamespace(fout, (NamespaceInfo *) dobj);
7301 dumpExtension(fout, (ExtensionInfo *) dobj);
7304 dumpType(fout, (TypeInfo *) dobj);
7307 dumpShellType(fout, (ShellTypeInfo *) dobj);
7310 dumpFunc(fout, (FuncInfo *) dobj);
7313 dumpAgg(fout, (AggInfo *) dobj);
7316 dumpOpr(fout, (OprInfo *) dobj);
7319 dumpOpclass(fout, (OpclassInfo *) dobj);
7322 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7325 dumpCollation(fout, (CollInfo *) dobj);
7328 dumpConversion(fout, (ConvInfo *) dobj);
7331 dumpTable(fout, (TableInfo *) dobj);
7334 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7337 dumpIndex(fout, (IndxInfo *) dobj);
7340 dumpRule(fout, (RuleInfo *) dobj);
7343 dumpTrigger(fout, (TriggerInfo *) dobj);
7345 case DO_EVENT_TRIGGER:
7346 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7349 dumpConstraint(fout, (ConstraintInfo *) dobj);
7351 case DO_FK_CONSTRAINT:
7352 dumpConstraint(fout, (ConstraintInfo *) dobj);
7355 dumpProcLang(fout, (ProcLangInfo *) dobj);
7358 dumpCast(fout, (CastInfo *) dobj);
7361 if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7362 dumpSequenceData(fout, (TableDataInfo *) dobj);
7364 dumpTableData(fout, (TableDataInfo *) dobj);
7367 /* table rowtypes and array types are never dumped separately */
7370 dumpTSParser(fout, (TSParserInfo *) dobj);
7373 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7376 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7379 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7382 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7384 case DO_FOREIGN_SERVER:
7385 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7387 case DO_DEFAULT_ACL:
7388 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7391 dumpBlob(fout, (BlobInfo *) dobj);
7394 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7395 dobj->name, NULL, NULL, "",
7396 false, "BLOBS", SECTION_DATA,
7401 case DO_PRE_DATA_BOUNDARY:
7402 case DO_POST_DATA_BOUNDARY:
7403 /* never dumped, nothing to do */
7410 * writes out to fout the queries to recreate a user-defined namespace
7413 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7420 /* Skip if not to be dumped */
7421 if (!nspinfo->dobj.dump || dataOnly)
7424 /* don't dump dummy namespace from pre-7.3 source */
7425 if (strlen(nspinfo->dobj.name) == 0)
7428 q = createPQExpBuffer();
7429 delq = createPQExpBuffer();
7430 labelq = createPQExpBuffer();
7432 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7434 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7436 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7438 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7441 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7443 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7447 false, "SCHEMA", SECTION_PRE_DATA,
7448 q->data, delq->data, NULL,
7452 /* Dump Schema Comments and Security Labels */
7453 dumpComment(fout, labelq->data,
7454 NULL, nspinfo->rolname,
7455 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7456 dumpSecLabel(fout, labelq->data,
7457 NULL, nspinfo->rolname,
7458 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7460 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7461 qnspname, NULL, nspinfo->dobj.name, NULL,
7462 nspinfo->rolname, nspinfo->nspacl);
7466 destroyPQExpBuffer(q);
7467 destroyPQExpBuffer(delq);
7468 destroyPQExpBuffer(labelq);
7473 * writes out to fout the queries to recreate an extension
7476 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7483 /* Skip if not to be dumped */
7484 if (!extinfo->dobj.dump || dataOnly)
7487 q = createPQExpBuffer();
7488 delq = createPQExpBuffer();
7489 labelq = createPQExpBuffer();
7491 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7493 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7495 if (!binary_upgrade)
7498 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7499 * problem if the extension already exists in the target database;
7500 * this is essential for installed-by-default extensions such as
7503 * In binary-upgrade mode, that doesn't work well, so instead we skip
7504 * built-in extensions based on their OIDs; see
7505 * selectDumpableExtension.
7507 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7508 qextname, fmtId(extinfo->namespace));
7515 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7518 * We unconditionally create the extension, so we must drop it if it
7519 * exists. This could happen if the user deleted 'plpgsql' and then
7520 * readded it, causing its oid to be greater than FirstNormalObjectId.
7521 * The FirstNormalObjectId test was kept to avoid repeatedly dropping
7522 * and recreating extensions like 'plpgsql'.
7524 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7526 appendPQExpBuffer(q,
7527 "SELECT binary_upgrade.create_empty_extension(");
7528 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7529 appendPQExpBuffer(q, ", ");
7530 appendStringLiteralAH(q, extinfo->namespace, fout);
7531 appendPQExpBuffer(q, ", ");
7532 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7533 appendStringLiteralAH(q, extinfo->extversion, fout);
7534 appendPQExpBuffer(q, ", ");
7537 * Note that we're pushing extconfig (an OID array) back into
7538 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7539 * preserved in binary upgrade.
7541 if (strlen(extinfo->extconfig) > 2)
7542 appendStringLiteralAH(q, extinfo->extconfig, fout);
7544 appendPQExpBuffer(q, "NULL");
7545 appendPQExpBuffer(q, ", ");
7546 if (strlen(extinfo->extcondition) > 2)
7547 appendStringLiteralAH(q, extinfo->extcondition, fout);
7549 appendPQExpBuffer(q, "NULL");
7550 appendPQExpBuffer(q, ", ");
7551 appendPQExpBuffer(q, "ARRAY[");
7553 for (i = 0; i < extinfo->dobj.nDeps; i++)
7555 DumpableObject *extobj;
7557 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7558 if (extobj && extobj->objType == DO_EXTENSION)
7561 appendPQExpBuffer(q, ",");
7562 appendStringLiteralAH(q, extobj->name, fout);
7565 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7566 appendPQExpBuffer(q, ");\n");
7569 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7571 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7575 false, "EXTENSION", SECTION_PRE_DATA,
7576 q->data, delq->data, NULL,
7580 /* Dump Extension Comments and Security Labels */
7581 dumpComment(fout, labelq->data,
7583 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7584 dumpSecLabel(fout, labelq->data,
7586 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7590 destroyPQExpBuffer(q);
7591 destroyPQExpBuffer(delq);
7592 destroyPQExpBuffer(labelq);
7597 * writes out to fout the queries to recreate a user-defined type
7600 dumpType(Archive *fout, TypeInfo *tyinfo)
7602 /* Skip if not to be dumped */
7603 if (!tyinfo->dobj.dump || dataOnly)
7606 /* Dump out in proper style */
7607 if (tyinfo->typtype == TYPTYPE_BASE)
7608 dumpBaseType(fout, tyinfo);
7609 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7610 dumpDomain(fout, tyinfo);
7611 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7612 dumpCompositeType(fout, tyinfo);
7613 else if (tyinfo->typtype == TYPTYPE_ENUM)
7614 dumpEnumType(fout, tyinfo);
7615 else if (tyinfo->typtype == TYPTYPE_RANGE)
7616 dumpRangeType(fout, tyinfo);
7618 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7624 * writes out to fout the queries to recreate a user-defined enum type
7627 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7629 PQExpBuffer q = createPQExpBuffer();
7630 PQExpBuffer delq = createPQExpBuffer();
7631 PQExpBuffer labelq = createPQExpBuffer();
7632 PQExpBuffer query = createPQExpBuffer();
7640 /* Set proper schema search path */
7641 selectSourceSchema(fout, "pg_catalog");
7643 if (fout->remoteVersion >= 90100)
7644 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7645 "FROM pg_catalog.pg_enum "
7646 "WHERE enumtypid = '%u'"
7647 "ORDER BY enumsortorder",
7648 tyinfo->dobj.catId.oid);
7650 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7651 "FROM pg_catalog.pg_enum "
7652 "WHERE enumtypid = '%u'"
7654 tyinfo->dobj.catId.oid);
7656 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7658 num = PQntuples(res);
7660 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7663 * DROP must be fully qualified in case same name appears in pg_catalog.
7664 * CASCADE shouldn't be required here as for normal types since the I/O
7665 * functions are generic and do not get dropped.
7667 appendPQExpBuffer(delq, "DROP TYPE %s.",
7668 fmtId(tyinfo->dobj.namespace->dobj.name));
7669 appendPQExpBuffer(delq, "%s;\n",
7673 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7674 tyinfo->dobj.catId.oid);
7676 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7679 if (!binary_upgrade)
7681 /* Labels with server-assigned oids */
7682 for (i = 0; i < num; i++)
7684 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7686 appendPQExpBuffer(q, ",");
7687 appendPQExpBuffer(q, "\n ");
7688 appendStringLiteralAH(q, label, fout);
7692 appendPQExpBuffer(q, "\n);\n");
7696 /* Labels with dump-assigned (preserved) oids */
7697 for (i = 0; i < num; i++)
7699 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7700 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7703 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7704 appendPQExpBuffer(q,
7705 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7707 appendPQExpBuffer(q, "ALTER TYPE %s.",
7708 fmtId(tyinfo->dobj.namespace->dobj.name));
7709 appendPQExpBuffer(q, "%s ADD VALUE ",
7711 appendStringLiteralAH(q, label, fout);
7712 appendPQExpBuffer(q, ";\n\n");
7716 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7719 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7721 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7723 tyinfo->dobj.namespace->dobj.name,
7725 tyinfo->rolname, false,
7726 "TYPE", SECTION_PRE_DATA,
7727 q->data, delq->data, NULL,
7731 /* Dump Type Comments and Security Labels */
7732 dumpComment(fout, labelq->data,
7733 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7734 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7735 dumpSecLabel(fout, labelq->data,
7736 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7737 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7739 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7740 qtypname, NULL, tyinfo->dobj.name,
7741 tyinfo->dobj.namespace->dobj.name,
7742 tyinfo->rolname, tyinfo->typacl);
7745 destroyPQExpBuffer(q);
7746 destroyPQExpBuffer(delq);
7747 destroyPQExpBuffer(labelq);
7748 destroyPQExpBuffer(query);
7753 * writes out to fout the queries to recreate a user-defined range type
7756 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7758 PQExpBuffer q = createPQExpBuffer();
7759 PQExpBuffer delq = createPQExpBuffer();
7760 PQExpBuffer labelq = createPQExpBuffer();
7761 PQExpBuffer query = createPQExpBuffer();
7768 * select appropriate schema to ensure names in CREATE are properly
7771 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7773 appendPQExpBuffer(query,
7774 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7775 "opc.opcname AS opcname, "
7776 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7777 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7779 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7780 " ELSE rngcollation END AS collation, "
7781 "rngcanonical, rngsubdiff "
7782 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7783 " pg_catalog.pg_opclass opc "
7784 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7786 tyinfo->dobj.catId.oid);
7788 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7790 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7793 * DROP must be fully qualified in case same name appears in pg_catalog.
7794 * CASCADE shouldn't be required here as for normal types since the I/O
7795 * functions are generic and do not get dropped.
7797 appendPQExpBuffer(delq, "DROP TYPE %s.",
7798 fmtId(tyinfo->dobj.namespace->dobj.name));
7799 appendPQExpBuffer(delq, "%s;\n",
7803 binary_upgrade_set_type_oids_by_type_oid(fout,
7804 q, tyinfo->dobj.catId.oid);
7806 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7809 appendPQExpBuffer(q, "\n subtype = %s",
7810 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7812 /* print subtype_opclass only if not default for subtype */
7813 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7815 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7816 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7818 /* always schema-qualify, don't try to be smart */
7819 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7821 appendPQExpBuffer(q, "%s", fmtId(opcname));
7824 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7825 if (OidIsValid(collationOid))
7827 CollInfo *coll = findCollationByOid(collationOid);
7831 /* always schema-qualify, don't try to be smart */
7832 appendPQExpBuffer(q, ",\n collation = %s.",
7833 fmtId(coll->dobj.namespace->dobj.name));
7834 appendPQExpBuffer(q, "%s",
7835 fmtId(coll->dobj.name));
7839 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7840 if (strcmp(procname, "-") != 0)
7841 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7843 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7844 if (strcmp(procname, "-") != 0)
7845 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7847 appendPQExpBuffer(q, "\n);\n");
7849 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7852 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7854 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7856 tyinfo->dobj.namespace->dobj.name,
7858 tyinfo->rolname, false,
7859 "TYPE", SECTION_PRE_DATA,
7860 q->data, delq->data, NULL,
7864 /* Dump Type Comments and Security Labels */
7865 dumpComment(fout, labelq->data,
7866 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7867 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7868 dumpSecLabel(fout, labelq->data,
7869 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7870 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7872 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7873 qtypname, NULL, tyinfo->dobj.name,
7874 tyinfo->dobj.namespace->dobj.name,
7875 tyinfo->rolname, tyinfo->typacl);
7878 destroyPQExpBuffer(q);
7879 destroyPQExpBuffer(delq);
7880 destroyPQExpBuffer(labelq);
7881 destroyPQExpBuffer(query);
7886 * writes out to fout the queries to recreate a user-defined base type
7889 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7891 PQExpBuffer q = createPQExpBuffer();
7892 PQExpBuffer delq = createPQExpBuffer();
7893 PQExpBuffer labelq = createPQExpBuffer();
7894 PQExpBuffer query = createPQExpBuffer();
7911 char *typispreferred;
7916 char *typcollatable;
7918 bool typdefault_is_literal = false;
7920 /* Set proper schema search path so regproc references list correctly */
7921 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7923 /* Fetch type-specific details */
7924 if (fout->remoteVersion >= 90100)
7926 appendPQExpBuffer(query, "SELECT typlen, "
7927 "typinput, typoutput, typreceive, typsend, "
7928 "typmodin, typmodout, typanalyze, "
7929 "typreceive::pg_catalog.oid AS typreceiveoid, "
7930 "typsend::pg_catalog.oid AS typsendoid, "
7931 "typmodin::pg_catalog.oid AS typmodinoid, "
7932 "typmodout::pg_catalog.oid AS typmodoutoid, "
7933 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7934 "typcategory, typispreferred, "
7935 "typdelim, typbyval, typalign, typstorage, "
7936 "(typcollation <> 0) AS typcollatable, "
7937 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7938 "FROM pg_catalog.pg_type "
7939 "WHERE oid = '%u'::pg_catalog.oid",
7940 tyinfo->dobj.catId.oid);
7942 else if (fout->remoteVersion >= 80400)
7944 appendPQExpBuffer(query, "SELECT typlen, "
7945 "typinput, typoutput, typreceive, typsend, "
7946 "typmodin, typmodout, typanalyze, "
7947 "typreceive::pg_catalog.oid AS typreceiveoid, "
7948 "typsend::pg_catalog.oid AS typsendoid, "
7949 "typmodin::pg_catalog.oid AS typmodinoid, "
7950 "typmodout::pg_catalog.oid AS typmodoutoid, "
7951 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7952 "typcategory, typispreferred, "
7953 "typdelim, typbyval, typalign, typstorage, "
7954 "false AS typcollatable, "
7955 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7956 "FROM pg_catalog.pg_type "
7957 "WHERE oid = '%u'::pg_catalog.oid",
7958 tyinfo->dobj.catId.oid);
7960 else if (fout->remoteVersion >= 80300)
7962 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7963 appendPQExpBuffer(query, "SELECT typlen, "
7964 "typinput, typoutput, typreceive, typsend, "
7965 "typmodin, typmodout, typanalyze, "
7966 "typreceive::pg_catalog.oid AS typreceiveoid, "
7967 "typsend::pg_catalog.oid AS typsendoid, "
7968 "typmodin::pg_catalog.oid AS typmodinoid, "
7969 "typmodout::pg_catalog.oid AS typmodoutoid, "
7970 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7971 "'U' AS typcategory, false AS typispreferred, "
7972 "typdelim, typbyval, typalign, typstorage, "
7973 "false AS typcollatable, "
7974 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7975 "FROM pg_catalog.pg_type "
7976 "WHERE oid = '%u'::pg_catalog.oid",
7977 tyinfo->dobj.catId.oid);
7979 else if (fout->remoteVersion >= 80000)
7981 appendPQExpBuffer(query, "SELECT typlen, "
7982 "typinput, typoutput, typreceive, typsend, "
7983 "'-' AS typmodin, '-' AS typmodout, "
7985 "typreceive::pg_catalog.oid AS typreceiveoid, "
7986 "typsend::pg_catalog.oid AS typsendoid, "
7987 "0 AS typmodinoid, 0 AS typmodoutoid, "
7988 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7989 "'U' AS typcategory, false AS typispreferred, "
7990 "typdelim, typbyval, typalign, typstorage, "
7991 "false AS typcollatable, "
7992 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7993 "FROM pg_catalog.pg_type "
7994 "WHERE oid = '%u'::pg_catalog.oid",
7995 tyinfo->dobj.catId.oid);
7997 else if (fout->remoteVersion >= 70400)
7999 appendPQExpBuffer(query, "SELECT typlen, "
8000 "typinput, typoutput, typreceive, typsend, "
8001 "'-' AS typmodin, '-' AS typmodout, "
8002 "'-' AS typanalyze, "
8003 "typreceive::pg_catalog.oid AS typreceiveoid, "
8004 "typsend::pg_catalog.oid AS typsendoid, "
8005 "0 AS typmodinoid, 0 AS typmodoutoid, "
8006 "0 AS typanalyzeoid, "
8007 "'U' AS typcategory, false AS typispreferred, "
8008 "typdelim, typbyval, typalign, typstorage, "
8009 "false AS typcollatable, "
8010 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8011 "FROM pg_catalog.pg_type "
8012 "WHERE oid = '%u'::pg_catalog.oid",
8013 tyinfo->dobj.catId.oid);
8015 else if (fout->remoteVersion >= 70300)
8017 appendPQExpBuffer(query, "SELECT typlen, "
8018 "typinput, typoutput, "
8019 "'-' AS typreceive, '-' AS typsend, "
8020 "'-' AS typmodin, '-' AS typmodout, "
8021 "'-' AS typanalyze, "
8022 "0 AS typreceiveoid, 0 AS typsendoid, "
8023 "0 AS typmodinoid, 0 AS typmodoutoid, "
8024 "0 AS typanalyzeoid, "
8025 "'U' AS typcategory, false AS typispreferred, "
8026 "typdelim, typbyval, typalign, typstorage, "
8027 "false AS typcollatable, "
8028 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8029 "FROM pg_catalog.pg_type "
8030 "WHERE oid = '%u'::pg_catalog.oid",
8031 tyinfo->dobj.catId.oid);
8033 else if (fout->remoteVersion >= 70200)
8036 * Note: although pre-7.3 catalogs contain typreceive and typsend,
8037 * ignore them because they are not right.
8039 appendPQExpBuffer(query, "SELECT typlen, "
8040 "typinput, typoutput, "
8041 "'-' AS typreceive, '-' AS typsend, "
8042 "'-' AS typmodin, '-' AS typmodout, "
8043 "'-' AS typanalyze, "
8044 "0 AS typreceiveoid, 0 AS typsendoid, "
8045 "0 AS typmodinoid, 0 AS typmodoutoid, "
8046 "0 AS typanalyzeoid, "
8047 "'U' AS typcategory, false AS typispreferred, "
8048 "typdelim, typbyval, typalign, typstorage, "
8049 "false AS typcollatable, "
8050 "NULL AS typdefaultbin, typdefault "
8052 "WHERE oid = '%u'::oid",
8053 tyinfo->dobj.catId.oid);
8055 else if (fout->remoteVersion >= 70100)
8058 * Ignore pre-7.2 typdefault; the field exists but has an unusable
8061 appendPQExpBuffer(query, "SELECT typlen, "
8062 "typinput, typoutput, "
8063 "'-' AS typreceive, '-' AS typsend, "
8064 "'-' AS typmodin, '-' AS typmodout, "
8065 "'-' AS typanalyze, "
8066 "0 AS typreceiveoid, 0 AS typsendoid, "
8067 "0 AS typmodinoid, 0 AS typmodoutoid, "
8068 "0 AS typanalyzeoid, "
8069 "'U' AS typcategory, false AS typispreferred, "
8070 "typdelim, typbyval, typalign, typstorage, "
8071 "false AS typcollatable, "
8072 "NULL AS typdefaultbin, NULL AS typdefault "
8074 "WHERE oid = '%u'::oid",
8075 tyinfo->dobj.catId.oid);
8079 appendPQExpBuffer(query, "SELECT typlen, "
8080 "typinput, typoutput, "
8081 "'-' AS typreceive, '-' AS typsend, "
8082 "'-' AS typmodin, '-' AS typmodout, "
8083 "'-' AS typanalyze, "
8084 "0 AS typreceiveoid, 0 AS typsendoid, "
8085 "0 AS typmodinoid, 0 AS typmodoutoid, "
8086 "0 AS typanalyzeoid, "
8087 "'U' AS typcategory, false AS typispreferred, "
8088 "typdelim, typbyval, typalign, "
8089 "'p'::char AS typstorage, "
8090 "false AS typcollatable, "
8091 "NULL AS typdefaultbin, NULL AS typdefault "
8093 "WHERE oid = '%u'::oid",
8094 tyinfo->dobj.catId.oid);
8097 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8099 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8100 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8101 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8102 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8103 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8104 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8105 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8106 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8107 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8108 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8109 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8110 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8111 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8112 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8113 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8114 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8115 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8116 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8117 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8118 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8119 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8120 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8121 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8123 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8124 typdefault_is_literal = true; /* it needs quotes */
8129 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8132 * DROP must be fully qualified in case same name appears in pg_catalog.
8133 * The reason we include CASCADE is that the circular dependency between
8134 * the type and its I/O functions makes it impossible to drop the type any
8137 appendPQExpBuffer(delq, "DROP TYPE %s.",
8138 fmtId(tyinfo->dobj.namespace->dobj.name));
8139 appendPQExpBuffer(delq, "%s CASCADE;\n",
8142 /* We might already have a shell type, but setting pg_type_oid is harmless */
8144 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8145 tyinfo->dobj.catId.oid);
8147 appendPQExpBuffer(q,
8148 "CREATE TYPE %s (\n"
8149 " INTERNALLENGTH = %s",
8151 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8153 if (fout->remoteVersion >= 70300)
8155 /* regproc result is correctly quoted as of 7.3 */
8156 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8157 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8158 if (OidIsValid(typreceiveoid))
8159 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8160 if (OidIsValid(typsendoid))
8161 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8162 if (OidIsValid(typmodinoid))
8163 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8164 if (OidIsValid(typmodoutoid))
8165 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8166 if (OidIsValid(typanalyzeoid))
8167 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8171 /* regproc delivers an unquoted name before 7.3 */
8172 /* cannot combine these because fmtId uses static result area */
8173 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8174 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8175 /* receive/send/typmodin/typmodout/analyze need not be printed */
8178 if (strcmp(typcollatable, "t") == 0)
8179 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8181 if (typdefault != NULL)
8183 appendPQExpBuffer(q, ",\n DEFAULT = ");
8184 if (typdefault_is_literal)
8185 appendStringLiteralAH(q, typdefault, fout);
8187 appendPQExpBufferStr(q, typdefault);
8190 if (OidIsValid(tyinfo->typelem))
8194 /* reselect schema in case changed by function dump */
8195 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8196 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8197 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8201 if (strcmp(typcategory, "U") != 0)
8203 appendPQExpBuffer(q, ",\n CATEGORY = ");
8204 appendStringLiteralAH(q, typcategory, fout);
8207 if (strcmp(typispreferred, "t") == 0)
8208 appendPQExpBuffer(q, ",\n PREFERRED = true");
8210 if (typdelim && strcmp(typdelim, ",") != 0)
8212 appendPQExpBuffer(q, ",\n DELIMITER = ");
8213 appendStringLiteralAH(q, typdelim, fout);
8216 if (strcmp(typalign, "c") == 0)
8217 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8218 else if (strcmp(typalign, "s") == 0)
8219 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8220 else if (strcmp(typalign, "i") == 0)
8221 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8222 else if (strcmp(typalign, "d") == 0)
8223 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8225 if (strcmp(typstorage, "p") == 0)
8226 appendPQExpBuffer(q, ",\n STORAGE = plain");
8227 else if (strcmp(typstorage, "e") == 0)
8228 appendPQExpBuffer(q, ",\n STORAGE = external");
8229 else if (strcmp(typstorage, "x") == 0)
8230 appendPQExpBuffer(q, ",\n STORAGE = extended");
8231 else if (strcmp(typstorage, "m") == 0)
8232 appendPQExpBuffer(q, ",\n STORAGE = main");
8234 if (strcmp(typbyval, "t") == 0)
8235 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8237 appendPQExpBuffer(q, "\n);\n");
8239 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8242 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8244 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8246 tyinfo->dobj.namespace->dobj.name,
8248 tyinfo->rolname, false,
8249 "TYPE", SECTION_PRE_DATA,
8250 q->data, delq->data, NULL,
8254 /* Dump Type Comments and Security Labels */
8255 dumpComment(fout, labelq->data,
8256 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8257 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8258 dumpSecLabel(fout, labelq->data,
8259 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8260 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8262 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8263 qtypname, NULL, tyinfo->dobj.name,
8264 tyinfo->dobj.namespace->dobj.name,
8265 tyinfo->rolname, tyinfo->typacl);
8268 destroyPQExpBuffer(q);
8269 destroyPQExpBuffer(delq);
8270 destroyPQExpBuffer(labelq);
8271 destroyPQExpBuffer(query);
8276 * writes out to fout the queries to recreate a user-defined domain
8279 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8281 PQExpBuffer q = createPQExpBuffer();
8282 PQExpBuffer delq = createPQExpBuffer();
8283 PQExpBuffer labelq = createPQExpBuffer();
8284 PQExpBuffer query = createPQExpBuffer();
8292 bool typdefault_is_literal = false;
8294 /* Set proper schema search path so type references list correctly */
8295 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8297 /* Fetch domain specific details */
8298 if (fout->remoteVersion >= 90100)
8300 /* typcollation is new in 9.1 */
8301 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8302 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8303 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8305 "CASE WHEN t.typcollation <> u.typcollation "
8306 "THEN t.typcollation ELSE 0 END AS typcollation "
8307 "FROM pg_catalog.pg_type t "
8308 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8309 "WHERE t.oid = '%u'::pg_catalog.oid",
8310 tyinfo->dobj.catId.oid);
8314 /* We assume here that remoteVersion must be at least 70300 */
8315 appendPQExpBuffer(query, "SELECT typnotnull, "
8316 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8317 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8318 "typdefault, 0 AS typcollation "
8319 "FROM pg_catalog.pg_type "
8320 "WHERE oid = '%u'::pg_catalog.oid",
8321 tyinfo->dobj.catId.oid);
8324 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8326 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8327 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8328 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8329 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8330 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8332 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8333 typdefault_is_literal = true; /* it needs quotes */
8337 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8340 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8341 tyinfo->dobj.catId.oid);
8343 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8345 appendPQExpBuffer(q,
8346 "CREATE DOMAIN %s AS %s",
8350 /* Print collation only if different from base type's collation */
8351 if (OidIsValid(typcollation))
8355 coll = findCollationByOid(typcollation);
8358 /* always schema-qualify, don't try to be smart */
8359 appendPQExpBuffer(q, " COLLATE %s.",
8360 fmtId(coll->dobj.namespace->dobj.name));
8361 appendPQExpBuffer(q, "%s",
8362 fmtId(coll->dobj.name));
8366 if (typnotnull[0] == 't')
8367 appendPQExpBuffer(q, " NOT NULL");
8369 if (typdefault != NULL)
8371 appendPQExpBuffer(q, " DEFAULT ");
8372 if (typdefault_is_literal)
8373 appendStringLiteralAH(q, typdefault, fout);
8375 appendPQExpBufferStr(q, typdefault);
8381 * Add any CHECK constraints for the domain
8383 for (i = 0; i < tyinfo->nDomChecks; i++)
8385 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8387 if (!domcheck->separate)
8388 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8389 fmtId(domcheck->dobj.name), domcheck->condef);
8392 appendPQExpBuffer(q, ";\n");
8395 * DROP must be fully qualified in case same name appears in pg_catalog
8397 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8398 fmtId(tyinfo->dobj.namespace->dobj.name));
8399 appendPQExpBuffer(delq, "%s;\n",
8402 appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8405 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8407 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8409 tyinfo->dobj.namespace->dobj.name,
8411 tyinfo->rolname, false,
8412 "DOMAIN", SECTION_PRE_DATA,
8413 q->data, delq->data, NULL,
8417 /* Dump Domain Comments and Security Labels */
8418 dumpComment(fout, labelq->data,
8419 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8420 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8421 dumpSecLabel(fout, labelq->data,
8422 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8423 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8425 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8426 qtypname, NULL, tyinfo->dobj.name,
8427 tyinfo->dobj.namespace->dobj.name,
8428 tyinfo->rolname, tyinfo->typacl);
8430 destroyPQExpBuffer(q);
8431 destroyPQExpBuffer(delq);
8432 destroyPQExpBuffer(labelq);
8433 destroyPQExpBuffer(query);
8438 * writes out to fout the queries to recreate a user-defined stand-alone
8442 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8444 PQExpBuffer q = createPQExpBuffer();
8445 PQExpBuffer dropped = createPQExpBuffer();
8446 PQExpBuffer delq = createPQExpBuffer();
8447 PQExpBuffer labelq = createPQExpBuffer();
8448 PQExpBuffer query = createPQExpBuffer();
8462 /* Set proper schema search path so type references list correctly */
8463 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8465 /* Fetch type specific details */
8466 if (fout->remoteVersion >= 90100)
8469 * attcollation is new in 9.1. Since we only want to dump COLLATE
8470 * clauses for attributes whose collation is different from their
8471 * type's default, we use a CASE here to suppress uninteresting
8472 * attcollations cheaply. atttypid will be 0 for dropped columns;
8473 * collation does not matter for those.
8475 appendPQExpBuffer(query, "SELECT a.attname, "
8476 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8477 "a.attlen, a.attalign, a.attisdropped, "
8478 "CASE WHEN a.attcollation <> at.typcollation "
8479 "THEN a.attcollation ELSE 0 END AS attcollation, "
8481 "FROM pg_catalog.pg_type ct "
8482 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8483 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8484 "WHERE ct.oid = '%u'::pg_catalog.oid "
8485 "ORDER BY a.attnum ",
8486 tyinfo->dobj.catId.oid);
8491 * We assume here that remoteVersion must be at least 70300. Since
8492 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8495 appendPQExpBuffer(query, "SELECT a.attname, "
8496 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8497 "a.attlen, a.attalign, a.attisdropped, "
8498 "0 AS attcollation, "
8500 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8501 "WHERE ct.oid = '%u'::pg_catalog.oid "
8502 "AND a.attrelid = ct.typrelid "
8503 "ORDER BY a.attnum ",
8504 tyinfo->dobj.catId.oid);
8507 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8509 ntups = PQntuples(res);
8511 i_attname = PQfnumber(res, "attname");
8512 i_atttypdefn = PQfnumber(res, "atttypdefn");
8513 i_attlen = PQfnumber(res, "attlen");
8514 i_attalign = PQfnumber(res, "attalign");
8515 i_attisdropped = PQfnumber(res, "attisdropped");
8516 i_attcollation = PQfnumber(res, "attcollation");
8517 i_typrelid = PQfnumber(res, "typrelid");
8521 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8523 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8524 tyinfo->dobj.catId.oid);
8525 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8528 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8530 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8534 for (i = 0; i < ntups; i++)
8543 attname = PQgetvalue(res, i, i_attname);
8544 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8545 attlen = PQgetvalue(res, i, i_attlen);
8546 attalign = PQgetvalue(res, i, i_attalign);
8547 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8548 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8550 if (attisdropped && !binary_upgrade)
8553 /* Format properly if not first attr */
8554 if (actual_atts++ > 0)
8555 appendPQExpBuffer(q, ",");
8556 appendPQExpBuffer(q, "\n\t");
8560 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8562 /* Add collation if not default for the column type */
8563 if (OidIsValid(attcollation))
8567 coll = findCollationByOid(attcollation);
8570 /* always schema-qualify, don't try to be smart */
8571 appendPQExpBuffer(q, " COLLATE %s.",
8572 fmtId(coll->dobj.namespace->dobj.name));
8573 appendPQExpBuffer(q, "%s",
8574 fmtId(coll->dobj.name));
8581 * This is a dropped attribute and we're in binary_upgrade mode.
8582 * Insert a placeholder for it in the CREATE TYPE command, and set
8583 * length and alignment with direct UPDATE to the catalogs
8584 * afterwards. See similar code in dumpTableSchema().
8586 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8588 /* stash separately for insertion after the CREATE TYPE */
8589 appendPQExpBuffer(dropped,
8590 "\n-- For binary upgrade, recreate dropped column.\n");
8591 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8593 "attalign = '%s', attbyval = false\n"
8594 "WHERE attname = ", attlen, attalign);
8595 appendStringLiteralAH(dropped, attname, fout);
8596 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8597 appendStringLiteralAH(dropped, qtypname, fout);
8598 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8600 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8602 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8606 appendPQExpBuffer(q, "\n);\n");
8607 appendPQExpBufferStr(q, dropped->data);
8610 * DROP must be fully qualified in case same name appears in pg_catalog
8612 appendPQExpBuffer(delq, "DROP TYPE %s.",
8613 fmtId(tyinfo->dobj.namespace->dobj.name));
8614 appendPQExpBuffer(delq, "%s;\n",
8617 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8620 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8622 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8624 tyinfo->dobj.namespace->dobj.name,
8626 tyinfo->rolname, false,
8627 "TYPE", SECTION_PRE_DATA,
8628 q->data, delq->data, NULL,
8633 /* Dump Type Comments and Security Labels */
8634 dumpComment(fout, labelq->data,
8635 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8636 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8637 dumpSecLabel(fout, labelq->data,
8638 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8639 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8641 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8642 qtypname, NULL, tyinfo->dobj.name,
8643 tyinfo->dobj.namespace->dobj.name,
8644 tyinfo->rolname, tyinfo->typacl);
8647 destroyPQExpBuffer(q);
8648 destroyPQExpBuffer(dropped);
8649 destroyPQExpBuffer(delq);
8650 destroyPQExpBuffer(labelq);
8651 destroyPQExpBuffer(query);
8653 /* Dump any per-column comments */
8654 dumpCompositeTypeColComments(fout, tyinfo);
8658 * dumpCompositeTypeColComments
8659 * writes out to fout the queries to recreate comments on the columns of
8660 * a user-defined stand-alone composite type
8663 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8665 CommentItem *comments;
8676 query = createPQExpBuffer();
8678 /* We assume here that remoteVersion must be at least 70300 */
8679 appendPQExpBuffer(query,
8680 "SELECT c.tableoid, a.attname, a.attnum "
8681 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8682 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8683 " AND NOT a.attisdropped "
8684 "ORDER BY a.attnum ",
8687 /* Fetch column attnames */
8688 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8690 ntups = PQntuples(res);
8694 destroyPQExpBuffer(query);
8698 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8700 /* Search for comments associated with type's pg_class OID */
8701 ncomments = findComments(fout,
8706 /* If no comments exist, we're done */
8710 destroyPQExpBuffer(query);
8714 /* Build COMMENT ON statements */
8715 target = createPQExpBuffer();
8717 i_attnum = PQfnumber(res, "attnum");
8718 i_attname = PQfnumber(res, "attname");
8719 while (ncomments > 0)
8721 const char *attname;
8724 for (i = 0; i < ntups; i++)
8726 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8728 attname = PQgetvalue(res, i, i_attname);
8732 if (attname) /* just in case we don't find it */
8734 const char *descr = comments->descr;
8736 resetPQExpBuffer(target);
8737 appendPQExpBuffer(target, "COLUMN %s.",
8738 fmtId(tyinfo->dobj.name));
8739 appendPQExpBuffer(target, "%s",
8742 resetPQExpBuffer(query);
8743 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8744 appendStringLiteralAH(query, descr, fout);
8745 appendPQExpBuffer(query, ";\n");
8747 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8749 tyinfo->dobj.namespace->dobj.name,
8750 NULL, tyinfo->rolname,
8751 false, "COMMENT", SECTION_NONE,
8752 query->data, "", NULL,
8753 &(tyinfo->dobj.dumpId), 1,
8762 destroyPQExpBuffer(query);
8763 destroyPQExpBuffer(target);
8768 * writes out to fout the queries to create a shell type
8770 * We dump a shell definition in advance of the I/O functions for the type.
8773 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8777 /* Skip if not to be dumped */
8778 if (!stinfo->dobj.dump || dataOnly)
8781 q = createPQExpBuffer();
8784 * Note the lack of a DROP command for the shell type; any required DROP
8785 * is driven off the base type entry, instead. This interacts with
8786 * _printTocEntry()'s use of the presence of a DROP command to decide
8787 * whether an entry needs an ALTER OWNER command. We don't want to alter
8788 * the shell type's owner immediately on creation; that should happen only
8789 * after it's filled in, otherwise the backend complains.
8793 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8794 stinfo->baseType->dobj.catId.oid);
8796 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8797 fmtId(stinfo->dobj.name));
8799 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8801 stinfo->dobj.namespace->dobj.name,
8803 stinfo->baseType->rolname, false,
8804 "SHELL TYPE", SECTION_PRE_DATA,
8809 destroyPQExpBuffer(q);
8813 * Determine whether we want to dump definitions for procedural languages.
8814 * Since the languages themselves don't have schemas, we can't rely on
8815 * the normal schema-based selection mechanism. We choose to dump them
8816 * whenever neither --schema nor --table was given. (Before 8.1, we used
8817 * the dump flag of the PL's call handler function, but in 8.1 this will
8818 * probably always be false since call handlers are created in pg_catalog.)
8820 * For some backwards compatibility with the older behavior, we forcibly
8821 * dump a PL if its handler function (and validator if any) are in a
8822 * dumpable namespace. That case is not checked here.
8824 * Also, if the PL belongs to an extension, we do not use this heuristic.
8825 * That case isn't checked here either.
8828 shouldDumpProcLangs(void)
8830 if (!include_everything)
8832 /* And they're schema not data */
8840 * writes out to fout the queries to recreate a user-defined
8841 * procedural language
8844 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8853 FuncInfo *inlineInfo = NULL;
8854 FuncInfo *validatorInfo = NULL;
8856 /* Skip if not to be dumped */
8857 if (!plang->dobj.dump || dataOnly)
8861 * Try to find the support function(s). It is not an error if we don't
8862 * find them --- if the functions are in the pg_catalog schema, as is
8863 * standard in 8.1 and up, then we won't have loaded them. (In this case
8864 * we will emit a parameterless CREATE LANGUAGE command, which will
8865 * require PL template knowledge in the backend to reload.)
8868 funcInfo = findFuncByOid(plang->lanplcallfoid);
8869 if (funcInfo != NULL && !funcInfo->dobj.dump)
8870 funcInfo = NULL; /* treat not-dumped same as not-found */
8872 if (OidIsValid(plang->laninline))
8874 inlineInfo = findFuncByOid(plang->laninline);
8875 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8879 if (OidIsValid(plang->lanvalidator))
8881 validatorInfo = findFuncByOid(plang->lanvalidator);
8882 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8883 validatorInfo = NULL;
8887 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8888 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8891 * However, for a language that belongs to an extension, we must not use
8892 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8893 * told to (via dobj.dump). Generally the support functions will belong
8894 * to the same extension and so have the same dump flags ... if they
8895 * don't, this might not work terribly nicely.
8897 useParams = (funcInfo != NULL &&
8898 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8899 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8901 if (!plang->dobj.ext_member)
8903 if (!useParams && !shouldDumpProcLangs())
8907 defqry = createPQExpBuffer();
8908 delqry = createPQExpBuffer();
8909 labelq = createPQExpBuffer();
8911 qlanname = pg_strdup(fmtId(plang->dobj.name));
8914 * If dumping a HANDLER clause, treat the language as being in the handler
8915 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8916 * it doesn't really have a schema.
8919 lanschema = funcInfo->dobj.namespace->dobj.name;
8923 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8928 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8929 plang->lanpltrusted ? "TRUSTED " : "",
8931 appendPQExpBuffer(defqry, " HANDLER %s",
8932 fmtId(funcInfo->dobj.name));
8933 if (OidIsValid(plang->laninline))
8935 appendPQExpBuffer(defqry, " INLINE ");
8936 /* Cope with possibility that inline is in different schema */
8937 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8938 appendPQExpBuffer(defqry, "%s.",
8939 fmtId(inlineInfo->dobj.namespace->dobj.name));
8940 appendPQExpBuffer(defqry, "%s",
8941 fmtId(inlineInfo->dobj.name));
8943 if (OidIsValid(plang->lanvalidator))
8945 appendPQExpBuffer(defqry, " VALIDATOR ");
8946 /* Cope with possibility that validator is in different schema */
8947 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8948 appendPQExpBuffer(defqry, "%s.",
8949 fmtId(validatorInfo->dobj.namespace->dobj.name));
8950 appendPQExpBuffer(defqry, "%s",
8951 fmtId(validatorInfo->dobj.name));
8957 * If not dumping parameters, then use CREATE OR REPLACE so that the
8958 * command will not fail if the language is preinstalled in the target
8959 * database. We restrict the use of REPLACE to this case so as to
8960 * eliminate the risk of replacing a language with incompatible
8961 * parameter settings: this command will only succeed at all if there
8962 * is a pg_pltemplate entry, and if there is one, the existing entry
8963 * must match it too.
8965 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8968 appendPQExpBuffer(defqry, ";\n");
8970 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8973 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8975 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8977 lanschema, NULL, plang->lanowner,
8978 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8979 defqry->data, delqry->data, NULL,
8983 /* Dump Proc Lang Comments and Security Labels */
8984 dumpComment(fout, labelq->data,
8986 plang->dobj.catId, 0, plang->dobj.dumpId);
8987 dumpSecLabel(fout, labelq->data,
8989 plang->dobj.catId, 0, plang->dobj.dumpId);
8991 if (plang->lanpltrusted)
8992 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8993 qlanname, NULL, plang->dobj.name,
8995 plang->lanowner, plang->lanacl);
8999 destroyPQExpBuffer(defqry);
9000 destroyPQExpBuffer(delqry);
9001 destroyPQExpBuffer(labelq);
9005 * format_function_arguments: generate function name and argument list
9007 * This is used when we can rely on pg_get_function_arguments to format
9008 * the argument list.
9011 format_function_arguments(FuncInfo *finfo, char *funcargs)
9015 initPQExpBuffer(&fn);
9016 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9021 * format_function_arguments_old: generate function name and argument list
9023 * The argument type names are qualified if needed. The function name
9024 * is never qualified.
9026 * This is used only with pre-8.4 servers, so we aren't expecting to see
9027 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9029 * Any or all of allargtypes, argmodes, argnames may be NULL.
9032 format_function_arguments_old(Archive *fout,
9033 FuncInfo *finfo, int nallargs,
9041 initPQExpBuffer(&fn);
9042 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9043 for (j = 0; j < nallargs; j++)
9047 const char *argmode;
9048 const char *argname;
9050 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9051 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9055 switch (argmodes[j][0])
9060 case PROARGMODE_OUT:
9063 case PROARGMODE_INOUT:
9067 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9075 argname = argnames ? argnames[j] : (char *) NULL;
9076 if (argname && argname[0] == '\0')
9079 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9080 (j > 0) ? ", " : "",
9082 argname ? fmtId(argname) : "",
9087 appendPQExpBuffer(&fn, ")");
9092 * format_function_signature: generate function name and argument list
9094 * This is like format_function_arguments_old except that only a minimal
9095 * list of input argument types is generated; this is sufficient to
9096 * reference the function, but not to define it.
9098 * If honor_quotes is false then the function name is never quoted.
9099 * This is appropriate for use in TOC tags, but not in SQL commands.
9102 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9107 initPQExpBuffer(&fn);
9109 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9111 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9112 for (j = 0; j < finfo->nargs; j++)
9116 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9119 appendPQExpBuffer(&fn, "%s%s",
9120 (j > 0) ? ", " : "",
9124 appendPQExpBuffer(&fn, ")");
9131 * dump out one function
9134 dumpFunc(Archive *fout, FuncInfo *finfo)
9142 char *funcsig; /* identity signature */
9143 char *funcfullsig; /* full signature */
9151 char *proallargtypes;
9165 char **allargtypes = NULL;
9166 char **argmodes = NULL;
9167 char **argnames = NULL;
9168 char **configitems = NULL;
9169 int nconfigitems = 0;
9172 /* Skip if not to be dumped */
9173 if (!finfo->dobj.dump || dataOnly)
9176 query = createPQExpBuffer();
9177 q = createPQExpBuffer();
9178 delqry = createPQExpBuffer();
9179 labelq = createPQExpBuffer();
9180 asPart = createPQExpBuffer();
9182 /* Set proper schema search path so type references list correctly */
9183 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9185 /* Fetch function-specific details */
9186 if (fout->remoteVersion >= 90200)
9189 * proleakproof was added at v9.2
9191 appendPQExpBuffer(query,
9192 "SELECT proretset, prosrc, probin, "
9193 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9194 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9195 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9196 "proiswindow, provolatile, proisstrict, prosecdef, "
9197 "proleakproof, proconfig, procost, prorows, "
9198 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9199 "FROM pg_catalog.pg_proc "
9200 "WHERE oid = '%u'::pg_catalog.oid",
9201 finfo->dobj.catId.oid);
9203 else if (fout->remoteVersion >= 80400)
9206 * In 8.4 and up we rely on pg_get_function_arguments and
9207 * pg_get_function_result instead of examining proallargtypes etc.
9209 appendPQExpBuffer(query,
9210 "SELECT proretset, prosrc, probin, "
9211 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9212 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9213 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9214 "proiswindow, provolatile, proisstrict, prosecdef, "
9215 "false AS proleakproof, "
9216 " proconfig, procost, prorows, "
9217 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9218 "FROM pg_catalog.pg_proc "
9219 "WHERE oid = '%u'::pg_catalog.oid",
9220 finfo->dobj.catId.oid);
9222 else if (fout->remoteVersion >= 80300)
9224 appendPQExpBuffer(query,
9225 "SELECT proretset, prosrc, probin, "
9226 "proallargtypes, proargmodes, proargnames, "
9227 "false AS proiswindow, "
9228 "provolatile, proisstrict, prosecdef, "
9229 "false AS proleakproof, "
9230 "proconfig, procost, prorows, "
9231 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9232 "FROM pg_catalog.pg_proc "
9233 "WHERE oid = '%u'::pg_catalog.oid",
9234 finfo->dobj.catId.oid);
9236 else if (fout->remoteVersion >= 80100)
9238 appendPQExpBuffer(query,
9239 "SELECT proretset, prosrc, probin, "
9240 "proallargtypes, proargmodes, proargnames, "
9241 "false AS proiswindow, "
9242 "provolatile, proisstrict, prosecdef, "
9243 "false AS proleakproof, "
9244 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9245 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9246 "FROM pg_catalog.pg_proc "
9247 "WHERE oid = '%u'::pg_catalog.oid",
9248 finfo->dobj.catId.oid);
9250 else if (fout->remoteVersion >= 80000)
9252 appendPQExpBuffer(query,
9253 "SELECT proretset, prosrc, probin, "
9254 "null AS proallargtypes, "
9255 "null AS proargmodes, "
9257 "false AS proiswindow, "
9258 "provolatile, proisstrict, prosecdef, "
9259 "false AS proleakproof, "
9260 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9261 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9262 "FROM pg_catalog.pg_proc "
9263 "WHERE oid = '%u'::pg_catalog.oid",
9264 finfo->dobj.catId.oid);
9266 else if (fout->remoteVersion >= 70300)
9268 appendPQExpBuffer(query,
9269 "SELECT proretset, prosrc, probin, "
9270 "null AS proallargtypes, "
9271 "null AS proargmodes, "
9272 "null AS proargnames, "
9273 "false AS proiswindow, "
9274 "provolatile, proisstrict, prosecdef, "
9275 "false AS proleakproof, "
9276 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9277 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9278 "FROM pg_catalog.pg_proc "
9279 "WHERE oid = '%u'::pg_catalog.oid",
9280 finfo->dobj.catId.oid);
9282 else if (fout->remoteVersion >= 70100)
9284 appendPQExpBuffer(query,
9285 "SELECT proretset, prosrc, probin, "
9286 "null AS proallargtypes, "
9287 "null AS proargmodes, "
9288 "null AS proargnames, "
9289 "false AS proiswindow, "
9290 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9292 "false AS prosecdef, "
9293 "false AS proleakproof, "
9294 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9295 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9297 "WHERE oid = '%u'::oid",
9298 finfo->dobj.catId.oid);
9302 appendPQExpBuffer(query,
9303 "SELECT proretset, prosrc, probin, "
9304 "null AS proallargtypes, "
9305 "null AS proargmodes, "
9306 "null AS proargnames, "
9307 "false AS proiswindow, "
9308 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9309 "false AS proisstrict, "
9310 "false AS prosecdef, "
9311 "false AS proleakproof, "
9312 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9313 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9315 "WHERE oid = '%u'::oid",
9316 finfo->dobj.catId.oid);
9319 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9321 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9322 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9323 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9324 if (fout->remoteVersion >= 80400)
9326 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9327 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9328 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9329 proallargtypes = proargmodes = proargnames = NULL;
9333 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9334 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9335 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9336 funcargs = funciargs = funcresult = NULL;
9338 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9339 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9340 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9341 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9342 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9343 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9344 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9345 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9346 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9349 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9350 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9351 * versions would set it to "-". There are no known cases in which prosrc
9352 * is unused, so the tests below for "-" are probably useless.
9354 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9356 appendPQExpBuffer(asPart, "AS ");
9357 appendStringLiteralAH(asPart, probin, fout);
9358 if (strcmp(prosrc, "-") != 0)
9360 appendPQExpBuffer(asPart, ", ");
9363 * where we have bin, use dollar quoting if allowed and src
9364 * contains quote or backslash; else use regular quoting.
9366 if (disable_dollar_quoting ||
9367 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9368 appendStringLiteralAH(asPart, prosrc, fout);
9370 appendStringLiteralDQ(asPart, prosrc, NULL);
9375 if (strcmp(prosrc, "-") != 0)
9377 appendPQExpBuffer(asPart, "AS ");
9378 /* with no bin, dollar quote src unconditionally if allowed */
9379 if (disable_dollar_quoting)
9380 appendStringLiteralAH(asPart, prosrc, fout);
9382 appendStringLiteralDQ(asPart, prosrc, NULL);
9386 nallargs = finfo->nargs; /* unless we learn different from allargs */
9388 if (proallargtypes && *proallargtypes)
9392 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9393 nitems < finfo->nargs)
9395 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9404 if (proargmodes && *proargmodes)
9408 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9411 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9418 if (proargnames && *proargnames)
9422 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9425 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9432 if (proconfig && *proconfig)
9434 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9436 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9446 /* 8.4 or later; we rely on server-side code for most of the work */
9447 funcfullsig = format_function_arguments(finfo, funcargs);
9448 funcsig = format_function_arguments(finfo, funciargs);
9452 /* pre-8.4, do it ourselves */
9453 funcsig = format_function_arguments_old(fout,
9454 finfo, nallargs, allargtypes,
9455 argmodes, argnames);
9456 funcfullsig = funcsig;
9459 funcsig_tag = format_function_signature(fout, finfo, false);
9462 * DROP must be fully qualified in case same name appears in pg_catalog
9464 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9465 fmtId(finfo->dobj.namespace->dobj.name),
9468 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9470 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9473 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9475 appendPQExpBuffer(q, "RETURNS %s%s",
9476 (proretset[0] == 't') ? "SETOF " : "",
9481 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9483 if (proiswindow[0] == 't')
9484 appendPQExpBuffer(q, " WINDOW");
9486 if (provolatile[0] != PROVOLATILE_VOLATILE)
9488 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9489 appendPQExpBuffer(q, " IMMUTABLE");
9490 else if (provolatile[0] == PROVOLATILE_STABLE)
9491 appendPQExpBuffer(q, " STABLE");
9492 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9493 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9497 if (proisstrict[0] == 't')
9498 appendPQExpBuffer(q, " STRICT");
9500 if (prosecdef[0] == 't')
9501 appendPQExpBuffer(q, " SECURITY DEFINER");
9503 if (proleakproof[0] == 't')
9504 appendPQExpBuffer(q, " LEAKPROOF");
9507 * COST and ROWS are emitted only if present and not default, so as not to
9508 * break backwards-compatibility of the dump without need. Keep this code
9509 * in sync with the defaults in functioncmds.c.
9511 if (strcmp(procost, "0") != 0)
9513 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9515 /* default cost is 1 */
9516 if (strcmp(procost, "1") != 0)
9517 appendPQExpBuffer(q, " COST %s", procost);
9521 /* default cost is 100 */
9522 if (strcmp(procost, "100") != 0)
9523 appendPQExpBuffer(q, " COST %s", procost);
9526 if (proretset[0] == 't' &&
9527 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9528 appendPQExpBuffer(q, " ROWS %s", prorows);
9530 for (i = 0; i < nconfigitems; i++)
9532 /* we feel free to scribble on configitems[] here */
9533 char *configitem = configitems[i];
9536 pos = strchr(configitem, '=');
9540 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9543 * Some GUC variable names are 'LIST' type and hence must not be
9546 if (pg_strcasecmp(configitem, "DateStyle") == 0
9547 || pg_strcasecmp(configitem, "search_path") == 0)
9548 appendPQExpBuffer(q, "%s", pos);
9550 appendStringLiteralAH(q, pos, fout);
9553 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9555 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9558 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9560 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9562 finfo->dobj.namespace->dobj.name,
9564 finfo->rolname, false,
9565 "FUNCTION", SECTION_PRE_DATA,
9566 q->data, delqry->data, NULL,
9570 /* Dump Function Comments and Security Labels */
9571 dumpComment(fout, labelq->data,
9572 finfo->dobj.namespace->dobj.name, finfo->rolname,
9573 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9574 dumpSecLabel(fout, labelq->data,
9575 finfo->dobj.namespace->dobj.name, finfo->rolname,
9576 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9578 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9579 funcsig, NULL, funcsig_tag,
9580 finfo->dobj.namespace->dobj.name,
9581 finfo->rolname, finfo->proacl);
9585 destroyPQExpBuffer(query);
9586 destroyPQExpBuffer(q);
9587 destroyPQExpBuffer(delqry);
9588 destroyPQExpBuffer(labelq);
9589 destroyPQExpBuffer(asPart);
9604 * Dump a user-defined cast
9607 dumpCast(Archive *fout, CastInfo *cast)
9612 FuncInfo *funcInfo = NULL;
9614 /* Skip if not to be dumped */
9615 if (!cast->dobj.dump || dataOnly)
9618 /* Cannot dump if we don't have the cast function's info */
9619 if (OidIsValid(cast->castfunc))
9621 funcInfo = findFuncByOid(cast->castfunc);
9622 if (funcInfo == NULL)
9627 * As per discussion we dump casts if one or more of the underlying
9628 * objects (the conversion function and the two data types) are not
9629 * builtin AND if all of the non-builtin objects are included in the dump.
9630 * Builtin meaning, the namespace name does not start with "pg_".
9632 * However, for a cast that belongs to an extension, we must not use this
9633 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9635 if (!cast->dobj.ext_member)
9637 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9638 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9640 if (sourceInfo == NULL || targetInfo == NULL)
9644 * Skip this cast if all objects are from pg_
9646 if ((funcInfo == NULL ||
9647 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9648 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9649 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9653 * Skip cast if function isn't from pg_ and is not to be dumped.
9656 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9657 !funcInfo->dobj.dump)
9661 * Same for the source type
9663 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9664 !sourceInfo->dobj.dump)
9668 * and the target type.
9670 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9671 !targetInfo->dobj.dump)
9675 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9676 selectSourceSchema(fout, "pg_catalog");
9678 defqry = createPQExpBuffer();
9679 delqry = createPQExpBuffer();
9680 labelq = createPQExpBuffer();
9682 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9683 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9684 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9686 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9687 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9688 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9690 switch (cast->castmethod)
9692 case COERCION_METHOD_BINARY:
9693 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9695 case COERCION_METHOD_INOUT:
9696 appendPQExpBuffer(defqry, "WITH INOUT");
9698 case COERCION_METHOD_FUNCTION:
9701 char *fsig = format_function_signature(fout, funcInfo, true);
9704 * Always qualify the function name, in case it is not in
9705 * pg_catalog schema (format_function_signature won't qualify
9708 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9709 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9713 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9716 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9719 if (cast->castcontext == 'a')
9720 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9721 else if (cast->castcontext == 'i')
9722 appendPQExpBuffer(defqry, " AS IMPLICIT");
9723 appendPQExpBuffer(defqry, ";\n");
9725 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9726 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9727 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9730 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9732 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9734 "pg_catalog", NULL, "",
9735 false, "CAST", SECTION_PRE_DATA,
9736 defqry->data, delqry->data, NULL,
9740 /* Dump Cast Comments */
9741 dumpComment(fout, labelq->data,
9743 cast->dobj.catId, 0, cast->dobj.dumpId);
9745 destroyPQExpBuffer(defqry);
9746 destroyPQExpBuffer(delqry);
9747 destroyPQExpBuffer(labelq);
9752 * write out a single operator definition
9755 dumpOpr(Archive *fout, OprInfo *oprinfo)
9762 PQExpBuffer details;
9786 /* Skip if not to be dumped */
9787 if (!oprinfo->dobj.dump || dataOnly)
9791 * some operators are invalid because they were the result of user
9792 * defining operators before commutators exist
9794 if (!OidIsValid(oprinfo->oprcode))
9797 query = createPQExpBuffer();
9798 q = createPQExpBuffer();
9799 delq = createPQExpBuffer();
9800 labelq = createPQExpBuffer();
9801 oprid = createPQExpBuffer();
9802 details = createPQExpBuffer();
9804 /* Make sure we are in proper schema so regoperator works correctly */
9805 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9807 if (fout->remoteVersion >= 80300)
9809 appendPQExpBuffer(query, "SELECT oprkind, "
9810 "oprcode::pg_catalog.regprocedure, "
9811 "oprleft::pg_catalog.regtype, "
9812 "oprright::pg_catalog.regtype, "
9813 "oprcom::pg_catalog.regoperator, "
9814 "oprnegate::pg_catalog.regoperator, "
9815 "oprrest::pg_catalog.regprocedure, "
9816 "oprjoin::pg_catalog.regprocedure, "
9817 "oprcanmerge, oprcanhash "
9818 "FROM pg_catalog.pg_operator "
9819 "WHERE oid = '%u'::pg_catalog.oid",
9820 oprinfo->dobj.catId.oid);
9822 else if (fout->remoteVersion >= 70300)
9824 appendPQExpBuffer(query, "SELECT oprkind, "
9825 "oprcode::pg_catalog.regprocedure, "
9826 "oprleft::pg_catalog.regtype, "
9827 "oprright::pg_catalog.regtype, "
9828 "oprcom::pg_catalog.regoperator, "
9829 "oprnegate::pg_catalog.regoperator, "
9830 "oprrest::pg_catalog.regprocedure, "
9831 "oprjoin::pg_catalog.regprocedure, "
9832 "(oprlsortop != 0) AS oprcanmerge, "
9834 "FROM pg_catalog.pg_operator "
9835 "WHERE oid = '%u'::pg_catalog.oid",
9836 oprinfo->dobj.catId.oid);
9838 else if (fout->remoteVersion >= 70100)
9840 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9841 "CASE WHEN oprleft = 0 THEN '-' "
9842 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9843 "CASE WHEN oprright = 0 THEN '-' "
9844 "ELSE format_type(oprright, NULL) END AS oprright, "
9845 "oprcom, oprnegate, oprrest, oprjoin, "
9846 "(oprlsortop != 0) AS oprcanmerge, "
9849 "WHERE oid = '%u'::oid",
9850 oprinfo->dobj.catId.oid);
9854 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9855 "CASE WHEN oprleft = 0 THEN '-'::name "
9856 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9857 "CASE WHEN oprright = 0 THEN '-'::name "
9858 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9859 "oprcom, oprnegate, oprrest, oprjoin, "
9860 "(oprlsortop != 0) AS oprcanmerge, "
9863 "WHERE oid = '%u'::oid",
9864 oprinfo->dobj.catId.oid);
9867 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9869 i_oprkind = PQfnumber(res, "oprkind");
9870 i_oprcode = PQfnumber(res, "oprcode");
9871 i_oprleft = PQfnumber(res, "oprleft");
9872 i_oprright = PQfnumber(res, "oprright");
9873 i_oprcom = PQfnumber(res, "oprcom");
9874 i_oprnegate = PQfnumber(res, "oprnegate");
9875 i_oprrest = PQfnumber(res, "oprrest");
9876 i_oprjoin = PQfnumber(res, "oprjoin");
9877 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9878 i_oprcanhash = PQfnumber(res, "oprcanhash");
9880 oprkind = PQgetvalue(res, 0, i_oprkind);
9881 oprcode = PQgetvalue(res, 0, i_oprcode);
9882 oprleft = PQgetvalue(res, 0, i_oprleft);
9883 oprright = PQgetvalue(res, 0, i_oprright);
9884 oprcom = PQgetvalue(res, 0, i_oprcom);
9885 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9886 oprrest = PQgetvalue(res, 0, i_oprrest);
9887 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9888 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9889 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9891 appendPQExpBuffer(details, " PROCEDURE = %s",
9892 convertRegProcReference(fout, oprcode));
9894 appendPQExpBuffer(oprid, "%s (",
9895 oprinfo->dobj.name);
9898 * right unary means there's a left arg and left unary means there's a
9901 if (strcmp(oprkind, "r") == 0 ||
9902 strcmp(oprkind, "b") == 0)
9904 if (fout->remoteVersion >= 70100)
9907 name = fmtId(oprleft);
9908 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9909 appendPQExpBuffer(oprid, "%s", name);
9912 appendPQExpBuffer(oprid, "NONE");
9914 if (strcmp(oprkind, "l") == 0 ||
9915 strcmp(oprkind, "b") == 0)
9917 if (fout->remoteVersion >= 70100)
9920 name = fmtId(oprright);
9921 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9922 appendPQExpBuffer(oprid, ", %s)", name);
9925 appendPQExpBuffer(oprid, ", NONE)");
9927 name = convertOperatorReference(fout, oprcom);
9929 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9931 name = convertOperatorReference(fout, oprnegate);
9933 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9935 if (strcmp(oprcanmerge, "t") == 0)
9936 appendPQExpBuffer(details, ",\n MERGES");
9938 if (strcmp(oprcanhash, "t") == 0)
9939 appendPQExpBuffer(details, ",\n HASHES");
9941 name = convertRegProcReference(fout, oprrest);
9943 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9945 name = convertRegProcReference(fout, oprjoin);
9947 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9950 * DROP must be fully qualified in case same name appears in pg_catalog
9952 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9953 fmtId(oprinfo->dobj.namespace->dobj.name),
9956 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9957 oprinfo->dobj.name, details->data);
9959 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9962 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9964 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9966 oprinfo->dobj.namespace->dobj.name,
9969 false, "OPERATOR", SECTION_PRE_DATA,
9970 q->data, delq->data, NULL,
9974 /* Dump Operator Comments */
9975 dumpComment(fout, labelq->data,
9976 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9977 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9981 destroyPQExpBuffer(query);
9982 destroyPQExpBuffer(q);
9983 destroyPQExpBuffer(delq);
9984 destroyPQExpBuffer(labelq);
9985 destroyPQExpBuffer(oprid);
9986 destroyPQExpBuffer(details);
9990 * Convert a function reference obtained from pg_operator
9992 * Returns what to print, or NULL if function references is InvalidOid
9994 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9995 * argument-types part. In prior versions, the input is a REGPROC display.
9998 convertRegProcReference(Archive *fout, const char *proc)
10000 /* In all cases "-" means a null reference */
10001 if (strcmp(proc, "-") == 0)
10004 if (fout->remoteVersion >= 70300)
10010 name = pg_strdup(proc);
10011 /* find non-double-quoted left paren */
10013 for (paren = name; *paren; paren++)
10015 if (*paren == '(' && !inquote)
10021 inquote = !inquote;
10026 /* REGPROC before 7.3 does not quote its result */
10027 return fmtId(proc);
10031 * Convert an operator cross-reference obtained from pg_operator
10033 * Returns what to print, or NULL to print nothing
10035 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10036 * argument-types part, and add OPERATOR() decoration if the name is
10037 * schema-qualified. In older versions, the input is just a numeric OID,
10038 * which we search our operator list for.
10040 static const char *
10041 convertOperatorReference(Archive *fout, const char *opr)
10045 /* In all cases "0" means a null reference */
10046 if (strcmp(opr, "0") == 0)
10049 if (fout->remoteVersion >= 70300)
10057 name = pg_strdup(opr);
10058 /* find non-double-quoted left paren, and check for non-quoted dot */
10061 for (ptr = name; *ptr; ptr++)
10064 inquote = !inquote;
10065 else if (*ptr == '.' && !inquote)
10067 else if (*ptr == '(' && !inquote)
10073 /* If not schema-qualified, don't need to add OPERATOR() */
10076 oname = pg_malloc(strlen(name) + 11);
10077 sprintf(oname, "OPERATOR(%s)", name);
10082 oprInfo = findOprByOid(atooid(opr));
10083 if (oprInfo == NULL)
10085 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10089 return oprInfo->dobj.name;
10093 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10095 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10096 * argument lists of these functions are predetermined. Note that the
10097 * caller should ensure we are in the proper schema, because the results
10098 * are search path dependent!
10100 static const char *
10101 convertTSFunction(Archive *fout, Oid funcOid)
10107 snprintf(query, sizeof(query),
10108 "SELECT '%u'::pg_catalog.regproc", funcOid);
10109 res = ExecuteSqlQueryForSingleRow(fout, query);
10111 result = pg_strdup(PQgetvalue(res, 0, 0));
10121 * write out a single operator class definition
10124 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10129 PQExpBuffer labelq;
10136 int i_opcfamilyname;
10137 int i_opcfamilynsp;
10139 int i_amopstrategy;
10140 int i_amopreqcheck;
10143 int i_sortfamilynsp;
10146 int i_amproclefttype;
10147 int i_amprocrighttype;
10152 char *opcfamilyname;
10153 char *opcfamilynsp;
10155 char *amopstrategy;
10156 char *amopreqcheck;
10159 char *sortfamilynsp;
10162 char *amproclefttype;
10163 char *amprocrighttype;
10167 /* Skip if not to be dumped */
10168 if (!opcinfo->dobj.dump || dataOnly)
10172 * XXX currently we do not implement dumping of operator classes from
10173 * pre-7.3 databases. This could be done but it seems not worth the
10176 if (fout->remoteVersion < 70300)
10179 query = createPQExpBuffer();
10180 q = createPQExpBuffer();
10181 delq = createPQExpBuffer();
10182 labelq = createPQExpBuffer();
10184 /* Make sure we are in proper schema so regoperator works correctly */
10185 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10187 /* Get additional fields from the pg_opclass row */
10188 if (fout->remoteVersion >= 80300)
10190 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10191 "opckeytype::pg_catalog.regtype, "
10192 "opcdefault, opcfamily, "
10193 "opfname AS opcfamilyname, "
10194 "nspname AS opcfamilynsp, "
10195 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10196 "FROM pg_catalog.pg_opclass c "
10197 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10198 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10199 "WHERE c.oid = '%u'::pg_catalog.oid",
10200 opcinfo->dobj.catId.oid);
10204 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10205 "opckeytype::pg_catalog.regtype, "
10206 "opcdefault, NULL AS opcfamily, "
10207 "NULL AS opcfamilyname, "
10208 "NULL AS opcfamilynsp, "
10209 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10210 "FROM pg_catalog.pg_opclass "
10211 "WHERE oid = '%u'::pg_catalog.oid",
10212 opcinfo->dobj.catId.oid);
10215 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10217 i_opcintype = PQfnumber(res, "opcintype");
10218 i_opckeytype = PQfnumber(res, "opckeytype");
10219 i_opcdefault = PQfnumber(res, "opcdefault");
10220 i_opcfamily = PQfnumber(res, "opcfamily");
10221 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10222 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10223 i_amname = PQfnumber(res, "amname");
10225 opcintype = PQgetvalue(res, 0, i_opcintype);
10226 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10227 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10228 /* opcfamily will still be needed after we PQclear res */
10229 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10230 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10231 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10232 /* amname will still be needed after we PQclear res */
10233 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10236 * DROP must be fully qualified in case same name appears in pg_catalog
10238 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10239 fmtId(opcinfo->dobj.namespace->dobj.name));
10240 appendPQExpBuffer(delq, ".%s",
10241 fmtId(opcinfo->dobj.name));
10242 appendPQExpBuffer(delq, " USING %s;\n",
10245 /* Build the fixed portion of the CREATE command */
10246 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10247 fmtId(opcinfo->dobj.name));
10248 if (strcmp(opcdefault, "t") == 0)
10249 appendPQExpBuffer(q, "DEFAULT ");
10250 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10253 if (strlen(opcfamilyname) > 0 &&
10254 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10255 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10257 appendPQExpBuffer(q, " FAMILY ");
10258 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10259 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10260 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10262 appendPQExpBuffer(q, " AS\n ");
10266 if (strcmp(opckeytype, "-") != 0)
10268 appendPQExpBuffer(q, "STORAGE %s",
10276 * Now fetch and print the OPERATOR entries (pg_amop rows).
10278 * Print only those opfamily members that are tied to the opclass by
10279 * pg_depend entries.
10281 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10282 * older server's opclass in which it is used. This is to avoid
10283 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10284 * older server and then reload into that old version. This can go away
10285 * once 8.3 is so old as to not be of interest to anyone.
10287 resetPQExpBuffer(query);
10289 if (fout->remoteVersion >= 90100)
10291 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10292 "amopopr::pg_catalog.regoperator, "
10293 "opfname AS sortfamily, "
10294 "nspname AS sortfamilynsp "
10295 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10296 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10297 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10298 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10299 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10300 "AND refobjid = '%u'::pg_catalog.oid "
10301 "AND amopfamily = '%s'::pg_catalog.oid "
10302 "ORDER BY amopstrategy",
10303 opcinfo->dobj.catId.oid,
10306 else if (fout->remoteVersion >= 80400)
10308 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10309 "amopopr::pg_catalog.regoperator, "
10310 "NULL AS sortfamily, "
10311 "NULL AS sortfamilynsp "
10312 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10313 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10314 "AND refobjid = '%u'::pg_catalog.oid "
10315 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10316 "AND objid = ao.oid "
10317 "ORDER BY amopstrategy",
10318 opcinfo->dobj.catId.oid);
10320 else if (fout->remoteVersion >= 80300)
10322 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10323 "amopopr::pg_catalog.regoperator, "
10324 "NULL AS sortfamily, "
10325 "NULL AS sortfamilynsp "
10326 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10327 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10328 "AND refobjid = '%u'::pg_catalog.oid "
10329 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10330 "AND objid = ao.oid "
10331 "ORDER BY amopstrategy",
10332 opcinfo->dobj.catId.oid);
10337 * Here, we print all entries since there are no opfamilies and hence
10338 * no loose operators to worry about.
10340 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10341 "amopopr::pg_catalog.regoperator, "
10342 "NULL AS sortfamily, "
10343 "NULL AS sortfamilynsp "
10344 "FROM pg_catalog.pg_amop "
10345 "WHERE amopclaid = '%u'::pg_catalog.oid "
10346 "ORDER BY amopstrategy",
10347 opcinfo->dobj.catId.oid);
10350 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10352 ntups = PQntuples(res);
10354 i_amopstrategy = PQfnumber(res, "amopstrategy");
10355 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10356 i_amopopr = PQfnumber(res, "amopopr");
10357 i_sortfamily = PQfnumber(res, "sortfamily");
10358 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10360 for (i = 0; i < ntups; i++)
10362 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10363 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10364 amopopr = PQgetvalue(res, i, i_amopopr);
10365 sortfamily = PQgetvalue(res, i, i_sortfamily);
10366 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10369 appendPQExpBuffer(q, " ,\n ");
10371 appendPQExpBuffer(q, "OPERATOR %s %s",
10372 amopstrategy, amopopr);
10374 if (strlen(sortfamily) > 0)
10376 appendPQExpBuffer(q, " FOR ORDER BY ");
10377 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10378 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10379 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10382 if (strcmp(amopreqcheck, "t") == 0)
10383 appendPQExpBuffer(q, " RECHECK");
10391 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10393 * Print only those opfamily members that are tied to the opclass by
10394 * pg_depend entries.
10396 * We print the amproclefttype/amprocrighttype even though in most cases
10397 * the backend could deduce the right values, because of the corner case
10398 * of a btree sort support function for a cross-type comparison. That's
10399 * only allowed in 9.2 and later, but for simplicity print them in all
10400 * versions that have the columns.
10402 resetPQExpBuffer(query);
10404 if (fout->remoteVersion >= 80300)
10406 appendPQExpBuffer(query, "SELECT amprocnum, "
10407 "amproc::pg_catalog.regprocedure, "
10408 "amproclefttype::pg_catalog.regtype, "
10409 "amprocrighttype::pg_catalog.regtype "
10410 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10411 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10412 "AND refobjid = '%u'::pg_catalog.oid "
10413 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10414 "AND objid = ap.oid "
10415 "ORDER BY amprocnum",
10416 opcinfo->dobj.catId.oid);
10420 appendPQExpBuffer(query, "SELECT amprocnum, "
10421 "amproc::pg_catalog.regprocedure, "
10422 "'' AS amproclefttype, "
10423 "'' AS amprocrighttype "
10424 "FROM pg_catalog.pg_amproc "
10425 "WHERE amopclaid = '%u'::pg_catalog.oid "
10426 "ORDER BY amprocnum",
10427 opcinfo->dobj.catId.oid);
10430 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10432 ntups = PQntuples(res);
10434 i_amprocnum = PQfnumber(res, "amprocnum");
10435 i_amproc = PQfnumber(res, "amproc");
10436 i_amproclefttype = PQfnumber(res, "amproclefttype");
10437 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10439 for (i = 0; i < ntups; i++)
10441 amprocnum = PQgetvalue(res, i, i_amprocnum);
10442 amproc = PQgetvalue(res, i, i_amproc);
10443 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10444 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10447 appendPQExpBuffer(q, " ,\n ");
10449 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10451 if (*amproclefttype && *amprocrighttype)
10452 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10454 appendPQExpBuffer(q, " %s", amproc);
10461 appendPQExpBuffer(q, ";\n");
10463 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10464 fmtId(opcinfo->dobj.name));
10465 appendPQExpBuffer(labelq, " USING %s",
10468 if (binary_upgrade)
10469 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10471 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10472 opcinfo->dobj.name,
10473 opcinfo->dobj.namespace->dobj.name,
10476 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10477 q->data, delq->data, NULL,
10481 /* Dump Operator Class Comments */
10482 dumpComment(fout, labelq->data,
10483 NULL, opcinfo->rolname,
10484 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10487 destroyPQExpBuffer(query);
10488 destroyPQExpBuffer(q);
10489 destroyPQExpBuffer(delq);
10490 destroyPQExpBuffer(labelq);
10495 * write out a single operator family definition
10497 * Note: this also dumps any "loose" operator members that aren't bound to a
10498 * specific opclass within the opfamily.
10501 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10506 PQExpBuffer labelq;
10509 PGresult *res_procs;
10512 int i_amopstrategy;
10513 int i_amopreqcheck;
10516 int i_sortfamilynsp;
10519 int i_amproclefttype;
10520 int i_amprocrighttype;
10522 char *amopstrategy;
10523 char *amopreqcheck;
10526 char *sortfamilynsp;
10529 char *amproclefttype;
10530 char *amprocrighttype;
10534 /* Skip if not to be dumped */
10535 if (!opfinfo->dobj.dump || dataOnly)
10539 * We want to dump the opfamily only if (1) it contains "loose" operators
10540 * or functions, or (2) it contains an opclass with a different name or
10541 * owner. Otherwise it's sufficient to let it be created during creation
10542 * of the contained opclass, and not dumping it improves portability of
10543 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10547 query = createPQExpBuffer();
10548 q = createPQExpBuffer();
10549 delq = createPQExpBuffer();
10550 labelq = createPQExpBuffer();
10552 /* Make sure we are in proper schema so regoperator works correctly */
10553 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10556 * Fetch only those opfamily members that are tied directly to the
10557 * opfamily by pg_depend entries.
10559 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10560 * older server's opclass in which it is used. This is to avoid
10561 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10562 * older server and then reload into that old version. This can go away
10563 * once 8.3 is so old as to not be of interest to anyone.
10565 if (fout->remoteVersion >= 90100)
10567 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10568 "amopopr::pg_catalog.regoperator, "
10569 "opfname AS sortfamily, "
10570 "nspname AS sortfamilynsp "
10571 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10572 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10573 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10574 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10575 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10576 "AND refobjid = '%u'::pg_catalog.oid "
10577 "AND amopfamily = '%u'::pg_catalog.oid "
10578 "ORDER BY amopstrategy",
10579 opfinfo->dobj.catId.oid,
10580 opfinfo->dobj.catId.oid);
10582 else if (fout->remoteVersion >= 80400)
10584 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10585 "amopopr::pg_catalog.regoperator, "
10586 "NULL AS sortfamily, "
10587 "NULL AS sortfamilynsp "
10588 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10589 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10590 "AND refobjid = '%u'::pg_catalog.oid "
10591 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10592 "AND objid = ao.oid "
10593 "ORDER BY amopstrategy",
10594 opfinfo->dobj.catId.oid);
10598 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10599 "amopopr::pg_catalog.regoperator, "
10600 "NULL AS sortfamily, "
10601 "NULL AS sortfamilynsp "
10602 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10603 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10604 "AND refobjid = '%u'::pg_catalog.oid "
10605 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10606 "AND objid = ao.oid "
10607 "ORDER BY amopstrategy",
10608 opfinfo->dobj.catId.oid);
10611 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10613 resetPQExpBuffer(query);
10615 appendPQExpBuffer(query, "SELECT amprocnum, "
10616 "amproc::pg_catalog.regprocedure, "
10617 "amproclefttype::pg_catalog.regtype, "
10618 "amprocrighttype::pg_catalog.regtype "
10619 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10620 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10621 "AND refobjid = '%u'::pg_catalog.oid "
10622 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10623 "AND objid = ap.oid "
10624 "ORDER BY amprocnum",
10625 opfinfo->dobj.catId.oid);
10627 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10629 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10631 /* No loose members, so check contained opclasses */
10632 resetPQExpBuffer(query);
10634 appendPQExpBuffer(query, "SELECT 1 "
10635 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10636 "WHERE f.oid = '%u'::pg_catalog.oid "
10637 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10638 "AND refobjid = f.oid "
10639 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10640 "AND objid = c.oid "
10641 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10643 opfinfo->dobj.catId.oid);
10645 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10647 if (PQntuples(res) == 0)
10649 /* no need to dump it, so bail out */
10652 PQclear(res_procs);
10653 destroyPQExpBuffer(query);
10654 destroyPQExpBuffer(q);
10655 destroyPQExpBuffer(delq);
10656 destroyPQExpBuffer(labelq);
10663 /* Get additional fields from the pg_opfamily row */
10664 resetPQExpBuffer(query);
10666 appendPQExpBuffer(query, "SELECT "
10667 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10668 "FROM pg_catalog.pg_opfamily "
10669 "WHERE oid = '%u'::pg_catalog.oid",
10670 opfinfo->dobj.catId.oid);
10672 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10674 i_amname = PQfnumber(res, "amname");
10676 /* amname will still be needed after we PQclear res */
10677 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10680 * DROP must be fully qualified in case same name appears in pg_catalog
10682 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10683 fmtId(opfinfo->dobj.namespace->dobj.name));
10684 appendPQExpBuffer(delq, ".%s",
10685 fmtId(opfinfo->dobj.name));
10686 appendPQExpBuffer(delq, " USING %s;\n",
10689 /* Build the fixed portion of the CREATE command */
10690 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10691 fmtId(opfinfo->dobj.name));
10692 appendPQExpBuffer(q, " USING %s;\n",
10697 /* Do we need an ALTER to add loose members? */
10698 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10700 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10701 fmtId(opfinfo->dobj.name));
10702 appendPQExpBuffer(q, " USING %s ADD\n ",
10708 * Now fetch and print the OPERATOR entries (pg_amop rows).
10710 ntups = PQntuples(res_ops);
10712 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10713 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10714 i_amopopr = PQfnumber(res_ops, "amopopr");
10715 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10716 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10718 for (i = 0; i < ntups; i++)
10720 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10721 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10722 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10723 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10724 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10727 appendPQExpBuffer(q, " ,\n ");
10729 appendPQExpBuffer(q, "OPERATOR %s %s",
10730 amopstrategy, amopopr);
10732 if (strlen(sortfamily) > 0)
10734 appendPQExpBuffer(q, " FOR ORDER BY ");
10735 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10736 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10737 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10740 if (strcmp(amopreqcheck, "t") == 0)
10741 appendPQExpBuffer(q, " RECHECK");
10747 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10749 ntups = PQntuples(res_procs);
10751 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10752 i_amproc = PQfnumber(res_procs, "amproc");
10753 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10754 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10756 for (i = 0; i < ntups; i++)
10758 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10759 amproc = PQgetvalue(res_procs, i, i_amproc);
10760 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10761 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10764 appendPQExpBuffer(q, " ,\n ");
10766 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10767 amprocnum, amproclefttype, amprocrighttype,
10773 appendPQExpBuffer(q, ";\n");
10776 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10777 fmtId(opfinfo->dobj.name));
10778 appendPQExpBuffer(labelq, " USING %s",
10781 if (binary_upgrade)
10782 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10784 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10785 opfinfo->dobj.name,
10786 opfinfo->dobj.namespace->dobj.name,
10789 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10790 q->data, delq->data, NULL,
10794 /* Dump Operator Family Comments */
10795 dumpComment(fout, labelq->data,
10796 NULL, opfinfo->rolname,
10797 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10801 PQclear(res_procs);
10802 destroyPQExpBuffer(query);
10803 destroyPQExpBuffer(q);
10804 destroyPQExpBuffer(delq);
10805 destroyPQExpBuffer(labelq);
10810 * write out a single collation definition
10813 dumpCollation(Archive *fout, CollInfo *collinfo)
10818 PQExpBuffer labelq;
10822 const char *collcollate;
10823 const char *collctype;
10825 /* Skip if not to be dumped */
10826 if (!collinfo->dobj.dump || dataOnly)
10829 query = createPQExpBuffer();
10830 q = createPQExpBuffer();
10831 delq = createPQExpBuffer();
10832 labelq = createPQExpBuffer();
10834 /* Make sure we are in proper schema */
10835 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10837 /* Get conversion-specific details */
10838 appendPQExpBuffer(query, "SELECT "
10841 "FROM pg_catalog.pg_collation c "
10842 "WHERE c.oid = '%u'::pg_catalog.oid",
10843 collinfo->dobj.catId.oid);
10845 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10847 i_collcollate = PQfnumber(res, "collcollate");
10848 i_collctype = PQfnumber(res, "collctype");
10850 collcollate = PQgetvalue(res, 0, i_collcollate);
10851 collctype = PQgetvalue(res, 0, i_collctype);
10854 * DROP must be fully qualified in case same name appears in pg_catalog
10856 appendPQExpBuffer(delq, "DROP COLLATION %s",
10857 fmtId(collinfo->dobj.namespace->dobj.name));
10858 appendPQExpBuffer(delq, ".%s;\n",
10859 fmtId(collinfo->dobj.name));
10861 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10862 fmtId(collinfo->dobj.name));
10863 appendStringLiteralAH(q, collcollate, fout);
10864 appendPQExpBuffer(q, ", lc_ctype = ");
10865 appendStringLiteralAH(q, collctype, fout);
10866 appendPQExpBuffer(q, ");\n");
10868 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10870 if (binary_upgrade)
10871 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10873 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10874 collinfo->dobj.name,
10875 collinfo->dobj.namespace->dobj.name,
10878 false, "COLLATION", SECTION_PRE_DATA,
10879 q->data, delq->data, NULL,
10883 /* Dump Collation Comments */
10884 dumpComment(fout, labelq->data,
10885 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10886 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10890 destroyPQExpBuffer(query);
10891 destroyPQExpBuffer(q);
10892 destroyPQExpBuffer(delq);
10893 destroyPQExpBuffer(labelq);
10898 * write out a single conversion definition
10901 dumpConversion(Archive *fout, ConvInfo *convinfo)
10906 PQExpBuffer labelq;
10908 int i_conforencoding;
10909 int i_contoencoding;
10912 const char *conforencoding;
10913 const char *contoencoding;
10914 const char *conproc;
10917 /* Skip if not to be dumped */
10918 if (!convinfo->dobj.dump || dataOnly)
10921 query = createPQExpBuffer();
10922 q = createPQExpBuffer();
10923 delq = createPQExpBuffer();
10924 labelq = createPQExpBuffer();
10926 /* Make sure we are in proper schema */
10927 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10929 /* Get conversion-specific details */
10930 appendPQExpBuffer(query, "SELECT "
10931 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10932 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10933 "conproc, condefault "
10934 "FROM pg_catalog.pg_conversion c "
10935 "WHERE c.oid = '%u'::pg_catalog.oid",
10936 convinfo->dobj.catId.oid);
10938 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10940 i_conforencoding = PQfnumber(res, "conforencoding");
10941 i_contoencoding = PQfnumber(res, "contoencoding");
10942 i_conproc = PQfnumber(res, "conproc");
10943 i_condefault = PQfnumber(res, "condefault");
10945 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10946 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10947 conproc = PQgetvalue(res, 0, i_conproc);
10948 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10951 * DROP must be fully qualified in case same name appears in pg_catalog
10953 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10954 fmtId(convinfo->dobj.namespace->dobj.name));
10955 appendPQExpBuffer(delq, ".%s;\n",
10956 fmtId(convinfo->dobj.name));
10958 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10959 (condefault) ? "DEFAULT " : "",
10960 fmtId(convinfo->dobj.name));
10961 appendStringLiteralAH(q, conforencoding, fout);
10962 appendPQExpBuffer(q, " TO ");
10963 appendStringLiteralAH(q, contoencoding, fout);
10964 /* regproc is automatically quoted in 7.3 and above */
10965 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10967 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10969 if (binary_upgrade)
10970 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10972 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10973 convinfo->dobj.name,
10974 convinfo->dobj.namespace->dobj.name,
10977 false, "CONVERSION", SECTION_PRE_DATA,
10978 q->data, delq->data, NULL,
10982 /* Dump Conversion Comments */
10983 dumpComment(fout, labelq->data,
10984 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10985 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10989 destroyPQExpBuffer(query);
10990 destroyPQExpBuffer(q);
10991 destroyPQExpBuffer(delq);
10992 destroyPQExpBuffer(labelq);
10996 * format_aggregate_signature: generate aggregate name and argument list
10998 * The argument type names are qualified if needed. The aggregate name
10999 * is never qualified.
11002 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11004 PQExpBufferData buf;
11007 initPQExpBuffer(&buf);
11009 appendPQExpBuffer(&buf, "%s",
11010 fmtId(agginfo->aggfn.dobj.name));
11012 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11014 if (agginfo->aggfn.nargs == 0)
11015 appendPQExpBuffer(&buf, "(*)");
11018 appendPQExpBuffer(&buf, "(");
11019 for (j = 0; j < agginfo->aggfn.nargs; j++)
11023 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11026 appendPQExpBuffer(&buf, "%s%s",
11027 (j > 0) ? ", " : "",
11031 appendPQExpBuffer(&buf, ")");
11038 * write out a single aggregate definition
11041 dumpAgg(Archive *fout, AggInfo *agginfo)
11046 PQExpBuffer labelq;
11047 PQExpBuffer details;
11054 int i_aggtranstype;
11057 const char *aggtransfn;
11058 const char *aggfinalfn;
11059 const char *aggsortop;
11060 const char *aggtranstype;
11061 const char *agginitval;
11064 /* Skip if not to be dumped */
11065 if (!agginfo->aggfn.dobj.dump || dataOnly)
11068 query = createPQExpBuffer();
11069 q = createPQExpBuffer();
11070 delq = createPQExpBuffer();
11071 labelq = createPQExpBuffer();
11072 details = createPQExpBuffer();
11074 /* Make sure we are in proper schema */
11075 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11077 /* Get aggregate-specific details */
11078 if (fout->remoteVersion >= 80100)
11080 appendPQExpBuffer(query, "SELECT aggtransfn, "
11081 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11082 "aggsortop::pg_catalog.regoperator, "
11084 "'t'::boolean AS convertok "
11085 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11086 "WHERE a.aggfnoid = p.oid "
11087 "AND p.oid = '%u'::pg_catalog.oid",
11088 agginfo->aggfn.dobj.catId.oid);
11090 else if (fout->remoteVersion >= 70300)
11092 appendPQExpBuffer(query, "SELECT aggtransfn, "
11093 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11096 "'t'::boolean AS convertok "
11097 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11098 "WHERE a.aggfnoid = p.oid "
11099 "AND p.oid = '%u'::pg_catalog.oid",
11100 agginfo->aggfn.dobj.catId.oid);
11102 else if (fout->remoteVersion >= 70100)
11104 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11105 "format_type(aggtranstype, NULL) AS aggtranstype, "
11108 "'t'::boolean AS convertok "
11109 "FROM pg_aggregate "
11110 "WHERE oid = '%u'::oid",
11111 agginfo->aggfn.dobj.catId.oid);
11115 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11117 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11119 "agginitval1 AS agginitval, "
11120 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11121 "FROM pg_aggregate "
11122 "WHERE oid = '%u'::oid",
11123 agginfo->aggfn.dobj.catId.oid);
11126 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11128 i_aggtransfn = PQfnumber(res, "aggtransfn");
11129 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11130 i_aggsortop = PQfnumber(res, "aggsortop");
11131 i_aggtranstype = PQfnumber(res, "aggtranstype");
11132 i_agginitval = PQfnumber(res, "agginitval");
11133 i_convertok = PQfnumber(res, "convertok");
11135 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11136 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11137 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11138 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11139 agginitval = PQgetvalue(res, 0, i_agginitval);
11140 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11142 aggsig = format_aggregate_signature(agginfo, fout, true);
11143 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11147 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11152 if (fout->remoteVersion >= 70300)
11154 /* If using 7.3's regproc or regtype, data is already quoted */
11155 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11159 else if (fout->remoteVersion >= 70100)
11161 /* format_type quotes, regproc does not */
11162 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11168 /* need quotes all around */
11169 appendPQExpBuffer(details, " SFUNC = %s,\n",
11170 fmtId(aggtransfn));
11171 appendPQExpBuffer(details, " STYPE = %s",
11172 fmtId(aggtranstype));
11175 if (!PQgetisnull(res, 0, i_agginitval))
11177 appendPQExpBuffer(details, ",\n INITCOND = ");
11178 appendStringLiteralAH(details, agginitval, fout);
11181 if (strcmp(aggfinalfn, "-") != 0)
11183 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11187 aggsortop = convertOperatorReference(fout, aggsortop);
11190 appendPQExpBuffer(details, ",\n SORTOP = %s",
11195 * DROP must be fully qualified in case same name appears in pg_catalog
11197 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11198 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11201 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11202 aggsig, details->data);
11204 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11206 if (binary_upgrade)
11207 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11209 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11211 agginfo->aggfn.dobj.namespace->dobj.name,
11213 agginfo->aggfn.rolname,
11214 false, "AGGREGATE", SECTION_PRE_DATA,
11215 q->data, delq->data, NULL,
11219 /* Dump Aggregate Comments */
11220 dumpComment(fout, labelq->data,
11221 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11222 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11223 dumpSecLabel(fout, labelq->data,
11224 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11225 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11228 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11229 * command look like a function's GRANT; in particular this affects the
11230 * syntax for zero-argument aggregates.
11235 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11236 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11238 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11240 aggsig, NULL, aggsig_tag,
11241 agginfo->aggfn.dobj.namespace->dobj.name,
11242 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11249 destroyPQExpBuffer(query);
11250 destroyPQExpBuffer(q);
11251 destroyPQExpBuffer(delq);
11252 destroyPQExpBuffer(labelq);
11253 destroyPQExpBuffer(details);
11258 * write out a single text search parser
11261 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11265 PQExpBuffer labelq;
11267 /* Skip if not to be dumped */
11268 if (!prsinfo->dobj.dump || dataOnly)
11271 q = createPQExpBuffer();
11272 delq = createPQExpBuffer();
11273 labelq = createPQExpBuffer();
11275 /* Make sure we are in proper schema */
11276 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11278 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11279 fmtId(prsinfo->dobj.name));
11281 appendPQExpBuffer(q, " START = %s,\n",
11282 convertTSFunction(fout, prsinfo->prsstart));
11283 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11284 convertTSFunction(fout, prsinfo->prstoken));
11285 appendPQExpBuffer(q, " END = %s,\n",
11286 convertTSFunction(fout, prsinfo->prsend));
11287 if (prsinfo->prsheadline != InvalidOid)
11288 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11289 convertTSFunction(fout, prsinfo->prsheadline));
11290 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11291 convertTSFunction(fout, prsinfo->prslextype));
11294 * DROP must be fully qualified in case same name appears in pg_catalog
11296 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11297 fmtId(prsinfo->dobj.namespace->dobj.name));
11298 appendPQExpBuffer(delq, ".%s;\n",
11299 fmtId(prsinfo->dobj.name));
11301 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11302 fmtId(prsinfo->dobj.name));
11304 if (binary_upgrade)
11305 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11307 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11308 prsinfo->dobj.name,
11309 prsinfo->dobj.namespace->dobj.name,
11312 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11313 q->data, delq->data, NULL,
11317 /* Dump Parser Comments */
11318 dumpComment(fout, labelq->data,
11320 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11322 destroyPQExpBuffer(q);
11323 destroyPQExpBuffer(delq);
11324 destroyPQExpBuffer(labelq);
11329 * write out a single text search dictionary
11332 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11336 PQExpBuffer labelq;
11342 /* Skip if not to be dumped */
11343 if (!dictinfo->dobj.dump || dataOnly)
11346 q = createPQExpBuffer();
11347 delq = createPQExpBuffer();
11348 labelq = createPQExpBuffer();
11349 query = createPQExpBuffer();
11351 /* Fetch name and namespace of the dictionary's template */
11352 selectSourceSchema(fout, "pg_catalog");
11353 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11354 "FROM pg_ts_template p, pg_namespace n "
11355 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11356 dictinfo->dicttemplate);
11357 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11358 nspname = PQgetvalue(res, 0, 0);
11359 tmplname = PQgetvalue(res, 0, 1);
11361 /* Make sure we are in proper schema */
11362 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11364 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11365 fmtId(dictinfo->dobj.name));
11367 appendPQExpBuffer(q, " TEMPLATE = ");
11368 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11369 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11370 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11374 /* the dictinitoption can be dumped straight into the command */
11375 if (dictinfo->dictinitoption)
11376 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11378 appendPQExpBuffer(q, " );\n");
11381 * DROP must be fully qualified in case same name appears in pg_catalog
11383 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11384 fmtId(dictinfo->dobj.namespace->dobj.name));
11385 appendPQExpBuffer(delq, ".%s;\n",
11386 fmtId(dictinfo->dobj.name));
11388 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11389 fmtId(dictinfo->dobj.name));
11391 if (binary_upgrade)
11392 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11394 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11395 dictinfo->dobj.name,
11396 dictinfo->dobj.namespace->dobj.name,
11399 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11400 q->data, delq->data, NULL,
11404 /* Dump Dictionary Comments */
11405 dumpComment(fout, labelq->data,
11406 NULL, dictinfo->rolname,
11407 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11409 destroyPQExpBuffer(q);
11410 destroyPQExpBuffer(delq);
11411 destroyPQExpBuffer(labelq);
11412 destroyPQExpBuffer(query);
11417 * write out a single text search template
11420 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11424 PQExpBuffer labelq;
11426 /* Skip if not to be dumped */
11427 if (!tmplinfo->dobj.dump || dataOnly)
11430 q = createPQExpBuffer();
11431 delq = createPQExpBuffer();
11432 labelq = createPQExpBuffer();
11434 /* Make sure we are in proper schema */
11435 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11437 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11438 fmtId(tmplinfo->dobj.name));
11440 if (tmplinfo->tmplinit != InvalidOid)
11441 appendPQExpBuffer(q, " INIT = %s,\n",
11442 convertTSFunction(fout, tmplinfo->tmplinit));
11443 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11444 convertTSFunction(fout, tmplinfo->tmpllexize));
11447 * DROP must be fully qualified in case same name appears in pg_catalog
11449 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11450 fmtId(tmplinfo->dobj.namespace->dobj.name));
11451 appendPQExpBuffer(delq, ".%s;\n",
11452 fmtId(tmplinfo->dobj.name));
11454 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11455 fmtId(tmplinfo->dobj.name));
11457 if (binary_upgrade)
11458 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11460 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11461 tmplinfo->dobj.name,
11462 tmplinfo->dobj.namespace->dobj.name,
11465 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11466 q->data, delq->data, NULL,
11470 /* Dump Template Comments */
11471 dumpComment(fout, labelq->data,
11473 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11475 destroyPQExpBuffer(q);
11476 destroyPQExpBuffer(delq);
11477 destroyPQExpBuffer(labelq);
11482 * write out a single text search configuration
11485 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11489 PQExpBuffer labelq;
11499 /* Skip if not to be dumped */
11500 if (!cfginfo->dobj.dump || dataOnly)
11503 q = createPQExpBuffer();
11504 delq = createPQExpBuffer();
11505 labelq = createPQExpBuffer();
11506 query = createPQExpBuffer();
11508 /* Fetch name and namespace of the config's parser */
11509 selectSourceSchema(fout, "pg_catalog");
11510 appendPQExpBuffer(query, "SELECT nspname, prsname "
11511 "FROM pg_ts_parser p, pg_namespace n "
11512 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11513 cfginfo->cfgparser);
11514 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11515 nspname = PQgetvalue(res, 0, 0);
11516 prsname = PQgetvalue(res, 0, 1);
11518 /* Make sure we are in proper schema */
11519 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11521 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11522 fmtId(cfginfo->dobj.name));
11524 appendPQExpBuffer(q, " PARSER = ");
11525 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11526 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11527 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11531 resetPQExpBuffer(query);
11532 appendPQExpBuffer(query,
11534 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11535 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11536 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11537 "FROM pg_catalog.pg_ts_config_map AS m \n"
11538 "WHERE m.mapcfg = '%u' \n"
11539 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11540 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11542 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11543 ntups = PQntuples(res);
11545 i_tokenname = PQfnumber(res, "tokenname");
11546 i_dictname = PQfnumber(res, "dictname");
11548 for (i = 0; i < ntups; i++)
11550 char *tokenname = PQgetvalue(res, i, i_tokenname);
11551 char *dictname = PQgetvalue(res, i, i_dictname);
11554 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11556 /* starting a new token type, so start a new command */
11558 appendPQExpBuffer(q, ";\n");
11559 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11560 fmtId(cfginfo->dobj.name));
11561 /* tokenname needs quoting, dictname does NOT */
11562 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11563 fmtId(tokenname), dictname);
11566 appendPQExpBuffer(q, ", %s", dictname);
11570 appendPQExpBuffer(q, ";\n");
11575 * DROP must be fully qualified in case same name appears in pg_catalog
11577 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11578 fmtId(cfginfo->dobj.namespace->dobj.name));
11579 appendPQExpBuffer(delq, ".%s;\n",
11580 fmtId(cfginfo->dobj.name));
11582 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11583 fmtId(cfginfo->dobj.name));
11585 if (binary_upgrade)
11586 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11588 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11589 cfginfo->dobj.name,
11590 cfginfo->dobj.namespace->dobj.name,
11593 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11594 q->data, delq->data, NULL,
11598 /* Dump Configuration Comments */
11599 dumpComment(fout, labelq->data,
11600 NULL, cfginfo->rolname,
11601 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11603 destroyPQExpBuffer(q);
11604 destroyPQExpBuffer(delq);
11605 destroyPQExpBuffer(labelq);
11606 destroyPQExpBuffer(query);
11610 * dumpForeignDataWrapper
11611 * write out a single foreign-data wrapper definition
11614 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11618 PQExpBuffer labelq;
11621 /* Skip if not to be dumped */
11622 if (!fdwinfo->dobj.dump || dataOnly)
11626 * FDWs that belong to an extension are dumped based on their "dump"
11627 * field. Otherwise omit them if we are only dumping some specific object.
11629 if (!fdwinfo->dobj.ext_member)
11630 if (!include_everything)
11633 q = createPQExpBuffer();
11634 delq = createPQExpBuffer();
11635 labelq = createPQExpBuffer();
11637 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11639 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11642 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11643 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11645 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11646 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11648 if (strlen(fdwinfo->fdwoptions) > 0)
11649 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11651 appendPQExpBuffer(q, ";\n");
11653 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11656 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11659 if (binary_upgrade)
11660 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11662 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11663 fdwinfo->dobj.name,
11667 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11668 q->data, delq->data, NULL,
11672 /* Handle the ACL */
11673 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11674 "FOREIGN DATA WRAPPER",
11675 qfdwname, NULL, fdwinfo->dobj.name,
11676 NULL, fdwinfo->rolname,
11679 /* Dump Foreign Data Wrapper Comments */
11680 dumpComment(fout, labelq->data,
11681 NULL, fdwinfo->rolname,
11682 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11686 destroyPQExpBuffer(q);
11687 destroyPQExpBuffer(delq);
11688 destroyPQExpBuffer(labelq);
11692 * dumpForeignServer
11693 * write out a foreign server definition
11696 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11700 PQExpBuffer labelq;
11706 /* Skip if not to be dumped */
11707 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11710 q = createPQExpBuffer();
11711 delq = createPQExpBuffer();
11712 labelq = createPQExpBuffer();
11713 query = createPQExpBuffer();
11715 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11717 /* look up the foreign-data wrapper */
11718 selectSourceSchema(fout, "pg_catalog");
11719 appendPQExpBuffer(query, "SELECT fdwname "
11720 "FROM pg_foreign_data_wrapper w "
11721 "WHERE w.oid = '%u'",
11723 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11724 fdwname = PQgetvalue(res, 0, 0);
11726 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11727 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11729 appendPQExpBuffer(q, " TYPE ");
11730 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11732 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11734 appendPQExpBuffer(q, " VERSION ");
11735 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11738 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11739 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11741 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11742 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11744 appendPQExpBuffer(q, ";\n");
11746 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11749 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11751 if (binary_upgrade)
11752 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11754 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11755 srvinfo->dobj.name,
11759 false, "SERVER", SECTION_PRE_DATA,
11760 q->data, delq->data, NULL,
11764 /* Handle the ACL */
11765 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11767 qsrvname, NULL, srvinfo->dobj.name,
11768 NULL, srvinfo->rolname,
11771 /* Dump user mappings */
11772 dumpUserMappings(fout,
11773 srvinfo->dobj.name, NULL,
11775 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11777 /* Dump Foreign Server Comments */
11778 dumpComment(fout, labelq->data,
11779 NULL, srvinfo->rolname,
11780 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11784 destroyPQExpBuffer(q);
11785 destroyPQExpBuffer(delq);
11786 destroyPQExpBuffer(labelq);
11792 * This routine is used to dump any user mappings associated with the
11793 * server handed to this routine. Should be called after ArchiveEntry()
11797 dumpUserMappings(Archive *fout,
11798 const char *servername, const char *namespace,
11800 CatalogId catalogId, DumpId dumpId)
11812 q = createPQExpBuffer();
11813 tag = createPQExpBuffer();
11814 delq = createPQExpBuffer();
11815 query = createPQExpBuffer();
11818 * We read from the publicly accessible view pg_user_mappings, so as not
11819 * to fail if run by a non-superuser. Note that the view will show
11820 * umoptions as null if the user hasn't got privileges for the associated
11821 * server; this means that pg_dump will dump such a mapping, but with no
11822 * OPTIONS clause. A possible alternative is to skip such mappings
11823 * altogether, but it's not clear that that's an improvement.
11825 selectSourceSchema(fout, "pg_catalog");
11827 appendPQExpBuffer(query,
11829 "array_to_string(ARRAY("
11830 "SELECT quote_ident(option_name) || ' ' || "
11831 "quote_literal(option_value) "
11832 "FROM pg_options_to_table(umoptions) "
11833 "ORDER BY option_name"
11834 "), E',\n ') AS umoptions "
11835 "FROM pg_user_mappings "
11836 "WHERE srvid = '%u' "
11837 "ORDER BY usename",
11840 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11842 ntups = PQntuples(res);
11843 i_usename = PQfnumber(res, "usename");
11844 i_umoptions = PQfnumber(res, "umoptions");
11846 for (i = 0; i < ntups; i++)
11851 usename = PQgetvalue(res, i, i_usename);
11852 umoptions = PQgetvalue(res, i, i_umoptions);
11854 resetPQExpBuffer(q);
11855 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11856 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11858 if (umoptions && strlen(umoptions) > 0)
11859 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11861 appendPQExpBuffer(q, ";\n");
11863 resetPQExpBuffer(delq);
11864 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11865 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11867 resetPQExpBuffer(tag);
11868 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11869 usename, servername);
11871 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11876 "USER MAPPING", SECTION_PRE_DATA,
11877 q->data, delq->data, NULL,
11884 destroyPQExpBuffer(query);
11885 destroyPQExpBuffer(delq);
11886 destroyPQExpBuffer(q);
11890 * Write out default privileges information
11893 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11899 /* Skip if not to be dumped */
11900 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11903 q = createPQExpBuffer();
11904 tag = createPQExpBuffer();
11906 switch (daclinfo->defaclobjtype)
11908 case DEFACLOBJ_RELATION:
11911 case DEFACLOBJ_SEQUENCE:
11912 type = "SEQUENCES";
11914 case DEFACLOBJ_FUNCTION:
11915 type = "FUNCTIONS";
11917 case DEFACLOBJ_TYPE:
11921 /* shouldn't get here */
11922 exit_horribly(NULL,
11923 "unrecognized object type in default privileges: %d\n",
11924 (int) daclinfo->defaclobjtype);
11925 type = ""; /* keep compiler quiet */
11928 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11930 /* build the actual command(s) for this tuple */
11931 if (!buildDefaultACLCommands(type,
11932 daclinfo->dobj.namespace != NULL ?
11933 daclinfo->dobj.namespace->dobj.name : NULL,
11934 daclinfo->defaclacl,
11935 daclinfo->defaclrole,
11936 fout->remoteVersion,
11938 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
11939 daclinfo->defaclacl);
11941 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11943 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11945 daclinfo->defaclrole,
11946 false, "DEFAULT ACL", SECTION_POST_DATA,
11951 destroyPQExpBuffer(tag);
11952 destroyPQExpBuffer(q);
11956 * Write out grant/revoke information
11958 * 'objCatId' is the catalog ID of the underlying object.
11959 * 'objDumpId' is the dump ID of the underlying object.
11960 * 'type' must be one of
11961 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11962 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11963 * 'name' is the formatted name of the object. Must be quoted etc. already.
11964 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11965 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11966 * 'nspname' is the namespace the object is in (NULL if none).
11967 * 'owner' is the owner, NULL if there is no owner (for languages).
11968 * 'acls' is the string read out of the fooacl system catalog field;
11969 * it will be parsed here.
11973 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11974 const char *type, const char *name, const char *subname,
11975 const char *tag, const char *nspname, const char *owner,
11980 /* Do nothing if ACL dump is not enabled */
11984 /* --data-only skips ACLs *except* BLOB ACLs */
11985 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11988 sql = createPQExpBuffer();
11990 if (!buildACLCommands(name, subname, type, acls, owner,
11991 "", fout->remoteVersion, sql))
11992 exit_horribly(NULL,
11993 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11997 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12000 owner ? owner : "",
12001 false, "ACL", SECTION_NONE,
12002 sql->data, "", NULL,
12006 destroyPQExpBuffer(sql);
12012 * This routine is used to dump any security labels associated with the
12013 * object handed to this routine. The routine takes a constant character
12014 * string for the target part of the security-label command, plus
12015 * the namespace and owner of the object (for labeling the ArchiveEntry),
12016 * plus catalog ID and subid which are the lookup key for pg_seclabel,
12017 * plus the dump ID for the object (for setting a dependency).
12018 * If a matching pg_seclabel entry is found, it is dumped.
12020 * Note: although this routine takes a dumpId for dependency purposes,
12021 * that purpose is just to mark the dependency in the emitted dump file
12022 * for possible future use by pg_restore. We do NOT use it for determining
12023 * ordering of the label in the dump file, because this routine is called
12024 * after dependency sorting occurs. This routine should be called just after
12025 * calling ArchiveEntry() for the specified object.
12028 dumpSecLabel(Archive *fout, const char *target,
12029 const char *namespace, const char *owner,
12030 CatalogId catalogId, int subid, DumpId dumpId)
12032 SecLabelItem *labels;
12037 /* do nothing, if --no-security-labels is supplied */
12038 if (no_security_labels)
12041 /* Comments are schema not data ... except blob comments are data */
12042 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12053 /* Search for security labels associated with catalogId, using table */
12054 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12056 query = createPQExpBuffer();
12058 for (i = 0; i < nlabels; i++)
12061 * Ignore label entries for which the subid doesn't match.
12063 if (labels[i].objsubid != subid)
12066 appendPQExpBuffer(query,
12067 "SECURITY LABEL FOR %s ON %s IS ",
12068 fmtId(labels[i].provider), target);
12069 appendStringLiteralAH(query, labels[i].label, fout);
12070 appendPQExpBuffer(query, ";\n");
12073 if (query->len > 0)
12075 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12076 target, namespace, NULL, owner,
12077 false, "SECURITY LABEL", SECTION_NONE,
12078 query->data, "", NULL,
12082 destroyPQExpBuffer(query);
12086 * dumpTableSecLabel
12088 * As above, but dump security label for both the specified table (or view)
12092 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12094 SecLabelItem *labels;
12098 PQExpBuffer target;
12100 /* do nothing, if --no-security-labels is supplied */
12101 if (no_security_labels)
12104 /* SecLabel are SCHEMA not data */
12108 /* Search for comments associated with relation, using table */
12109 nlabels = findSecLabels(fout,
12110 tbinfo->dobj.catId.tableoid,
12111 tbinfo->dobj.catId.oid,
12114 /* If security labels exist, build SECURITY LABEL statements */
12118 query = createPQExpBuffer();
12119 target = createPQExpBuffer();
12121 for (i = 0; i < nlabels; i++)
12123 const char *colname;
12124 const char *provider = labels[i].provider;
12125 const char *label = labels[i].label;
12126 int objsubid = labels[i].objsubid;
12128 resetPQExpBuffer(target);
12131 appendPQExpBuffer(target, "%s %s", reltypename,
12132 fmtId(tbinfo->dobj.name));
12136 colname = getAttrName(objsubid, tbinfo);
12137 /* first fmtId result must be consumed before calling it again */
12138 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12139 appendPQExpBuffer(target, ".%s", fmtId(colname));
12141 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12142 fmtId(provider), target->data);
12143 appendStringLiteralAH(query, label, fout);
12144 appendPQExpBuffer(query, ";\n");
12146 if (query->len > 0)
12148 resetPQExpBuffer(target);
12149 appendPQExpBuffer(target, "%s %s", reltypename,
12150 fmtId(tbinfo->dobj.name));
12151 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12153 tbinfo->dobj.namespace->dobj.name,
12154 NULL, tbinfo->rolname,
12155 false, "SECURITY LABEL", SECTION_NONE,
12156 query->data, "", NULL,
12157 &(tbinfo->dobj.dumpId), 1,
12160 destroyPQExpBuffer(query);
12161 destroyPQExpBuffer(target);
12167 * Find the security label(s), if any, associated with the given object.
12168 * All the objsubid values associated with the given classoid/objoid are
12169 * found with one search.
12172 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12174 /* static storage for table of security labels */
12175 static SecLabelItem *labels = NULL;
12176 static int nlabels = -1;
12178 SecLabelItem *middle = NULL;
12180 SecLabelItem *high;
12183 /* Get security labels if we didn't already */
12185 nlabels = collectSecLabels(fout, &labels);
12187 if (nlabels <= 0) /* no labels, so no match is possible */
12194 * Do binary search to find some item matching the object.
12197 high = &labels[nlabels - 1];
12198 while (low <= high)
12200 middle = low + (high - low) / 2;
12202 if (classoid < middle->classoid)
12204 else if (classoid > middle->classoid)
12206 else if (objoid < middle->objoid)
12208 else if (objoid > middle->objoid)
12211 break; /* found a match */
12214 if (low > high) /* no matches */
12221 * Now determine how many items match the object. The search loop
12222 * invariant still holds: only items between low and high inclusive could
12226 while (middle > low)
12228 if (classoid != middle[-1].classoid ||
12229 objoid != middle[-1].objoid)
12238 while (middle <= high)
12240 if (classoid != middle->classoid ||
12241 objoid != middle->objoid)
12253 * Construct a table of all security labels available for database objects.
12254 * It's much faster to pull them all at once.
12256 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12259 collectSecLabels(Archive *fout, SecLabelItem **items)
12270 SecLabelItem *labels;
12272 query = createPQExpBuffer();
12274 appendPQExpBuffer(query,
12275 "SELECT label, provider, classoid, objoid, objsubid "
12276 "FROM pg_catalog.pg_seclabel "
12277 "ORDER BY classoid, objoid, objsubid");
12279 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12281 /* Construct lookup table containing OIDs in numeric form */
12282 i_label = PQfnumber(res, "label");
12283 i_provider = PQfnumber(res, "provider");
12284 i_classoid = PQfnumber(res, "classoid");
12285 i_objoid = PQfnumber(res, "objoid");
12286 i_objsubid = PQfnumber(res, "objsubid");
12288 ntups = PQntuples(res);
12290 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12292 for (i = 0; i < ntups; i++)
12294 labels[i].label = PQgetvalue(res, i, i_label);
12295 labels[i].provider = PQgetvalue(res, i, i_provider);
12296 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12297 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12298 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12301 /* Do NOT free the PGresult since we are keeping pointers into it */
12302 destroyPQExpBuffer(query);
12310 * write out to fout the declarations (not data) of a user-defined table
12313 dumpTable(Archive *fout, TableInfo *tbinfo)
12315 if (tbinfo->dobj.dump && !dataOnly)
12319 if (tbinfo->relkind == RELKIND_SEQUENCE)
12320 dumpSequence(fout, tbinfo);
12322 dumpTableSchema(fout, tbinfo);
12324 /* Handle the ACL here */
12325 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12326 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12327 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12329 namecopy, NULL, tbinfo->dobj.name,
12330 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12334 * Handle column ACLs, if any. Note: we pull these with a separate
12335 * query rather than trying to fetch them during getTableAttrs, so
12336 * that we won't miss ACLs on system columns.
12338 if (fout->remoteVersion >= 80400)
12340 PQExpBuffer query = createPQExpBuffer();
12344 appendPQExpBuffer(query,
12345 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12346 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12348 tbinfo->dobj.catId.oid);
12349 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12351 for (i = 0; i < PQntuples(res); i++)
12353 char *attname = PQgetvalue(res, i, 0);
12354 char *attacl = PQgetvalue(res, i, 1);
12358 attnamecopy = pg_strdup(fmtId(attname));
12359 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12360 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12361 /* Column's GRANT type is always TABLE */
12362 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12363 namecopy, attnamecopy, acltag,
12364 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12370 destroyPQExpBuffer(query);
12379 * write the declaration (not data) of one user-defined table or view
12382 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12384 PQExpBuffer query = createPQExpBuffer();
12385 PQExpBuffer q = createPQExpBuffer();
12386 PQExpBuffer delq = createPQExpBuffer();
12387 PQExpBuffer labelq = createPQExpBuffer();
12390 TableInfo **parents;
12391 int actual_atts; /* number of attrs in this CREATE statement */
12392 const char *reltypename;
12399 /* Make sure we are in proper schema */
12400 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12402 if (binary_upgrade)
12403 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12404 tbinfo->dobj.catId.oid);
12406 /* Is it a table or a view? */
12407 if (tbinfo->relkind == RELKIND_VIEW)
12411 reltypename = "VIEW";
12413 /* Fetch the view definition */
12414 if (fout->remoteVersion >= 70300)
12416 /* Beginning in 7.3, viewname is not unique; rely on OID */
12417 appendPQExpBuffer(query,
12418 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12419 tbinfo->dobj.catId.oid);
12423 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12424 "FROM pg_views WHERE viewname = ");
12425 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12426 appendPQExpBuffer(query, ";");
12429 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12431 if (PQntuples(res) != 1)
12433 if (PQntuples(res) < 1)
12434 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12435 tbinfo->dobj.name);
12437 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12438 tbinfo->dobj.name);
12441 viewdef = PQgetvalue(res, 0, 0);
12443 if (strlen(viewdef) == 0)
12444 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12445 tbinfo->dobj.name);
12448 * DROP must be fully qualified in case same name appears in
12451 appendPQExpBuffer(delq, "DROP VIEW %s.",
12452 fmtId(tbinfo->dobj.namespace->dobj.name));
12453 appendPQExpBuffer(delq, "%s;\n",
12454 fmtId(tbinfo->dobj.name));
12456 if (binary_upgrade)
12457 binary_upgrade_set_pg_class_oids(fout, q,
12458 tbinfo->dobj.catId.oid, false);
12460 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12461 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12462 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12463 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12465 appendPQExpBuffer(labelq, "VIEW %s",
12466 fmtId(tbinfo->dobj.name));
12472 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12477 reltypename = "FOREIGN TABLE";
12479 /* retrieve name of foreign server and generic options */
12480 appendPQExpBuffer(query,
12481 "SELECT fs.srvname, "
12482 "pg_catalog.array_to_string(ARRAY("
12483 "SELECT pg_catalog.quote_ident(option_name) || "
12484 "' ' || pg_catalog.quote_literal(option_value) "
12485 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12486 "ORDER BY option_name"
12487 "), E',\n ') AS ftoptions "
12488 "FROM pg_catalog.pg_foreign_table ft "
12489 "JOIN pg_catalog.pg_foreign_server fs "
12490 "ON (fs.oid = ft.ftserver) "
12491 "WHERE ft.ftrelid = '%u'",
12492 tbinfo->dobj.catId.oid);
12493 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12494 i_srvname = PQfnumber(res, "srvname");
12495 i_ftoptions = PQfnumber(res, "ftoptions");
12496 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12497 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12502 reltypename = "TABLE";
12506 numParents = tbinfo->numParents;
12507 parents = tbinfo->parents;
12510 * DROP must be fully qualified in case same name appears in
12513 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12514 fmtId(tbinfo->dobj.namespace->dobj.name));
12515 appendPQExpBuffer(delq, "%s;\n",
12516 fmtId(tbinfo->dobj.name));
12518 appendPQExpBuffer(labelq, "%s %s", reltypename,
12519 fmtId(tbinfo->dobj.name));
12521 if (binary_upgrade)
12522 binary_upgrade_set_pg_class_oids(fout, q,
12523 tbinfo->dobj.catId.oid, false);
12525 appendPQExpBuffer(q, "CREATE %s%s %s",
12526 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12529 fmtId(tbinfo->dobj.name));
12532 * Attach to type, if reloftype; except in case of a binary upgrade,
12533 * we dump the table normally and attach it to the type afterward.
12535 if (tbinfo->reloftype && !binary_upgrade)
12536 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12538 /* Dump the attributes */
12540 for (j = 0; j < tbinfo->numatts; j++)
12543 * Normally, dump if it's locally defined in this table, and not
12544 * dropped. But for binary upgrade, we'll dump all the columns,
12545 * and then fix up the dropped and nonlocal cases below.
12547 if (shouldPrintColumn(tbinfo, j))
12550 * Default value --- suppress if to be printed separately.
12552 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12553 !tbinfo->attrdefs[j]->separate);
12556 * Not Null constraint --- suppress if inherited, except in
12557 * binary-upgrade case where that won't work.
12559 bool has_notnull = (tbinfo->notnull[j] &&
12560 (!tbinfo->inhNotNull[j] ||
12563 /* Skip column if fully defined by reloftype */
12564 if (tbinfo->reloftype &&
12565 !has_default && !has_notnull && !binary_upgrade)
12568 /* Format properly if not first attr */
12569 if (actual_atts == 0)
12570 appendPQExpBuffer(q, " (");
12572 appendPQExpBuffer(q, ",");
12573 appendPQExpBuffer(q, "\n ");
12576 /* Attribute name */
12577 appendPQExpBuffer(q, "%s ",
12578 fmtId(tbinfo->attnames[j]));
12580 if (tbinfo->attisdropped[j])
12583 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12584 * so we will not have gotten a valid type name; insert
12585 * INTEGER as a stopgap. We'll clean things up later.
12587 appendPQExpBuffer(q, "INTEGER /* dummy */");
12588 /* Skip all the rest, too */
12592 /* Attribute type */
12593 if (tbinfo->reloftype && !binary_upgrade)
12595 appendPQExpBuffer(q, "WITH OPTIONS");
12597 else if (fout->remoteVersion >= 70100)
12599 appendPQExpBuffer(q, "%s",
12600 tbinfo->atttypnames[j]);
12604 /* If no format_type, fake it */
12605 appendPQExpBuffer(q, "%s",
12606 myFormatType(tbinfo->atttypnames[j],
12607 tbinfo->atttypmod[j]));
12610 /* Add collation if not default for the type */
12611 if (OidIsValid(tbinfo->attcollation[j]))
12615 coll = findCollationByOid(tbinfo->attcollation[j]);
12618 /* always schema-qualify, don't try to be smart */
12619 appendPQExpBuffer(q, " COLLATE %s.",
12620 fmtId(coll->dobj.namespace->dobj.name));
12621 appendPQExpBuffer(q, "%s",
12622 fmtId(coll->dobj.name));
12627 appendPQExpBuffer(q, " DEFAULT %s",
12628 tbinfo->attrdefs[j]->adef_expr);
12631 appendPQExpBuffer(q, " NOT NULL");
12636 * Add non-inherited CHECK constraints, if any.
12638 for (j = 0; j < tbinfo->ncheck; j++)
12640 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12642 if (constr->separate || !constr->conislocal)
12645 if (actual_atts == 0)
12646 appendPQExpBuffer(q, " (\n ");
12648 appendPQExpBuffer(q, ",\n ");
12650 appendPQExpBuffer(q, "CONSTRAINT %s ",
12651 fmtId(constr->dobj.name));
12652 appendPQExpBuffer(q, "%s", constr->condef);
12658 appendPQExpBuffer(q, "\n)");
12659 else if (!(tbinfo->reloftype && !binary_upgrade))
12662 * We must have a parenthesized attribute list, even though empty,
12663 * when not using the OF TYPE syntax.
12665 appendPQExpBuffer(q, " (\n)");
12668 if (numParents > 0 && !binary_upgrade)
12670 appendPQExpBuffer(q, "\nINHERITS (");
12671 for (k = 0; k < numParents; k++)
12673 TableInfo *parentRel = parents[k];
12676 appendPQExpBuffer(q, ", ");
12677 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12678 appendPQExpBuffer(q, "%s.",
12679 fmtId(parentRel->dobj.namespace->dobj.name));
12680 appendPQExpBuffer(q, "%s",
12681 fmtId(parentRel->dobj.name));
12683 appendPQExpBuffer(q, ")");
12686 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12687 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12689 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12690 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12692 bool addcomma = false;
12694 appendPQExpBuffer(q, "\nWITH (");
12695 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12698 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12700 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12702 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12703 tbinfo->toast_reloptions);
12705 appendPQExpBuffer(q, ")");
12708 /* Dump generic options if any */
12709 if (ftoptions && ftoptions[0])
12710 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12712 appendPQExpBuffer(q, ";\n");
12715 * To create binary-compatible heap files, we have to ensure the same
12716 * physical column order, including dropped columns, as in the
12717 * original. Therefore, we create dropped columns above and drop them
12718 * here, also updating their attlen/attalign values so that the
12719 * dropped column can be skipped properly. (We do not bother with
12720 * restoring the original attbyval setting.) Also, inheritance
12721 * relationships are set up by doing ALTER INHERIT rather than using
12722 * an INHERITS clause --- the latter would possibly mess up the column
12723 * order. That also means we have to take care about setting
12724 * attislocal correctly, plus fix up any inherited CHECK constraints.
12725 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12727 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12729 for (j = 0; j < tbinfo->numatts; j++)
12731 if (tbinfo->attisdropped[j])
12733 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12734 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12735 "SET attlen = %d, "
12736 "attalign = '%c', attbyval = false\n"
12737 "WHERE attname = ",
12739 tbinfo->attalign[j]);
12740 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12741 appendPQExpBuffer(q, "\n AND attrelid = ");
12742 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12743 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12745 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12746 fmtId(tbinfo->dobj.name));
12747 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12748 fmtId(tbinfo->attnames[j]));
12750 else if (!tbinfo->attislocal[j])
12752 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12753 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12754 "SET attislocal = false\n"
12755 "WHERE attname = ");
12756 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12757 appendPQExpBuffer(q, "\n AND attrelid = ");
12758 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12759 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12763 for (k = 0; k < tbinfo->ncheck; k++)
12765 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12767 if (constr->separate || constr->conislocal)
12770 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12771 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12772 fmtId(tbinfo->dobj.name));
12773 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12774 fmtId(constr->dobj.name));
12775 appendPQExpBuffer(q, "%s;\n", constr->condef);
12776 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12777 "SET conislocal = false\n"
12778 "WHERE contype = 'c' AND conname = ");
12779 appendStringLiteralAH(q, constr->dobj.name, fout);
12780 appendPQExpBuffer(q, "\n AND conrelid = ");
12781 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12782 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12785 if (numParents > 0)
12787 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12788 for (k = 0; k < numParents; k++)
12790 TableInfo *parentRel = parents[k];
12792 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12793 fmtId(tbinfo->dobj.name));
12794 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12795 appendPQExpBuffer(q, "%s.",
12796 fmtId(parentRel->dobj.namespace->dobj.name));
12797 appendPQExpBuffer(q, "%s;\n",
12798 fmtId(parentRel->dobj.name));
12802 if (tbinfo->reloftype)
12804 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12805 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12806 fmtId(tbinfo->dobj.name),
12807 tbinfo->reloftype);
12810 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12811 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12812 "SET relfrozenxid = '%u'\n"
12814 tbinfo->frozenxid);
12815 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12816 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12818 if (tbinfo->toast_oid)
12820 /* We preserve the toast oids, so we can use it during restore */
12821 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12822 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12823 "SET relfrozenxid = '%u'\n"
12824 "WHERE oid = '%u';\n",
12825 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12830 * Dump additional per-column properties that we can't handle in the
12831 * main CREATE TABLE command.
12833 for (j = 0; j < tbinfo->numatts; j++)
12835 /* None of this applies to dropped columns */
12836 if (tbinfo->attisdropped[j])
12840 * If we didn't dump the column definition explicitly above, and
12841 * it is NOT NULL and did not inherit that property from a parent,
12842 * we have to mark it separately.
12844 if (!shouldPrintColumn(tbinfo, j) &&
12845 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12847 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12848 fmtId(tbinfo->dobj.name));
12849 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12850 fmtId(tbinfo->attnames[j]));
12854 * Dump per-column statistics information. We only issue an ALTER
12855 * TABLE statement if the attstattarget entry for this column is
12856 * non-negative (i.e. it's not the default value)
12858 if (tbinfo->attstattarget[j] >= 0)
12860 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12861 fmtId(tbinfo->dobj.name));
12862 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12863 fmtId(tbinfo->attnames[j]));
12864 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12865 tbinfo->attstattarget[j]);
12869 * Dump per-column storage information. The statement is only
12870 * dumped if the storage has been changed from the type's default.
12872 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12874 switch (tbinfo->attstorage[j])
12880 storage = "EXTERNAL";
12886 storage = "EXTENDED";
12893 * Only dump the statement if it's a storage type we recognize
12895 if (storage != NULL)
12897 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12898 fmtId(tbinfo->dobj.name));
12899 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12900 fmtId(tbinfo->attnames[j]));
12901 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12907 * Dump per-column attributes.
12909 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12911 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12912 fmtId(tbinfo->dobj.name));
12913 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12914 fmtId(tbinfo->attnames[j]));
12915 appendPQExpBuffer(q, "SET (%s);\n",
12916 tbinfo->attoptions[j]);
12920 * Dump per-column fdw options.
12922 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12923 tbinfo->attfdwoptions[j] &&
12924 tbinfo->attfdwoptions[j][0] != '\0')
12926 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12927 fmtId(tbinfo->dobj.name));
12928 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12929 fmtId(tbinfo->attnames[j]));
12930 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12931 tbinfo->attfdwoptions[j]);
12936 if (binary_upgrade)
12937 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12939 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12941 tbinfo->dobj.namespace->dobj.name,
12942 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12944 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12945 reltypename, SECTION_PRE_DATA,
12946 q->data, delq->data, NULL,
12951 /* Dump Table Comments */
12952 dumpTableComment(fout, tbinfo, reltypename);
12954 /* Dump Table Security Labels */
12955 dumpTableSecLabel(fout, tbinfo, reltypename);
12957 /* Dump comments on inlined table constraints */
12958 for (j = 0; j < tbinfo->ncheck; j++)
12960 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12962 if (constr->separate || !constr->conislocal)
12965 dumpTableConstraintComment(fout, constr);
12968 destroyPQExpBuffer(query);
12969 destroyPQExpBuffer(q);
12970 destroyPQExpBuffer(delq);
12971 destroyPQExpBuffer(labelq);
12975 * dumpAttrDef --- dump an attribute's default-value declaration
12978 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12980 TableInfo *tbinfo = adinfo->adtable;
12981 int adnum = adinfo->adnum;
12985 /* Skip if table definition not to be dumped */
12986 if (!tbinfo->dobj.dump || dataOnly)
12989 /* Skip if not "separate"; it was dumped in the table's definition */
12990 if (!adinfo->separate)
12993 q = createPQExpBuffer();
12994 delq = createPQExpBuffer();
12996 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12997 fmtId(tbinfo->dobj.name));
12998 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12999 fmtId(tbinfo->attnames[adnum - 1]),
13000 adinfo->adef_expr);
13003 * DROP must be fully qualified in case same name appears in pg_catalog
13005 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13006 fmtId(tbinfo->dobj.namespace->dobj.name));
13007 appendPQExpBuffer(delq, "%s ",
13008 fmtId(tbinfo->dobj.name));
13009 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13010 fmtId(tbinfo->attnames[adnum - 1]));
13012 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13013 tbinfo->attnames[adnum - 1],
13014 tbinfo->dobj.namespace->dobj.name,
13017 false, "DEFAULT", SECTION_PRE_DATA,
13018 q->data, delq->data, NULL,
13022 destroyPQExpBuffer(q);
13023 destroyPQExpBuffer(delq);
13027 * getAttrName: extract the correct name for an attribute
13029 * The array tblInfo->attnames[] only provides names of user attributes;
13030 * if a system attribute number is supplied, we have to fake it.
13031 * We also do a little bit of bounds checking for safety's sake.
13033 static const char *
13034 getAttrName(int attrnum, TableInfo *tblInfo)
13036 if (attrnum > 0 && attrnum <= tblInfo->numatts)
13037 return tblInfo->attnames[attrnum - 1];
13040 case SelfItemPointerAttributeNumber:
13042 case ObjectIdAttributeNumber:
13044 case MinTransactionIdAttributeNumber:
13046 case MinCommandIdAttributeNumber:
13048 case MaxTransactionIdAttributeNumber:
13050 case MaxCommandIdAttributeNumber:
13052 case TableOidAttributeNumber:
13055 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13056 attrnum, tblInfo->dobj.name);
13057 return NULL; /* keep compiler quiet */
13062 * write out to fout a user-defined index
13065 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13067 TableInfo *tbinfo = indxinfo->indextable;
13070 PQExpBuffer labelq;
13075 q = createPQExpBuffer();
13076 delq = createPQExpBuffer();
13077 labelq = createPQExpBuffer();
13079 appendPQExpBuffer(labelq, "INDEX %s",
13080 fmtId(indxinfo->dobj.name));
13083 * If there's an associated constraint, don't dump the index per se, but
13084 * do dump any comment for it. (This is safe because dependency ordering
13085 * will have ensured the constraint is emitted first.)
13087 if (indxinfo->indexconstraint == 0)
13089 if (binary_upgrade)
13090 binary_upgrade_set_pg_class_oids(fout, q,
13091 indxinfo->dobj.catId.oid, true);
13093 /* Plain secondary index */
13094 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13096 /* If the index is clustered, we need to record that. */
13097 if (indxinfo->indisclustered)
13099 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13100 fmtId(tbinfo->dobj.name));
13101 appendPQExpBuffer(q, " ON %s;\n",
13102 fmtId(indxinfo->dobj.name));
13106 * DROP must be fully qualified in case same name appears in
13109 appendPQExpBuffer(delq, "DROP INDEX %s.",
13110 fmtId(tbinfo->dobj.namespace->dobj.name));
13111 appendPQExpBuffer(delq, "%s;\n",
13112 fmtId(indxinfo->dobj.name));
13114 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13115 indxinfo->dobj.name,
13116 tbinfo->dobj.namespace->dobj.name,
13117 indxinfo->tablespace,
13118 tbinfo->rolname, false,
13119 "INDEX", SECTION_POST_DATA,
13120 q->data, delq->data, NULL,
13125 /* Dump Index Comments */
13126 dumpComment(fout, labelq->data,
13127 tbinfo->dobj.namespace->dobj.name,
13129 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13131 destroyPQExpBuffer(q);
13132 destroyPQExpBuffer(delq);
13133 destroyPQExpBuffer(labelq);
13138 * write out to fout a user-defined constraint
13141 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13143 TableInfo *tbinfo = coninfo->contable;
13147 /* Skip if not to be dumped */
13148 if (!coninfo->dobj.dump || dataOnly)
13151 q = createPQExpBuffer();
13152 delq = createPQExpBuffer();
13154 if (coninfo->contype == 'p' ||
13155 coninfo->contype == 'u' ||
13156 coninfo->contype == 'x')
13158 /* Index-related constraint */
13159 IndxInfo *indxinfo;
13162 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13164 if (indxinfo == NULL)
13165 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13166 coninfo->dobj.name);
13168 if (binary_upgrade)
13169 binary_upgrade_set_pg_class_oids(fout, q,
13170 indxinfo->dobj.catId.oid, true);
13172 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13173 fmtId(tbinfo->dobj.name));
13174 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13175 fmtId(coninfo->dobj.name));
13177 if (coninfo->condef)
13179 /* pg_get_constraintdef should have provided everything */
13180 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13184 appendPQExpBuffer(q, "%s (",
13185 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13186 for (k = 0; k < indxinfo->indnkeys; k++)
13188 int indkey = (int) indxinfo->indkeys[k];
13189 const char *attname;
13191 if (indkey == InvalidAttrNumber)
13193 attname = getAttrName(indkey, tbinfo);
13195 appendPQExpBuffer(q, "%s%s",
13196 (k == 0) ? "" : ", ",
13200 appendPQExpBuffer(q, ")");
13202 if (indxinfo->options && strlen(indxinfo->options) > 0)
13203 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13205 if (coninfo->condeferrable)
13207 appendPQExpBuffer(q, " DEFERRABLE");
13208 if (coninfo->condeferred)
13209 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13212 appendPQExpBuffer(q, ";\n");
13215 /* If the index is clustered, we need to record that. */
13216 if (indxinfo->indisclustered)
13218 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13219 fmtId(tbinfo->dobj.name));
13220 appendPQExpBuffer(q, " ON %s;\n",
13221 fmtId(indxinfo->dobj.name));
13225 * DROP must be fully qualified in case same name appears in
13228 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13229 fmtId(tbinfo->dobj.namespace->dobj.name));
13230 appendPQExpBuffer(delq, "%s ",
13231 fmtId(tbinfo->dobj.name));
13232 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13233 fmtId(coninfo->dobj.name));
13235 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13236 coninfo->dobj.name,
13237 tbinfo->dobj.namespace->dobj.name,
13238 indxinfo->tablespace,
13239 tbinfo->rolname, false,
13240 "CONSTRAINT", SECTION_POST_DATA,
13241 q->data, delq->data, NULL,
13245 else if (coninfo->contype == 'f')
13248 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13249 * current table data is not processed
13251 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13252 fmtId(tbinfo->dobj.name));
13253 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13254 fmtId(coninfo->dobj.name),
13258 * DROP must be fully qualified in case same name appears in
13261 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13262 fmtId(tbinfo->dobj.namespace->dobj.name));
13263 appendPQExpBuffer(delq, "%s ",
13264 fmtId(tbinfo->dobj.name));
13265 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13266 fmtId(coninfo->dobj.name));
13268 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13269 coninfo->dobj.name,
13270 tbinfo->dobj.namespace->dobj.name,
13272 tbinfo->rolname, false,
13273 "FK CONSTRAINT", SECTION_POST_DATA,
13274 q->data, delq->data, NULL,
13278 else if (coninfo->contype == 'c' && tbinfo)
13280 /* CHECK constraint on a table */
13282 /* Ignore if not to be dumped separately */
13283 if (coninfo->separate)
13285 /* not ONLY since we want it to propagate to children */
13286 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13287 fmtId(tbinfo->dobj.name));
13288 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13289 fmtId(coninfo->dobj.name),
13293 * DROP must be fully qualified in case same name appears in
13296 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13297 fmtId(tbinfo->dobj.namespace->dobj.name));
13298 appendPQExpBuffer(delq, "%s ",
13299 fmtId(tbinfo->dobj.name));
13300 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13301 fmtId(coninfo->dobj.name));
13303 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13304 coninfo->dobj.name,
13305 tbinfo->dobj.namespace->dobj.name,
13307 tbinfo->rolname, false,
13308 "CHECK CONSTRAINT", SECTION_POST_DATA,
13309 q->data, delq->data, NULL,
13314 else if (coninfo->contype == 'c' && tbinfo == NULL)
13316 /* CHECK constraint on a domain */
13317 TypeInfo *tyinfo = coninfo->condomain;
13319 /* Ignore if not to be dumped separately */
13320 if (coninfo->separate)
13322 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13323 fmtId(tyinfo->dobj.name));
13324 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13325 fmtId(coninfo->dobj.name),
13329 * DROP must be fully qualified in case same name appears in
13332 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13333 fmtId(tyinfo->dobj.namespace->dobj.name));
13334 appendPQExpBuffer(delq, "%s ",
13335 fmtId(tyinfo->dobj.name));
13336 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13337 fmtId(coninfo->dobj.name));
13339 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13340 coninfo->dobj.name,
13341 tyinfo->dobj.namespace->dobj.name,
13343 tyinfo->rolname, false,
13344 "CHECK CONSTRAINT", SECTION_POST_DATA,
13345 q->data, delq->data, NULL,
13352 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13356 /* Dump Constraint Comments --- only works for table constraints */
13357 if (tbinfo && coninfo->separate)
13358 dumpTableConstraintComment(fout, coninfo);
13360 destroyPQExpBuffer(q);
13361 destroyPQExpBuffer(delq);
13365 * dumpTableConstraintComment --- dump a constraint's comment if any
13367 * This is split out because we need the function in two different places
13368 * depending on whether the constraint is dumped as part of CREATE TABLE
13369 * or as a separate ALTER command.
13372 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13374 TableInfo *tbinfo = coninfo->contable;
13375 PQExpBuffer labelq = createPQExpBuffer();
13377 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13378 fmtId(coninfo->dobj.name));
13379 appendPQExpBuffer(labelq, "ON %s",
13380 fmtId(tbinfo->dobj.name));
13381 dumpComment(fout, labelq->data,
13382 tbinfo->dobj.namespace->dobj.name,
13384 coninfo->dobj.catId, 0,
13385 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13387 destroyPQExpBuffer(labelq);
13391 * findLastBuiltInOid -
13392 * find the last built in oid
13394 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13395 * pg_database entry for the current database
13398 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13402 PQExpBuffer query = createPQExpBuffer();
13404 resetPQExpBuffer(query);
13405 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13406 appendStringLiteralAH(query, dbname, fout);
13408 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13409 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13411 destroyPQExpBuffer(query);
13416 * findLastBuiltInOid -
13417 * find the last built in oid
13419 * For 7.0, we do this by assuming that the last thing that initdb does is to
13420 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13421 * initdb won't be changing anymore, it'll do.
13424 findLastBuiltinOid_V70(Archive *fout)
13429 res = ExecuteSqlQueryForSingleRow(fout,
13430 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13431 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13438 * write the declaration (not data) of one user-defined sequence
13441 dumpSequence(Archive *fout, TableInfo *tbinfo)
13452 PQExpBuffer query = createPQExpBuffer();
13453 PQExpBuffer delqry = createPQExpBuffer();
13454 PQExpBuffer labelq = createPQExpBuffer();
13456 /* Make sure we are in proper schema */
13457 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13459 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13460 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13462 if (fout->remoteVersion >= 80400)
13464 appendPQExpBuffer(query,
13465 "SELECT sequence_name, "
13466 "start_value, increment_by, "
13467 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13468 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13470 "END AS max_value, "
13471 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13472 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13474 "END AS min_value, "
13475 "cache_value, is_cycled FROM %s",
13477 fmtId(tbinfo->dobj.name));
13481 appendPQExpBuffer(query,
13482 "SELECT sequence_name, "
13483 "0 AS start_value, increment_by, "
13484 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13485 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13487 "END AS max_value, "
13488 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13489 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13491 "END AS min_value, "
13492 "cache_value, is_cycled FROM %s",
13494 fmtId(tbinfo->dobj.name));
13497 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13499 if (PQntuples(res) != 1)
13501 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13502 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13504 tbinfo->dobj.name, PQntuples(res));
13508 /* Disable this check: it fails if sequence has been renamed */
13510 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13512 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13513 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13518 startv = PQgetvalue(res, 0, 1);
13519 incby = PQgetvalue(res, 0, 2);
13520 if (!PQgetisnull(res, 0, 3))
13521 maxv = PQgetvalue(res, 0, 3);
13522 if (!PQgetisnull(res, 0, 4))
13523 minv = PQgetvalue(res, 0, 4);
13524 cache = PQgetvalue(res, 0, 5);
13525 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13528 * DROP must be fully qualified in case same name appears in pg_catalog
13530 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13531 fmtId(tbinfo->dobj.namespace->dobj.name));
13532 appendPQExpBuffer(delqry, "%s;\n",
13533 fmtId(tbinfo->dobj.name));
13535 resetPQExpBuffer(query);
13537 if (binary_upgrade)
13539 binary_upgrade_set_pg_class_oids(fout, query,
13540 tbinfo->dobj.catId.oid, false);
13541 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13542 tbinfo->dobj.catId.oid);
13545 appendPQExpBuffer(query,
13546 "CREATE SEQUENCE %s\n",
13547 fmtId(tbinfo->dobj.name));
13549 if (fout->remoteVersion >= 80400)
13550 appendPQExpBuffer(query, " START WITH %s\n", startv);
13552 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13555 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13557 appendPQExpBuffer(query, " NO MINVALUE\n");
13560 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13562 appendPQExpBuffer(query, " NO MAXVALUE\n");
13564 appendPQExpBuffer(query,
13566 cache, (cycled ? "\n CYCLE" : ""));
13568 appendPQExpBuffer(query, ";\n");
13570 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13572 /* binary_upgrade: no need to clear TOAST table oid */
13574 if (binary_upgrade)
13575 binary_upgrade_extension_member(query, &tbinfo->dobj,
13578 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13580 tbinfo->dobj.namespace->dobj.name,
13583 false, "SEQUENCE", SECTION_PRE_DATA,
13584 query->data, delqry->data, NULL,
13589 * If the sequence is owned by a table column, emit the ALTER for it as a
13590 * separate TOC entry immediately following the sequence's own entry.
13591 * It's OK to do this rather than using full sorting logic, because the
13592 * dependency that tells us it's owned will have forced the table to be
13593 * created first. We can't just include the ALTER in the TOC entry
13594 * because it will fail if we haven't reassigned the sequence owner to
13595 * match the table's owner.
13597 * We need not schema-qualify the table reference because both sequence
13598 * and table must be in the same schema.
13600 if (OidIsValid(tbinfo->owning_tab))
13602 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13604 if (owning_tab && owning_tab->dobj.dump)
13606 resetPQExpBuffer(query);
13607 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13608 fmtId(tbinfo->dobj.name));
13609 appendPQExpBuffer(query, " OWNED BY %s",
13610 fmtId(owning_tab->dobj.name));
13611 appendPQExpBuffer(query, ".%s;\n",
13612 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13614 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13616 tbinfo->dobj.namespace->dobj.name,
13619 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13620 query->data, "", NULL,
13621 &(tbinfo->dobj.dumpId), 1,
13626 /* Dump Sequence Comments and Security Labels */
13627 dumpComment(fout, labelq->data,
13628 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13629 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13630 dumpSecLabel(fout, labelq->data,
13631 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13632 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13636 destroyPQExpBuffer(query);
13637 destroyPQExpBuffer(delqry);
13638 destroyPQExpBuffer(labelq);
13643 * write the data of one user-defined sequence
13646 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
13648 TableInfo *tbinfo = tdinfo->tdtable;
13652 PQExpBuffer query = createPQExpBuffer();
13654 /* Make sure we are in proper schema */
13655 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13657 appendPQExpBuffer(query,
13658 "SELECT last_value, is_called FROM %s",
13659 fmtId(tbinfo->dobj.name));
13661 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13663 if (PQntuples(res) != 1)
13665 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13666 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13668 tbinfo->dobj.name, PQntuples(res));
13672 last = PQgetvalue(res, 0, 0);
13673 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
13675 resetPQExpBuffer(query);
13676 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13677 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13678 appendPQExpBuffer(query, ", %s, %s);\n",
13679 last, (called ? "true" : "false"));
13681 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13683 tbinfo->dobj.namespace->dobj.name,
13686 false, "SEQUENCE SET", SECTION_DATA,
13687 query->data, "", NULL,
13688 &(tbinfo->dobj.dumpId), 1,
13693 destroyPQExpBuffer(query);
13697 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13699 TableInfo *tbinfo = tginfo->tgtable;
13701 PQExpBuffer delqry;
13702 PQExpBuffer labelq;
13711 query = createPQExpBuffer();
13712 delqry = createPQExpBuffer();
13713 labelq = createPQExpBuffer();
13716 * DROP must be fully qualified in case same name appears in pg_catalog
13718 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13719 fmtId(tginfo->dobj.name));
13720 appendPQExpBuffer(delqry, "ON %s.",
13721 fmtId(tbinfo->dobj.namespace->dobj.name));
13722 appendPQExpBuffer(delqry, "%s;\n",
13723 fmtId(tbinfo->dobj.name));
13727 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13731 if (tginfo->tgisconstraint)
13733 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13734 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13738 appendPQExpBuffer(query, "CREATE TRIGGER ");
13739 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13741 appendPQExpBuffer(query, "\n ");
13744 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13745 appendPQExpBuffer(query, "BEFORE");
13746 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13747 appendPQExpBuffer(query, "AFTER");
13748 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13749 appendPQExpBuffer(query, "INSTEAD OF");
13752 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13757 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13759 appendPQExpBuffer(query, " INSERT");
13762 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13765 appendPQExpBuffer(query, " OR DELETE");
13767 appendPQExpBuffer(query, " DELETE");
13770 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13773 appendPQExpBuffer(query, " OR UPDATE");
13775 appendPQExpBuffer(query, " UPDATE");
13778 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13781 appendPQExpBuffer(query, " OR TRUNCATE");
13783 appendPQExpBuffer(query, " TRUNCATE");
13786 appendPQExpBuffer(query, " ON %s\n",
13787 fmtId(tbinfo->dobj.name));
13789 if (tginfo->tgisconstraint)
13791 if (OidIsValid(tginfo->tgconstrrelid))
13793 /* If we are using regclass, name is already quoted */
13794 if (fout->remoteVersion >= 70300)
13795 appendPQExpBuffer(query, " FROM %s\n ",
13796 tginfo->tgconstrrelname);
13798 appendPQExpBuffer(query, " FROM %s\n ",
13799 fmtId(tginfo->tgconstrrelname));
13801 if (!tginfo->tgdeferrable)
13802 appendPQExpBuffer(query, "NOT ");
13803 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13804 if (tginfo->tginitdeferred)
13805 appendPQExpBuffer(query, "DEFERRED\n");
13807 appendPQExpBuffer(query, "IMMEDIATE\n");
13810 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13811 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13813 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13815 /* In 7.3, result of regproc is already quoted */
13816 if (fout->remoteVersion >= 70300)
13817 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13820 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13821 fmtId(tginfo->tgfname));
13823 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13826 for (findx = 0; findx < tginfo->tgnargs; findx++)
13828 /* find the embedded null that terminates this trigger argument */
13829 size_t tlen = strlen(p);
13831 if (p + tlen >= tgargs + lentgargs)
13833 /* hm, not found before end of bytea value... */
13834 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13837 tbinfo->dobj.name);
13842 appendPQExpBuffer(query, ", ");
13843 appendStringLiteralAH(query, p, fout);
13847 appendPQExpBuffer(query, ");\n");
13850 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13852 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13853 fmtId(tbinfo->dobj.name));
13854 switch (tginfo->tgenabled)
13858 appendPQExpBuffer(query, "DISABLE");
13861 appendPQExpBuffer(query, "ENABLE ALWAYS");
13864 appendPQExpBuffer(query, "ENABLE REPLICA");
13867 appendPQExpBuffer(query, "ENABLE");
13870 appendPQExpBuffer(query, " TRIGGER %s;\n",
13871 fmtId(tginfo->dobj.name));
13874 appendPQExpBuffer(labelq, "TRIGGER %s ",
13875 fmtId(tginfo->dobj.name));
13876 appendPQExpBuffer(labelq, "ON %s",
13877 fmtId(tbinfo->dobj.name));
13879 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13881 tbinfo->dobj.namespace->dobj.name,
13883 tbinfo->rolname, false,
13884 "TRIGGER", SECTION_POST_DATA,
13885 query->data, delqry->data, NULL,
13889 dumpComment(fout, labelq->data,
13890 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13891 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13893 destroyPQExpBuffer(query);
13894 destroyPQExpBuffer(delqry);
13895 destroyPQExpBuffer(labelq);
13899 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
13902 PQExpBuffer labelq;
13904 query = createPQExpBuffer();
13905 labelq = createPQExpBuffer();
13907 appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
13908 appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
13909 appendPQExpBuffer(query, " ON ");
13910 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
13911 appendPQExpBufferStr(query, " ");
13913 if (strcmp("", evtinfo->evttags) != 0)
13915 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
13916 appendPQExpBufferStr(query, evtinfo->evttags);
13917 appendPQExpBufferStr(query, ") ");
13920 appendPQExpBuffer(query, "\n EXECUTE PROCEDURE ");
13921 appendPQExpBufferStr(query, evtinfo->evtfname);
13922 appendPQExpBuffer(query, "();\n");
13924 if (evtinfo->evtenabled != 'O')
13926 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
13927 fmtId(evtinfo->dobj.name));
13928 switch (evtinfo->evtenabled)
13931 appendPQExpBuffer(query, "DISABLE");
13934 appendPQExpBuffer(query, "ENABLE ALWAYS");
13937 appendPQExpBuffer(query, "ENABLE REPLICA");
13940 appendPQExpBuffer(query, "ENABLE");
13943 appendPQExpBuffer(query, ";\n");
13945 appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
13946 fmtId(evtinfo->dobj.name));
13948 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
13949 evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
13950 "EVENT TRIGGER", SECTION_POST_DATA,
13951 query->data, "", NULL, NULL, 0, NULL, NULL);
13953 dumpComment(fout, labelq->data,
13955 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
13957 destroyPQExpBuffer(query);
13958 destroyPQExpBuffer(labelq);
13966 dumpRule(Archive *fout, RuleInfo *rinfo)
13968 TableInfo *tbinfo = rinfo->ruletable;
13971 PQExpBuffer delcmd;
13972 PQExpBuffer labelq;
13975 /* Skip if not to be dumped */
13976 if (!rinfo->dobj.dump || dataOnly)
13980 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13981 * we do not want to dump it as a separate object.
13983 if (!rinfo->separate)
13987 * Make sure we are in proper schema.
13989 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13991 query = createPQExpBuffer();
13992 cmd = createPQExpBuffer();
13993 delcmd = createPQExpBuffer();
13994 labelq = createPQExpBuffer();
13996 if (fout->remoteVersion >= 70300)
13998 appendPQExpBuffer(query,
13999 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14000 rinfo->dobj.catId.oid);
14004 /* Rule name was unique before 7.3 ... */
14005 appendPQExpBuffer(query,
14006 "SELECT pg_get_ruledef('%s') AS definition",
14010 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14012 if (PQntuples(res) != 1)
14014 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14015 rinfo->dobj.name, tbinfo->dobj.name);
14019 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14022 * Add the command to alter the rules replication firing semantics if it
14023 * differs from the default.
14025 if (rinfo->ev_enabled != 'O')
14027 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14028 switch (rinfo->ev_enabled)
14031 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14032 fmtId(rinfo->dobj.name));
14035 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14036 fmtId(rinfo->dobj.name));
14039 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14040 fmtId(rinfo->dobj.name));
14046 * Apply view's reloptions when its ON SELECT rule is separate.
14048 if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14050 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14051 fmtId(tbinfo->dobj.name),
14052 rinfo->reloptions);
14056 * DROP must be fully qualified in case same name appears in pg_catalog
14058 appendPQExpBuffer(delcmd, "DROP RULE %s ",
14059 fmtId(rinfo->dobj.name));
14060 appendPQExpBuffer(delcmd, "ON %s.",
14061 fmtId(tbinfo->dobj.namespace->dobj.name));
14062 appendPQExpBuffer(delcmd, "%s;\n",
14063 fmtId(tbinfo->dobj.name));
14065 appendPQExpBuffer(labelq, "RULE %s",
14066 fmtId(rinfo->dobj.name));
14067 appendPQExpBuffer(labelq, " ON %s",
14068 fmtId(tbinfo->dobj.name));
14070 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14072 tbinfo->dobj.namespace->dobj.name,
14074 tbinfo->rolname, false,
14075 "RULE", SECTION_POST_DATA,
14076 cmd->data, delcmd->data, NULL,
14080 /* Dump rule comments */
14081 dumpComment(fout, labelq->data,
14082 tbinfo->dobj.namespace->dobj.name,
14084 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14088 destroyPQExpBuffer(query);
14089 destroyPQExpBuffer(cmd);
14090 destroyPQExpBuffer(delcmd);
14091 destroyPQExpBuffer(labelq);
14095 * getExtensionMembership --- obtain extension membership data
14098 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14109 DumpableObject *dobj,
14112 /* Nothing to do if no extensions */
14113 if (numExtensions == 0)
14116 /* Make sure we are in proper schema */
14117 selectSourceSchema(fout, "pg_catalog");
14119 query = createPQExpBuffer();
14121 /* refclassid constraint is redundant but may speed the search */
14122 appendPQExpBuffer(query, "SELECT "
14123 "classid, objid, refclassid, refobjid "
14125 "WHERE refclassid = 'pg_extension'::regclass "
14126 "AND deptype = 'e' "
14129 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14131 ntups = PQntuples(res);
14133 i_classid = PQfnumber(res, "classid");
14134 i_objid = PQfnumber(res, "objid");
14135 i_refclassid = PQfnumber(res, "refclassid");
14136 i_refobjid = PQfnumber(res, "refobjid");
14139 * Since we ordered the SELECT by referenced ID, we can expect that
14140 * multiple entries for the same extension will appear together; this
14141 * saves on searches.
14145 for (i = 0; i < ntups; i++)
14148 CatalogId refobjId;
14150 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14151 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14152 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14153 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14155 if (refdobj == NULL ||
14156 refdobj->catId.tableoid != refobjId.tableoid ||
14157 refdobj->catId.oid != refobjId.oid)
14158 refdobj = findObjectByCatalogId(refobjId);
14161 * Failure to find objects mentioned in pg_depend is not unexpected,
14162 * since for example we don't collect info about TOAST tables.
14164 if (refdobj == NULL)
14167 fprintf(stderr, "no referenced object %u %u\n",
14168 refobjId.tableoid, refobjId.oid);
14173 dobj = findObjectByCatalogId(objId);
14178 fprintf(stderr, "no referencing object %u %u\n",
14179 objId.tableoid, objId.oid);
14184 /* Record dependency so that getDependencies needn't repeat this */
14185 addObjectDependency(dobj, refdobj->dumpId);
14187 dobj->ext_member = true;
14190 * Normally, mark the member object as not to be dumped. But in
14191 * binary upgrades, we still dump the members individually, since the
14192 * idea is to exactly reproduce the database contents rather than
14193 * replace the extension contents with something different.
14195 if (!binary_upgrade)
14196 dobj->dump = false;
14198 dobj->dump = refdobj->dump;
14204 * Now identify extension configuration tables and create TableDataInfo
14205 * objects for them, ensuring their data will be dumped even though the
14206 * tables themselves won't be.
14208 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14209 * user data in a configuration table is treated like schema data. This
14210 * seems appropriate since system data in a config table would get
14211 * reloaded by CREATE EXTENSION.
14213 for (i = 0; i < numExtensions; i++)
14215 ExtensionInfo *curext = &(extinfo[i]);
14216 char *extconfig = curext->extconfig;
14217 char *extcondition = curext->extcondition;
14218 char **extconfigarray = NULL;
14219 char **extconditionarray = NULL;
14221 int nconditionitems;
14223 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14224 if (!curext->dobj.dump)
14227 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14228 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14229 nconfigitems == nconditionitems)
14233 for (j = 0; j < nconfigitems; j++)
14235 TableInfo *configtbl;
14237 configtbl = findTableByOid(atooid(extconfigarray[j]));
14238 if (configtbl == NULL)
14242 * Note: config tables are dumped without OIDs regardless of
14243 * the --oids setting. This is because row filtering
14244 * conditions aren't compatible with dumping OIDs.
14246 makeTableDataInfo(configtbl, false);
14247 if (configtbl->dataObj != NULL)
14249 if (strlen(extconditionarray[j]) > 0)
14250 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14254 if (extconfigarray)
14255 free(extconfigarray);
14256 if (extconditionarray)
14257 free(extconditionarray);
14260 destroyPQExpBuffer(query);
14264 * getDependencies --- obtain available dependency data
14267 getDependencies(Archive *fout)
14278 DumpableObject *dobj,
14281 /* No dependency info available before 7.3 */
14282 if (fout->remoteVersion < 70300)
14286 write_msg(NULL, "reading dependency data\n");
14288 /* Make sure we are in proper schema */
14289 selectSourceSchema(fout, "pg_catalog");
14291 query = createPQExpBuffer();
14294 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14295 * already processed by getExtensionMembership.
14297 appendPQExpBuffer(query, "SELECT "
14298 "classid, objid, refclassid, refobjid, deptype "
14300 "WHERE deptype != 'p' AND deptype != 'e' "
14303 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14305 ntups = PQntuples(res);
14307 i_classid = PQfnumber(res, "classid");
14308 i_objid = PQfnumber(res, "objid");
14309 i_refclassid = PQfnumber(res, "refclassid");
14310 i_refobjid = PQfnumber(res, "refobjid");
14311 i_deptype = PQfnumber(res, "deptype");
14314 * Since we ordered the SELECT by referencing ID, we can expect that
14315 * multiple entries for the same object will appear together; this saves
14320 for (i = 0; i < ntups; i++)
14323 CatalogId refobjId;
14326 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14327 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14328 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14329 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14330 deptype = *(PQgetvalue(res, i, i_deptype));
14332 if (dobj == NULL ||
14333 dobj->catId.tableoid != objId.tableoid ||
14334 dobj->catId.oid != objId.oid)
14335 dobj = findObjectByCatalogId(objId);
14338 * Failure to find objects mentioned in pg_depend is not unexpected,
14339 * since for example we don't collect info about TOAST tables.
14344 fprintf(stderr, "no referencing object %u %u\n",
14345 objId.tableoid, objId.oid);
14350 refdobj = findObjectByCatalogId(refobjId);
14352 if (refdobj == NULL)
14355 fprintf(stderr, "no referenced object %u %u\n",
14356 refobjId.tableoid, refobjId.oid);
14362 * Ordinarily, table rowtypes have implicit dependencies on their
14363 * tables. However, for a composite type the implicit dependency goes
14364 * the other way in pg_depend; which is the right thing for DROP but
14365 * it doesn't produce the dependency ordering we need. So in that one
14366 * case, we reverse the direction of the dependency.
14368 if (deptype == 'i' &&
14369 dobj->objType == DO_TABLE &&
14370 refdobj->objType == DO_TYPE)
14371 addObjectDependency(refdobj, dobj->dumpId);
14374 addObjectDependency(dobj, refdobj->dumpId);
14379 destroyPQExpBuffer(query);
14384 * createBoundaryObjects - create dummy DumpableObjects to represent
14385 * dump section boundaries.
14387 static DumpableObject *
14388 createBoundaryObjects(void)
14390 DumpableObject *dobjs;
14392 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14394 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14395 dobjs[0].catId = nilCatalogId;
14396 AssignDumpId(dobjs + 0);
14397 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14399 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14400 dobjs[1].catId = nilCatalogId;
14401 AssignDumpId(dobjs + 1);
14402 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14408 * addBoundaryDependencies - add dependencies as needed to enforce the dump
14409 * section boundaries.
14412 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14413 DumpableObject *boundaryObjs)
14415 DumpableObject *preDataBound = boundaryObjs + 0;
14416 DumpableObject *postDataBound = boundaryObjs + 1;
14419 for (i = 0; i < numObjs; i++)
14421 DumpableObject *dobj = dobjs[i];
14424 * The classification of object types here must match the SECTION_xxx
14425 * values assigned during subsequent ArchiveEntry calls!
14427 switch (dobj->objType)
14432 case DO_SHELL_TYPE:
14439 case DO_CONVERSION:
14444 case DO_DUMMY_TYPE:
14447 case DO_TSTEMPLATE:
14450 case DO_FOREIGN_SERVER:
14452 /* Pre-data objects: must come before the pre-data boundary */
14453 addObjectDependency(preDataBound, dobj->dumpId);
14455 case DO_TABLE_DATA:
14457 /* Data objects: must come between the boundaries */
14458 addObjectDependency(dobj, preDataBound->dumpId);
14459 addObjectDependency(postDataBound, dobj->dumpId);
14463 case DO_EVENT_TRIGGER:
14464 case DO_DEFAULT_ACL:
14465 /* Post-data objects: must come after the post-data boundary */
14466 addObjectDependency(dobj, postDataBound->dumpId);
14469 /* Rules are post-data, but only if dumped separately */
14470 if (((RuleInfo *) dobj)->separate)
14471 addObjectDependency(dobj, postDataBound->dumpId);
14473 case DO_CONSTRAINT:
14474 case DO_FK_CONSTRAINT:
14475 /* Constraints are post-data, but only if dumped separately */
14476 if (((ConstraintInfo *) dobj)->separate)
14477 addObjectDependency(dobj, postDataBound->dumpId);
14479 case DO_PRE_DATA_BOUNDARY:
14480 /* nothing to do */
14482 case DO_POST_DATA_BOUNDARY:
14483 /* must come after the pre-data boundary */
14484 addObjectDependency(dobj, preDataBound->dumpId);
14492 * BuildArchiveDependencies - create dependency data for archive TOC entries
14494 * The raw dependency data obtained by getDependencies() is not terribly
14495 * useful in an archive dump, because in many cases there are dependency
14496 * chains linking through objects that don't appear explicitly in the dump.
14497 * For example, a view will depend on its _RETURN rule while the _RETURN rule
14498 * will depend on other objects --- but the rule will not appear as a separate
14499 * object in the dump. We need to adjust the view's dependencies to include
14500 * whatever the rule depends on that is included in the dump.
14502 * Just to make things more complicated, there are also "special" dependencies
14503 * such as the dependency of a TABLE DATA item on its TABLE, which we must
14504 * not rearrange because pg_restore knows that TABLE DATA only depends on
14505 * its table. In these cases we must leave the dependencies strictly as-is
14506 * even if they refer to not-to-be-dumped objects.
14508 * To handle this, the convention is that "special" dependencies are created
14509 * during ArchiveEntry calls, and an archive TOC item that has any such
14510 * entries will not be touched here. Otherwise, we recursively search the
14511 * DumpableObject data structures to build the correct dependencies for each
14512 * archive TOC item.
14515 BuildArchiveDependencies(Archive *fout)
14517 ArchiveHandle *AH = (ArchiveHandle *) fout;
14520 /* Scan all TOC entries in the archive */
14521 for (te = AH->toc->next; te != AH->toc; te = te->next)
14523 DumpableObject *dobj;
14524 DumpId *dependencies;
14528 /* No need to process entries that will not be dumped */
14531 /* Ignore entries that already have "special" dependencies */
14534 /* Otherwise, look up the item's original DumpableObject, if any */
14535 dobj = findObjectByDumpId(te->dumpId);
14538 /* No work if it has no dependencies */
14539 if (dobj->nDeps <= 0)
14541 /* Set up work array */
14543 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14545 /* Recursively find all dumpable dependencies */
14546 findDumpableDependencies(AH, dobj,
14547 &dependencies, &nDeps, &allocDeps);
14548 /* And save 'em ... */
14551 dependencies = (DumpId *) pg_realloc(dependencies,
14552 nDeps * sizeof(DumpId));
14553 te->dependencies = dependencies;
14557 free(dependencies);
14561 /* Recursive search subroutine for BuildArchiveDependencies */
14563 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14564 DumpId **dependencies, int *nDeps, int *allocDeps)
14569 * Ignore section boundary objects: if we search through them, we'll
14570 * report lots of bogus dependencies.
14572 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14573 dobj->objType == DO_POST_DATA_BOUNDARY)
14576 for (i = 0; i < dobj->nDeps; i++)
14578 DumpId depid = dobj->dependencies[i];
14580 if (TocIDRequired(AH, depid) != 0)
14582 /* Object will be dumped, so just reference it as a dependency */
14583 if (*nDeps >= *allocDeps)
14586 *dependencies = (DumpId *) pg_realloc(*dependencies,
14587 *allocDeps * sizeof(DumpId));
14589 (*dependencies)[*nDeps] = depid;
14595 * Object will not be dumped, so recursively consider its deps.
14596 * We rely on the assumption that sortDumpableObjects already
14597 * broke any dependency loops, else we might recurse infinitely.
14599 DumpableObject *otherdobj = findObjectByDumpId(depid);
14602 findDumpableDependencies(AH, otherdobj,
14603 dependencies, nDeps, allocDeps);
14610 * selectSourceSchema - make the specified schema the active search path
14611 * in the source database.
14613 * NB: pg_catalog is explicitly searched after the specified schema;
14614 * so user names are only qualified if they are cross-schema references,
14615 * and system names are only qualified if they conflict with a user name
14616 * in the current schema.
14618 * Whenever the selected schema is not pg_catalog, be careful to qualify
14619 * references to system catalogs and types in our emitted commands!
14622 selectSourceSchema(Archive *fout, const char *schemaName)
14624 static char *curSchemaName = NULL;
14627 /* Not relevant if fetching from pre-7.3 DB */
14628 if (fout->remoteVersion < 70300)
14630 /* Ignore null schema names */
14631 if (schemaName == NULL || *schemaName == '\0')
14633 /* Optimize away repeated selection of same schema */
14634 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14637 query = createPQExpBuffer();
14638 appendPQExpBuffer(query, "SET search_path = %s",
14639 fmtId(schemaName));
14640 if (strcmp(schemaName, "pg_catalog") != 0)
14641 appendPQExpBuffer(query, ", pg_catalog");
14643 ExecuteSqlStatement(fout, query->data);
14645 destroyPQExpBuffer(query);
14647 free(curSchemaName);
14648 curSchemaName = pg_strdup(schemaName);
14652 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14655 * NB: in 7.3 and up the result may depend on the currently-selected
14656 * schema; this is why we don't try to cache the names.
14659 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14667 if ((opts & zeroAsOpaque) != 0)
14668 return pg_strdup(g_opaque_type);
14669 else if ((opts & zeroAsAny) != 0)
14670 return pg_strdup("'any'");
14671 else if ((opts & zeroAsStar) != 0)
14672 return pg_strdup("*");
14673 else if ((opts & zeroAsNone) != 0)
14674 return pg_strdup("NONE");
14677 query = createPQExpBuffer();
14678 if (fout->remoteVersion >= 70300)
14680 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14683 else if (fout->remoteVersion >= 70100)
14685 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14690 appendPQExpBuffer(query, "SELECT typname "
14692 "WHERE oid = '%u'::oid",
14696 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14698 if (fout->remoteVersion >= 70100)
14700 /* already quoted */
14701 result = pg_strdup(PQgetvalue(res, 0, 0));
14705 /* may need to quote it */
14706 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14710 destroyPQExpBuffer(query);
14716 * myFormatType --- local implementation of format_type for use with 7.0.
14719 myFormatType(const char *typname, int32 typmod)
14722 bool isarray = false;
14723 PQExpBuffer buf = createPQExpBuffer();
14725 /* Handle array types */
14726 if (typname[0] == '_')
14732 /* Show lengths on bpchar and varchar */
14733 if (strcmp(typname, "bpchar") == 0)
14735 int len = (typmod - VARHDRSZ);
14737 appendPQExpBuffer(buf, "character");
14739 appendPQExpBuffer(buf, "(%d)",
14740 typmod - VARHDRSZ);
14742 else if (strcmp(typname, "varchar") == 0)
14744 appendPQExpBuffer(buf, "character varying");
14746 appendPQExpBuffer(buf, "(%d)",
14747 typmod - VARHDRSZ);
14749 else if (strcmp(typname, "numeric") == 0)
14751 appendPQExpBuffer(buf, "numeric");
14758 tmp_typmod = typmod - VARHDRSZ;
14759 precision = (tmp_typmod >> 16) & 0xffff;
14760 scale = tmp_typmod & 0xffff;
14761 appendPQExpBuffer(buf, "(%d,%d)",
14767 * char is an internal single-byte data type; Let's make sure we force it
14768 * through with quotes. - thomas 1998-12-13
14770 else if (strcmp(typname, "char") == 0)
14771 appendPQExpBuffer(buf, "\"char\"");
14773 appendPQExpBuffer(buf, "%s", fmtId(typname));
14775 /* Append array qualifier for array types */
14777 appendPQExpBuffer(buf, "[]");
14779 result = pg_strdup(buf->data);
14780 destroyPQExpBuffer(buf);
14786 * fmtQualifiedId - convert a qualified name to the proper format for
14787 * the source database.
14789 * Like fmtId, use the result before calling again.
14791 static const char *
14792 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14794 static PQExpBuffer id_return = NULL;
14796 if (id_return) /* first time through? */
14797 resetPQExpBuffer(id_return);
14799 id_return = createPQExpBuffer();
14801 /* Suppress schema name if fetching from pre-7.3 DB */
14802 if (fout->remoteVersion >= 70300 && schema && *schema)
14804 appendPQExpBuffer(id_return, "%s.",
14807 appendPQExpBuffer(id_return, "%s",
14810 return id_return->data;
14814 * Return a column list clause for the given relation.
14816 * Special case: if there are no undropped columns in the relation, return
14817 * "", not an invalid "()" column list.
14819 static const char *
14820 fmtCopyColumnList(const TableInfo *ti)
14822 static PQExpBuffer q = NULL;
14823 int numatts = ti->numatts;
14824 char **attnames = ti->attnames;
14825 bool *attisdropped = ti->attisdropped;
14829 if (q) /* first time through? */
14830 resetPQExpBuffer(q);
14832 q = createPQExpBuffer();
14834 appendPQExpBuffer(q, "(");
14836 for (i = 0; i < numatts; i++)
14838 if (attisdropped[i])
14841 appendPQExpBuffer(q, ", ");
14842 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14847 return ""; /* no undropped columns */
14849 appendPQExpBuffer(q, ")");
14854 * Execute an SQL query and verify that we got exactly one row back.
14857 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
14862 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
14864 /* Expecting a single result only */
14865 ntups = PQntuples(res);
14867 exit_horribly(NULL,
14868 ngettext("query returned %d row instead of one: %s\n",
14869 "query returned %d rows instead of one: %s\n",