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 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
155 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
156 static void dumpComment(Archive *fout, const char *target,
157 const char *namespace, const char *owner,
158 CatalogId catalogId, int subid, DumpId dumpId);
159 static int findComments(Archive *fout, Oid classoid, Oid objoid,
160 CommentItem **items);
161 static int collectComments(Archive *fout, CommentItem **items);
162 static void dumpSecLabel(Archive *fout, const char *target,
163 const char *namespace, const char *owner,
164 CatalogId catalogId, int subid, DumpId dumpId);
165 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
166 SecLabelItem **items);
167 static int collectSecLabels(Archive *fout, SecLabelItem **items);
168 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
169 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
170 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
171 static void dumpType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
173 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
176 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
178 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
179 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
180 static void dumpFunc(Archive *fout, FuncInfo *finfo);
181 static void dumpCast(Archive *fout, CastInfo *cast);
182 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
183 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
184 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
185 static void dumpCollation(Archive *fout, CollInfo *convinfo);
186 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
187 static void dumpRule(Archive *fout, RuleInfo *rinfo);
188 static void dumpAgg(Archive *fout, AggInfo *agginfo);
189 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
190 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
191 static void dumpTable(Archive *fout, TableInfo *tbinfo);
192 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
193 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
194 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
195 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
196 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
197 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
198 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
199 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
200 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
201 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
202 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
203 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
204 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
205 static void dumpUserMappings(Archive *fout,
206 const char *servername, const char *namespace,
207 const char *owner, CatalogId catalogId, DumpId dumpId);
208 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
210 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
211 const char *type, const char *name, const char *subname,
212 const char *tag, const char *nspname, const char *owner,
215 static void getDependencies(Archive *fout);
216 static void BuildArchiveDependencies(Archive *fout);
217 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
218 DumpId **dependencies, int *nDeps, int *allocDeps);
220 static DumpableObject *createBoundaryObjects(void);
221 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
222 DumpableObject *boundaryObjs);
224 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
225 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
226 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
227 static void buildMatViewRefreshDependencies(Archive *fout);
228 static void getTableDataFKConstraints(void);
229 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
230 static char *format_function_arguments_old(Archive *fout,
231 FuncInfo *finfo, int nallargs,
235 static char *format_function_signature(Archive *fout,
236 FuncInfo *finfo, bool honor_quotes);
237 static const char *convertRegProcReference(Archive *fout,
239 static const char *convertOperatorReference(Archive *fout, const char *opr);
240 static const char *convertTSFunction(Archive *fout, Oid funcOid);
241 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
242 static Oid findLastBuiltinOid_V70(Archive *fout);
243 static void selectSourceSchema(Archive *fout, const char *schemaName);
244 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
245 static char *myFormatType(const char *typname, int32 typmod);
246 static const char *fmtQualifiedId(Archive *fout,
247 const char *schema, const char *id);
248 static void getBlobs(Archive *fout);
249 static void dumpBlob(Archive *fout, BlobInfo *binfo);
250 static int dumpBlobs(Archive *fout, void *arg);
251 static void dumpDatabase(Archive *AH);
252 static void dumpEncoding(Archive *AH);
253 static void dumpStdStrings(Archive *AH);
254 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
255 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
256 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
257 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
258 static void binary_upgrade_set_pg_class_oids(Archive *fout,
259 PQExpBuffer upgrade_buffer,
260 Oid pg_class_oid, bool is_index);
261 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
262 DumpableObject *dobj,
263 const char *objlabel);
264 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
265 static const char *fmtCopyColumnList(const TableInfo *ti);
266 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
270 main(int argc, char **argv)
273 const char *filename = NULL;
274 const char *format = "p";
275 const char *dbname = NULL;
276 const char *pghost = NULL;
277 const char *pgport = NULL;
278 const char *username = NULL;
279 const char *dumpencoding = NULL;
283 DumpableObject **dobjs;
285 DumpableObject *boundaryObjs;
287 enum trivalue prompt_password = TRI_DEFAULT;
288 int compressLevel = -1;
291 int outputCreateDB = 0;
292 bool outputBlobs = false;
293 int outputNoOwner = 0;
294 char *outputSuperuser = NULL;
295 char *use_role = NULL;
298 RestoreOptions *ropt;
299 ArchiveFormat archiveFormat = archUnknown;
300 ArchiveMode archiveMode;
301 Archive *fout; /* the script file */
303 static int disable_triggers = 0;
304 static int outputNoTablespaces = 0;
305 static int use_setsessauth = 0;
307 static struct option long_options[] = {
308 {"data-only", no_argument, NULL, 'a'},
309 {"blobs", no_argument, NULL, 'b'},
310 {"clean", no_argument, NULL, 'c'},
311 {"create", no_argument, NULL, 'C'},
312 {"dbname", required_argument, NULL, 'd'},
313 {"file", required_argument, NULL, 'f'},
314 {"format", required_argument, NULL, 'F'},
315 {"host", required_argument, NULL, 'h'},
316 {"ignore-version", no_argument, NULL, 'i'},
317 {"no-reconnect", no_argument, NULL, 'R'},
318 {"oids", no_argument, NULL, 'o'},
319 {"no-owner", no_argument, NULL, 'O'},
320 {"port", required_argument, NULL, 'p'},
321 {"schema", required_argument, NULL, 'n'},
322 {"exclude-schema", required_argument, NULL, 'N'},
323 {"schema-only", no_argument, NULL, 's'},
324 {"superuser", required_argument, NULL, 'S'},
325 {"table", required_argument, NULL, 't'},
326 {"exclude-table", required_argument, NULL, 'T'},
327 {"no-password", no_argument, NULL, 'w'},
328 {"password", no_argument, NULL, 'W'},
329 {"username", required_argument, NULL, 'U'},
330 {"verbose", no_argument, NULL, 'v'},
331 {"no-privileges", no_argument, NULL, 'x'},
332 {"no-acl", no_argument, NULL, 'x'},
333 {"compress", required_argument, NULL, 'Z'},
334 {"encoding", required_argument, NULL, 'E'},
335 {"help", no_argument, NULL, '?'},
336 {"version", no_argument, NULL, 'V'},
339 * the following options don't have an equivalent short option letter
341 {"attribute-inserts", no_argument, &column_inserts, 1},
342 {"binary-upgrade", no_argument, &binary_upgrade, 1},
343 {"column-inserts", no_argument, &column_inserts, 1},
344 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
345 {"disable-triggers", no_argument, &disable_triggers, 1},
346 {"exclude-table-data", required_argument, NULL, 4},
347 {"inserts", no_argument, &dump_inserts, 1},
348 {"lock-wait-timeout", required_argument, NULL, 2},
349 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
350 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
351 {"role", required_argument, NULL, 3},
352 {"section", required_argument, NULL, 5},
353 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
354 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
355 {"no-security-labels", no_argument, &no_security_labels, 1},
356 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
361 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
365 strcpy(g_comment_start, "-- ");
366 g_comment_end[0] = '\0';
367 strcpy(g_opaque_type, "opaque");
369 dataOnly = schemaOnly = false;
370 dumpSections = DUMP_UNSECTIONED;
371 lockWaitTimeout = NULL;
373 progname = get_progname(argv[0]);
375 /* Set default options based on progname */
376 if (strcmp(progname, "pg_backup") == 0)
381 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
386 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
388 puts("pg_dump (PostgreSQL) " PG_VERSION);
393 while ((c = getopt_long(argc, argv, "abcCd:E:f:F:h:iK:n:N:oOp:RsS:t:T:U:vwWxZ:",
394 long_options, &optindex)) != -1)
398 case 'a': /* Dump data only */
402 case 'b': /* Dump blobs */
406 case 'c': /* clean (i.e., drop) schema prior to create */
410 case 'C': /* Create DB */
414 case 'd': /* database name */
415 dbname = pg_strdup(optarg);
418 case 'E': /* Dump encoding */
419 dumpencoding = pg_strdup(optarg);
423 filename = pg_strdup(optarg);
427 format = pg_strdup(optarg);
430 case 'h': /* server host */
431 pghost = pg_strdup(optarg);
435 /* ignored, deprecated option */
438 case 'n': /* include schema(s) */
439 simple_string_list_append(&schema_include_patterns, optarg);
440 include_everything = false;
443 case 'N': /* exclude schema(s) */
444 simple_string_list_append(&schema_exclude_patterns, optarg);
447 case 'o': /* Dump oids */
451 case 'O': /* Don't reconnect to match owner */
455 case 'p': /* server port */
456 pgport = pg_strdup(optarg);
460 /* no-op, still accepted for backwards compatibility */
463 case 's': /* dump schema only */
467 case 'S': /* Username for superuser in plain text output */
468 outputSuperuser = pg_strdup(optarg);
471 case 't': /* include table(s) */
472 simple_string_list_append(&table_include_patterns, optarg);
473 include_everything = false;
476 case 'T': /* exclude table(s) */
477 simple_string_list_append(&table_exclude_patterns, optarg);
481 username = pg_strdup(optarg);
484 case 'v': /* verbose */
489 prompt_password = TRI_NO;
493 prompt_password = TRI_YES;
496 case 'x': /* skip ACL dump */
500 case 'Z': /* Compression Level */
501 compressLevel = atoi(optarg);
505 /* This covers the long options. */
508 case 2: /* lock-wait-timeout */
509 lockWaitTimeout = pg_strdup(optarg);
512 case 3: /* SET ROLE */
513 use_role = pg_strdup(optarg);
516 case 4: /* exclude table(s) data */
517 simple_string_list_append(&tabledata_exclude_patterns, optarg);
520 case 5: /* section */
521 set_dump_section(optarg, &dumpSections);
525 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
531 * Non-option argument specifies database name as long as it wasn't
532 * already specified with -d / --dbname
534 if (optind < argc && dbname == NULL)
535 dbname = argv[optind++];
537 /* Complain if any arguments remain */
540 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
541 progname, argv[optind]);
542 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
547 /* --column-inserts implies --inserts */
551 if (dataOnly && schemaOnly)
552 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
554 if (dataOnly && outputClean)
555 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
557 if (dump_inserts && oids)
559 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
560 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
564 /* Identify archive format to emit */
565 archiveFormat = parseArchiveFormat(format, &archiveMode);
567 /* archiveFormat specific setup */
568 if (archiveFormat == archNull)
571 /* Custom and directory formats are compressed by default, others not */
572 if (compressLevel == -1)
574 if (archiveFormat == archCustom || archiveFormat == archDirectory)
575 compressLevel = Z_DEFAULT_COMPRESSION;
580 /* Open the output file */
581 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
583 /* Register the cleanup hook */
584 on_exit_close_archive(fout);
587 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
589 /* Let the archiver know how noisy to be */
590 fout->verbose = g_verbose;
592 my_version = parse_version(PG_VERSION);
594 exit_horribly(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
597 * We allow the server to be back to 7.0, and up to any minor release of
598 * our own major version. (See also version check in pg_dumpall.c.)
600 fout->minRemoteVersion = 70000;
601 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
604 * Open the database using the Archiver, so it knows about it. Errors mean
607 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
608 setup_connection(fout, dumpencoding, use_role);
611 * Disable security label support if server version < v9.1.x (prevents
612 * access to nonexistent pg_seclabel catalog)
614 if (fout->remoteVersion < 90100)
615 no_security_labels = 1;
618 * When running against 9.0 or later, check if we are in recovery mode,
619 * which means we are on a hot standby.
621 if (fout->remoteVersion >= 90000)
623 PGresult *res = ExecuteSqlQueryForSingleRow(fout, "SELECT pg_catalog.pg_is_in_recovery()");
624 if (strcmp(PQgetvalue(res, 0, 0), "t") == 0)
627 * On hot standby slaves, never try to dump unlogged table data,
628 * since it will just throw an error.
630 no_unlogged_table_data = true;
636 * Start transaction-snapshot mode transaction to dump consistent data.
638 ExecuteSqlStatement(fout, "BEGIN");
639 if (fout->remoteVersion >= 90100)
641 if (serializable_deferrable)
642 ExecuteSqlStatement(fout,
643 "SET TRANSACTION ISOLATION LEVEL "
644 "SERIALIZABLE, READ ONLY, DEFERRABLE");
646 ExecuteSqlStatement(fout,
647 "SET TRANSACTION ISOLATION LEVEL "
648 "REPEATABLE READ, READ ONLY");
650 else if (fout->remoteVersion >= 70400)
652 /* note: comma was not accepted in SET TRANSACTION before 8.0 */
653 ExecuteSqlStatement(fout,
654 "SET TRANSACTION ISOLATION LEVEL "
655 "SERIALIZABLE READ ONLY");
658 ExecuteSqlStatement(fout,
659 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
661 /* Select the appropriate subquery to convert user IDs to names */
662 if (fout->remoteVersion >= 80100)
663 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
664 else if (fout->remoteVersion >= 70300)
665 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
667 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
669 /* Find the last built-in OID, if needed */
670 if (fout->remoteVersion < 70300)
672 if (fout->remoteVersion >= 70100)
673 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
674 PQdb(GetConnection(fout)));
676 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
678 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
681 /* Expand schema selection patterns into OID lists */
682 if (schema_include_patterns.head != NULL)
684 expand_schema_name_patterns(fout, &schema_include_patterns,
685 &schema_include_oids);
686 if (schema_include_oids.head == NULL)
687 exit_horribly(NULL, "No matching schemas were found\n");
689 expand_schema_name_patterns(fout, &schema_exclude_patterns,
690 &schema_exclude_oids);
691 /* non-matching exclusion patterns aren't an error */
693 /* Expand table selection patterns into OID lists */
694 if (table_include_patterns.head != NULL)
696 expand_table_name_patterns(fout, &table_include_patterns,
697 &table_include_oids);
698 if (table_include_oids.head == NULL)
699 exit_horribly(NULL, "No matching tables were found\n");
701 expand_table_name_patterns(fout, &table_exclude_patterns,
702 &table_exclude_oids);
704 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
705 &tabledata_exclude_oids);
707 /* non-matching exclusion patterns aren't an error */
710 * Dumping blobs is now default unless we saw an inclusion switch or -s
711 * ... but even if we did see one of these, -b turns it back on.
713 if (include_everything && !schemaOnly)
717 * Now scan the database and create DumpableObject structs for all the
718 * objects we intend to dump.
720 tblinfo = getSchemaData(fout, &numTables);
722 if (fout->remoteVersion < 80400)
723 guessConstraintInheritance(tblinfo, numTables);
727 getTableData(tblinfo, numTables, oids);
728 buildMatViewRefreshDependencies(fout);
730 getTableDataFKConstraints();
737 * Collect dependency data to assist in ordering the objects.
739 getDependencies(fout);
741 /* Lastly, create dummy objects to represent the section boundaries */
742 boundaryObjs = createBoundaryObjects();
744 /* Get pointers to all the known DumpableObjects */
745 getDumpableObjects(&dobjs, &numObjs);
748 * Add dummy dependencies to enforce the dump section ordering.
750 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
753 * Sort the objects into a safe dump order (no forward references).
755 * In 7.3 or later, we can rely on dependency information to help us
756 * determine a safe order, so the initial sort is mostly for cosmetic
757 * purposes: we sort by name to ensure that logically identical schemas
758 * will dump identically. Before 7.3 we don't have dependencies and we
759 * use OID ordering as an (unreliable) guide to creation order.
761 if (fout->remoteVersion >= 70300)
762 sortDumpableObjectsByTypeName(dobjs, numObjs);
764 sortDumpableObjectsByTypeOid(dobjs, numObjs);
766 sortDumpableObjects(dobjs, numObjs,
767 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
770 * Create archive TOC entries for all the objects to be dumped, in a safe
774 /* First the special ENCODING and STDSTRINGS entries. */
776 dumpStdStrings(fout);
778 /* The database item is always next, unless we don't want it at all */
779 if (include_everything && !dataOnly)
782 /* Now the rearrangeable objects. */
783 for (i = 0; i < numObjs; i++)
784 dumpDumpableObject(fout, dobjs[i]);
787 * Set up options info to ensure we dump what we want.
789 ropt = NewRestoreOptions();
790 ropt->filename = filename;
791 ropt->dropSchema = outputClean;
792 ropt->dataOnly = dataOnly;
793 ropt->schemaOnly = schemaOnly;
794 ropt->dumpSections = dumpSections;
795 ropt->aclsSkip = aclsSkip;
796 ropt->superuser = outputSuperuser;
797 ropt->createDB = outputCreateDB;
798 ropt->noOwner = outputNoOwner;
799 ropt->noTablespace = outputNoTablespaces;
800 ropt->disable_triggers = disable_triggers;
801 ropt->use_setsessauth = use_setsessauth;
803 if (compressLevel == -1)
804 ropt->compression = 0;
806 ropt->compression = compressLevel;
808 ropt->suppressDumpWarnings = true; /* We've already shown them */
810 SetArchiveRestoreOptions(fout, ropt);
813 * The archive's TOC entries are now marked as to which ones will
814 * actually be output, so we can set up their dependency lists properly.
815 * This isn't necessary for plain-text output, though.
818 BuildArchiveDependencies(fout);
821 * And finally we can do the actual output.
823 * Note: for non-plain-text output formats, the output file is written
824 * inside CloseArchive(). This is, um, bizarre; but not worth changing
828 RestoreArchive(fout);
837 help(const char *progname)
839 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
840 printf(_("Usage:\n"));
841 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
843 printf(_("\nGeneral options:\n"));
844 printf(_(" -f, --file=FILENAME output file or directory name\n"));
845 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
846 " plain text (default))\n"));
847 printf(_(" -v, --verbose verbose mode\n"));
848 printf(_(" -V, --version output version information, then exit\n"));
849 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
850 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
851 printf(_(" -?, --help show this help, then exit\n"));
853 printf(_("\nOptions controlling the output content:\n"));
854 printf(_(" -a, --data-only dump only the data, not the schema\n"));
855 printf(_(" -b, --blobs include large objects in dump\n"));
856 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
857 printf(_(" -C, --create include commands to create database in dump\n"));
858 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
859 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
860 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
861 printf(_(" -o, --oids include OIDs in dump\n"));
862 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
863 " plain-text format\n"));
864 printf(_(" -s, --schema-only dump only the schema, no data\n"));
865 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
866 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
867 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
868 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
869 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
870 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
871 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
872 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
873 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
874 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
875 printf(_(" --no-security-labels do not dump security label assignments\n"));
876 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
877 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
878 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
879 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
880 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
881 printf(_(" --use-set-session-authorization\n"
882 " use SET SESSION AUTHORIZATION commands instead of\n"
883 " ALTER OWNER commands to set ownership\n"));
885 printf(_("\nConnection options:\n"));
886 printf(_(" -d, --dbname=DBNAME database to dump\n"));
887 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
888 printf(_(" -p, --port=PORT database server port number\n"));
889 printf(_(" -U, --username=NAME connect as specified database user\n"));
890 printf(_(" -w, --no-password never prompt for password\n"));
891 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
892 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
894 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
895 "variable value is used.\n\n"));
896 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
900 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
902 PGconn *conn = GetConnection(AH);
903 const char *std_strings;
905 /* Set the client encoding if requested */
908 if (PQsetClientEncoding(conn, dumpencoding) < 0)
909 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
914 * Get the active encoding and the standard_conforming_strings setting, so
915 * we know how to escape strings.
917 AH->encoding = PQclientEncoding(conn);
919 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
920 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
922 /* Set the role if requested */
923 if (use_role && AH->remoteVersion >= 80100)
925 PQExpBuffer query = createPQExpBuffer();
927 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
928 ExecuteSqlStatement(AH, query->data);
929 destroyPQExpBuffer(query);
932 /* Set the datestyle to ISO to ensure the dump's portability */
933 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
935 /* Likewise, avoid using sql_standard intervalstyle */
936 if (AH->remoteVersion >= 80400)
937 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
940 * If supported, set extra_float_digits so that we can dump float data
941 * exactly (given correctly implemented float I/O code, anyway)
943 if (AH->remoteVersion >= 90000)
944 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
945 else if (AH->remoteVersion >= 70400)
946 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
949 * If synchronized scanning is supported, disable it, to prevent
950 * unpredictable changes in row ordering across a dump and reload.
952 if (AH->remoteVersion >= 80300)
953 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
956 * Disable timeouts if supported.
958 if (AH->remoteVersion >= 70300)
959 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
962 * Quote all identifiers, if requested.
964 if (quote_all_identifiers && AH->remoteVersion >= 90100)
965 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
969 parseArchiveFormat(const char *format, ArchiveMode *mode)
971 ArchiveFormat archiveFormat;
973 *mode = archModeWrite;
975 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
977 /* This is used by pg_dumpall, and is not documented */
978 archiveFormat = archNull;
979 *mode = archModeAppend;
981 else if (pg_strcasecmp(format, "c") == 0)
982 archiveFormat = archCustom;
983 else if (pg_strcasecmp(format, "custom") == 0)
984 archiveFormat = archCustom;
985 else if (pg_strcasecmp(format, "d") == 0)
986 archiveFormat = archDirectory;
987 else if (pg_strcasecmp(format, "directory") == 0)
988 archiveFormat = archDirectory;
989 else if (pg_strcasecmp(format, "p") == 0)
990 archiveFormat = archNull;
991 else if (pg_strcasecmp(format, "plain") == 0)
992 archiveFormat = archNull;
993 else if (pg_strcasecmp(format, "t") == 0)
994 archiveFormat = archTar;
995 else if (pg_strcasecmp(format, "tar") == 0)
996 archiveFormat = archTar;
998 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
999 return archiveFormat;
1003 * Find the OIDs of all schemas matching the given list of patterns,
1004 * and append them to the given OID list.
1007 expand_schema_name_patterns(Archive *fout,
1008 SimpleStringList *patterns,
1009 SimpleOidList *oids)
1013 SimpleStringListCell *cell;
1016 if (patterns->head == NULL)
1017 return; /* nothing to do */
1019 if (fout->remoteVersion < 70300)
1020 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1022 query = createPQExpBuffer();
1025 * We use UNION ALL rather than UNION; this might sometimes result in
1026 * duplicate entries in the OID list, but we don't care.
1029 for (cell = patterns->head; cell; cell = cell->next)
1031 if (cell != patterns->head)
1032 appendPQExpBuffer(query, "UNION ALL\n");
1033 appendPQExpBuffer(query,
1034 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1035 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1036 false, NULL, "n.nspname", NULL, NULL);
1039 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1041 for (i = 0; i < PQntuples(res); i++)
1043 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1047 destroyPQExpBuffer(query);
1051 * Find the OIDs of all tables matching the given list of patterns,
1052 * and append them to the given OID list.
1055 expand_table_name_patterns(Archive *fout,
1056 SimpleStringList *patterns, SimpleOidList *oids)
1060 SimpleStringListCell *cell;
1063 if (patterns->head == NULL)
1064 return; /* nothing to do */
1066 query = createPQExpBuffer();
1069 * We use UNION ALL rather than UNION; this might sometimes result in
1070 * duplicate entries in the OID list, but we don't care.
1073 for (cell = patterns->head; cell; cell = cell->next)
1075 if (cell != patterns->head)
1076 appendPQExpBuffer(query, "UNION ALL\n");
1077 appendPQExpBuffer(query,
1079 "\nFROM pg_catalog.pg_class c"
1080 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1081 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c')\n",
1082 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1083 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
1084 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1085 false, "n.nspname", "c.relname", NULL,
1086 "pg_catalog.pg_table_is_visible(c.oid)");
1089 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1091 for (i = 0; i < PQntuples(res); i++)
1093 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1097 destroyPQExpBuffer(query);
1101 * selectDumpableNamespace: policy-setting subroutine
1102 * Mark a namespace as to be dumped or not
1105 selectDumpableNamespace(NamespaceInfo *nsinfo)
1108 * If specific tables are being dumped, do not dump any complete
1109 * namespaces. If specific namespaces are being dumped, dump just those
1110 * namespaces. Otherwise, dump all non-system namespaces.
1112 if (table_include_oids.head != NULL)
1113 nsinfo->dobj.dump = false;
1114 else if (schema_include_oids.head != NULL)
1115 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1116 nsinfo->dobj.catId.oid);
1117 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1118 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1119 nsinfo->dobj.dump = false;
1121 nsinfo->dobj.dump = true;
1124 * In any case, a namespace can be excluded by an exclusion switch
1126 if (nsinfo->dobj.dump &&
1127 simple_oid_list_member(&schema_exclude_oids,
1128 nsinfo->dobj.catId.oid))
1129 nsinfo->dobj.dump = false;
1133 * selectDumpableTable: policy-setting subroutine
1134 * Mark a table as to be dumped or not
1137 selectDumpableTable(TableInfo *tbinfo)
1140 * If specific tables are being dumped, dump just those tables; else, dump
1141 * according to the parent namespace's dump flag.
1143 if (table_include_oids.head != NULL)
1144 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1145 tbinfo->dobj.catId.oid);
1147 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1150 * In any case, a table can be excluded by an exclusion switch
1152 if (tbinfo->dobj.dump &&
1153 simple_oid_list_member(&table_exclude_oids,
1154 tbinfo->dobj.catId.oid))
1155 tbinfo->dobj.dump = false;
1159 * selectDumpableType: policy-setting subroutine
1160 * Mark a type as to be dumped or not
1162 * If it's a table's rowtype or an autogenerated array type, we also apply a
1163 * special type code to facilitate sorting into the desired order. (We don't
1164 * want to consider those to be ordinary types because that would bring tables
1165 * up into the datatype part of the dump order.) We still set the object's
1166 * dump flag; that's not going to cause the dummy type to be dumped, but we
1167 * need it so that casts involving such types will be dumped correctly -- see
1168 * dumpCast. This means the flag should be set the same as for the underlying
1169 * object (the table or base type).
1172 selectDumpableType(TypeInfo *tyinfo)
1174 /* skip complex types, except for standalone composite types */
1175 if (OidIsValid(tyinfo->typrelid) &&
1176 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1178 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1180 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1181 if (tytable != NULL)
1182 tyinfo->dobj.dump = tytable->dobj.dump;
1184 tyinfo->dobj.dump = false;
1188 /* skip auto-generated array types */
1189 if (tyinfo->isArray)
1191 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1194 * Fall through to set the dump flag; we assume that the subsequent
1195 * rules will do the same thing as they would for the array's base
1196 * type. (We cannot reliably look up the base type here, since
1197 * getTypes may not have processed it yet.)
1201 /* dump only types in dumpable namespaces */
1202 if (!tyinfo->dobj.namespace->dobj.dump)
1203 tyinfo->dobj.dump = false;
1205 /* skip undefined placeholder types */
1206 else if (!tyinfo->isDefined)
1207 tyinfo->dobj.dump = false;
1210 tyinfo->dobj.dump = true;
1214 * selectDumpableDefaultACL: policy-setting subroutine
1215 * Mark a default ACL as to be dumped or not
1217 * For per-schema default ACLs, dump if the schema is to be dumped.
1218 * Otherwise dump if we are dumping "everything". Note that dataOnly
1219 * and aclsSkip are checked separately.
1222 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1224 if (dinfo->dobj.namespace)
1225 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1227 dinfo->dobj.dump = include_everything;
1231 * selectDumpableExtension: policy-setting subroutine
1232 * Mark an extension as to be dumped or not
1234 * Normally, we dump all extensions, or none of them if include_everything
1235 * is false (i.e., a --schema or --table switch was given). However, in
1236 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1237 * assume those will already be installed in the target database. We identify
1238 * such extensions by their having OIDs in the range reserved for initdb.
1241 selectDumpableExtension(ExtensionInfo *extinfo)
1243 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1244 extinfo->dobj.dump = false;
1246 extinfo->dobj.dump = include_everything;
1250 * selectDumpableObject: policy-setting subroutine
1251 * Mark a generic dumpable object as to be dumped or not
1253 * Use this only for object types without a special-case routine above.
1256 selectDumpableObject(DumpableObject *dobj)
1259 * Default policy is to dump if parent namespace is dumpable, or always
1260 * for non-namespace-associated items.
1262 if (dobj->namespace)
1263 dobj->dump = dobj->namespace->dobj.dump;
1269 * Dump a table's contents for loading using the COPY command
1270 * - this routine is called by the Archiver when it wants the table
1275 dumpTableData_copy(Archive *fout, void *dcontext)
1277 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1278 TableInfo *tbinfo = tdinfo->tdtable;
1279 const char *classname = tbinfo->dobj.name;
1280 const bool hasoids = tbinfo->hasoids;
1281 const bool oids = tdinfo->oids;
1282 PQExpBuffer q = createPQExpBuffer();
1283 PGconn *conn = GetConnection(fout);
1287 const char *column_list;
1290 write_msg(NULL, "dumping contents of table %s\n", classname);
1293 * Make sure we are in proper schema. We will qualify the table name
1294 * below anyway (in case its name conflicts with a pg_catalog table); but
1295 * this ensures reproducible results in case the table contains regproc,
1296 * regclass, etc columns.
1298 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1301 * If possible, specify the column list explicitly so that we have no
1302 * possibility of retrieving data in the wrong column order. (The default
1303 * column ordering of COPY will not be what we want in certain corner
1304 * cases involving ADD COLUMN and inheritance.)
1306 if (fout->remoteVersion >= 70300)
1307 column_list = fmtCopyColumnList(tbinfo);
1309 column_list = ""; /* can't select columns in COPY */
1311 if (oids && hasoids)
1313 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1314 fmtQualifiedId(fout,
1315 tbinfo->dobj.namespace->dobj.name,
1319 else if (tdinfo->filtercond)
1321 /* Note: this syntax is only supported in 8.2 and up */
1322 appendPQExpBufferStr(q, "COPY (SELECT ");
1323 /* klugery to get rid of parens in column list */
1324 if (strlen(column_list) > 2)
1326 appendPQExpBufferStr(q, column_list + 1);
1327 q->data[q->len - 1] = ' ';
1330 appendPQExpBufferStr(q, "* ");
1331 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1332 fmtQualifiedId(fout,
1333 tbinfo->dobj.namespace->dobj.name,
1335 tdinfo->filtercond);
1339 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1340 fmtQualifiedId(fout,
1341 tbinfo->dobj.namespace->dobj.name,
1345 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1350 ret = PQgetCopyData(conn, ©buf, 0);
1353 break; /* done or error */
1357 WriteData(fout, copybuf, ret);
1364 * There was considerable discussion in late July, 2000 regarding
1365 * slowing down pg_dump when backing up large tables. Users with both
1366 * slow & fast (multi-processor) machines experienced performance
1367 * degradation when doing a backup.
1369 * Initial attempts based on sleeping for a number of ms for each ms
1370 * of work were deemed too complex, then a simple 'sleep in each loop'
1371 * implementation was suggested. The latter failed because the loop
1372 * was too tight. Finally, the following was implemented:
1374 * If throttle is non-zero, then
1375 * See how long since the last sleep.
1376 * Work out how long to sleep (based on ratio).
1377 * If sleep is more than 100ms, then
1383 * where the throttle value was the number of ms to sleep per ms of
1384 * work. The calculation was done in each loop.
1386 * Most of the hard work is done in the backend, and this solution
1387 * still did not work particularly well: on slow machines, the ratio
1388 * was 50:1, and on medium paced machines, 1:1, and on fast
1389 * multi-processor machines, it had little or no effect, for reasons
1390 * that were unclear.
1392 * Further discussion ensued, and the proposal was dropped.
1394 * For those people who want this feature, it can be implemented using
1395 * gettimeofday in each loop, calculating the time since last sleep,
1396 * multiplying that by the sleep ratio, then if the result is more
1397 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1398 * function to sleep for a subsecond period ie.
1400 * select(0, NULL, NULL, NULL, &tvi);
1402 * This will return after the interval specified in the structure tvi.
1403 * Finally, call gettimeofday again to save the 'last sleep time'.
1407 archprintf(fout, "\\.\n\n\n");
1411 /* copy data transfer failed */
1412 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1413 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1414 write_msg(NULL, "The command was: %s\n", q->data);
1418 /* Check command status and return to normal libpq state */
1419 res = PQgetResult(conn);
1420 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1422 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1423 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1424 write_msg(NULL, "The command was: %s\n", q->data);
1429 destroyPQExpBuffer(q);
1434 * Dump table data using INSERT commands.
1436 * Caution: when we restore from an archive file direct to database, the
1437 * INSERT commands emitted by this function have to be parsed by
1438 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1439 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1442 dumpTableData_insert(Archive *fout, void *dcontext)
1444 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1445 TableInfo *tbinfo = tdinfo->tdtable;
1446 const char *classname = tbinfo->dobj.name;
1447 PQExpBuffer q = createPQExpBuffer();
1454 * Make sure we are in proper schema. We will qualify the table name
1455 * below anyway (in case its name conflicts with a pg_catalog table); but
1456 * this ensures reproducible results in case the table contains regproc,
1457 * regclass, etc columns.
1459 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1461 if (fout->remoteVersion >= 70100)
1463 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1464 "SELECT * FROM ONLY %s",
1465 fmtQualifiedId(fout,
1466 tbinfo->dobj.namespace->dobj.name,
1471 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1473 fmtQualifiedId(fout,
1474 tbinfo->dobj.namespace->dobj.name,
1477 if (tdinfo->filtercond)
1478 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1480 ExecuteSqlStatement(fout, q->data);
1484 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1486 nfields = PQnfields(res);
1487 for (tuple = 0; tuple < PQntuples(res); tuple++)
1489 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1492 /* corner case for zero-column table */
1493 archprintf(fout, "DEFAULT VALUES;\n");
1498 resetPQExpBuffer(q);
1499 appendPQExpBuffer(q, "(");
1500 for (field = 0; field < nfields; field++)
1503 appendPQExpBuffer(q, ", ");
1504 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1506 appendPQExpBuffer(q, ") ");
1507 archputs(q->data, fout);
1509 archprintf(fout, "VALUES (");
1510 for (field = 0; field < nfields; field++)
1513 archprintf(fout, ", ");
1514 if (PQgetisnull(res, tuple, field))
1516 archprintf(fout, "NULL");
1520 /* XXX This code is partially duplicated in ruleutils.c */
1521 switch (PQftype(res, field))
1532 * These types are printed without quotes unless
1533 * they contain values that aren't accepted by the
1534 * scanner unquoted (e.g., 'NaN'). Note that
1535 * strtod() and friends might accept NaN, so we
1536 * can't use that to test.
1538 * In reality we only need to defend against
1539 * infinity and NaN, so we need not get too crazy
1540 * about pattern matching here.
1542 const char *s = PQgetvalue(res, tuple, field);
1544 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1545 archprintf(fout, "%s", s);
1547 archprintf(fout, "'%s'", s);
1553 archprintf(fout, "B'%s'",
1554 PQgetvalue(res, tuple, field));
1558 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1559 archprintf(fout, "true");
1561 archprintf(fout, "false");
1565 /* All other types are printed as string literals. */
1566 resetPQExpBuffer(q);
1567 appendStringLiteralAH(q,
1568 PQgetvalue(res, tuple, field),
1570 archputs(q->data, fout);
1574 archprintf(fout, ");\n");
1577 if (PQntuples(res) <= 0)
1585 archprintf(fout, "\n\n");
1587 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1589 destroyPQExpBuffer(q);
1596 * dump the contents of a single table
1598 * Actually, this just makes an ArchiveEntry for the table contents.
1601 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1603 TableInfo *tbinfo = tdinfo->tdtable;
1604 PQExpBuffer copyBuf = createPQExpBuffer();
1605 DataDumperPtr dumpFn;
1610 /* Dump/restore using COPY */
1611 dumpFn = dumpTableData_copy;
1612 /* must use 2 steps here 'cause fmtId is nonreentrant */
1613 appendPQExpBuffer(copyBuf, "COPY %s ",
1614 fmtId(tbinfo->dobj.name));
1615 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1616 fmtCopyColumnList(tbinfo),
1617 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1618 copyStmt = copyBuf->data;
1622 /* Restore using INSERT */
1623 dumpFn = dumpTableData_insert;
1628 * Note: although the TableDataInfo is a full DumpableObject, we treat its
1629 * dependency on its table as "special" and pass it to ArchiveEntry now.
1630 * See comments for BuildArchiveDependencies.
1632 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1633 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1634 NULL, tbinfo->rolname,
1635 false, "TABLE DATA", SECTION_DATA,
1637 &(tbinfo->dobj.dumpId), 1,
1640 destroyPQExpBuffer(copyBuf);
1644 * refreshMatViewData -
1645 * load or refresh the contents of a single materialized view
1647 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
1651 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
1653 TableInfo *tbinfo = tdinfo->tdtable;
1656 /* If the materialized view is not flagged as scannable, skip this. */
1657 if (!tbinfo->isscannable)
1660 q = createPQExpBuffer();
1662 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
1663 fmtId(tbinfo->dobj.name));
1666 tdinfo->dobj.catId, /* catalog ID */
1667 tdinfo->dobj.dumpId, /* dump ID */
1668 tbinfo->dobj.name, /* Name */
1669 tbinfo->dobj.namespace->dobj.name, /* Namespace */
1670 NULL, /* Tablespace */
1671 tbinfo->rolname, /* Owner */
1672 false, /* with oids */
1673 "MATERIALIZED VIEW DATA", /* Desc */
1674 SECTION_POST_DATA, /* Section */
1675 q->data, /* Create */
1678 tdinfo->dobj.dependencies, /* Deps */
1679 tdinfo->dobj.nDeps, /* # Deps */
1681 NULL); /* Dumper Arg */
1683 destroyPQExpBuffer(q);
1688 * set up dumpable objects representing the contents of tables
1691 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1695 for (i = 0; i < numTables; i++)
1697 if (tblinfo[i].dobj.dump)
1698 makeTableDataInfo(&(tblinfo[i]), oids);
1703 * Make a dumpable object for the data of this specific table
1705 * Note: we make a TableDataInfo if and only if we are going to dump the
1706 * table data; the "dump" flag in such objects isn't used.
1709 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1711 TableDataInfo *tdinfo;
1714 * Nothing to do if we already decided to dump the table. This will
1715 * happen for "config" tables.
1717 if (tbinfo->dataObj != NULL)
1720 /* Skip VIEWs (no data to dump) */
1721 if (tbinfo->relkind == RELKIND_VIEW)
1723 /* Skip FOREIGN TABLEs (no data to dump) */
1724 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1727 /* Don't dump data in unlogged tables, if so requested */
1728 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1729 no_unlogged_table_data)
1732 /* Check that the data is not explicitly excluded */
1733 if (simple_oid_list_member(&tabledata_exclude_oids,
1734 tbinfo->dobj.catId.oid))
1737 /* OK, let's dump it */
1738 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1740 if (tbinfo->relkind == RELKIND_MATVIEW)
1741 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
1743 tdinfo->dobj.objType = DO_TABLE_DATA;
1746 * Note: use tableoid 0 so that this object won't be mistaken for
1747 * something that pg_depend entries apply to.
1749 tdinfo->dobj.catId.tableoid = 0;
1750 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1751 AssignDumpId(&tdinfo->dobj);
1752 tdinfo->dobj.name = tbinfo->dobj.name;
1753 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1754 tdinfo->tdtable = tbinfo;
1755 tdinfo->oids = oids;
1756 tdinfo->filtercond = NULL; /* might get set later */
1757 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1759 tbinfo->dataObj = tdinfo;
1763 * The refresh for a materialized view must be dependent on the refresh for
1764 * any materialized view that this one is dependent on.
1766 * This must be called after all the objects are created, but before they are
1770 buildMatViewRefreshDependencies(Archive *fout)
1772 PQExpBuffer query = createPQExpBuffer();
1780 /* Make sure we are in proper schema */
1781 selectSourceSchema(fout, "pg_catalog");
1783 if (fout->remoteVersion >= 90300)
1785 appendPQExpBuffer(query, "with recursive w as "
1787 "select d1.objid, d2.refobjid, c2.relkind as refrelkind "
1788 "from pg_depend d1 "
1789 "join pg_class c1 on c1.oid = d1.objid "
1790 "and c1.relkind = 'm' "
1791 "join pg_rewrite r1 on r1.ev_class = d1.objid "
1792 "join pg_depend d2 on d2.classid = 'pg_rewrite'::regclass "
1793 "and d2.objid = r1.oid "
1794 "and d2.refobjid <> d1.objid "
1795 "join pg_class c2 on c2.oid = d2.refobjid "
1796 "and c2.relkind in ('m','v') "
1797 "where d1.classid = 'pg_class'::regclass "
1799 "select w.objid, d3.refobjid, c3.relkind "
1801 "join pg_rewrite r3 on r3.ev_class = w.refobjid "
1802 "join pg_depend d3 on d3.classid = 'pg_rewrite'::regclass "
1803 "and d3.objid = r3.oid "
1804 "and d3.refobjid <> w.refobjid "
1805 "join pg_class c3 on c3.oid = d3.refobjid "
1806 "and c3.relkind in ('m','v') "
1808 "select 'pg_class'::regclass::oid as classid, objid, refobjid "
1810 "where refrelkind = 'm'");
1813 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1815 ntups = PQntuples(res);
1817 i_classid = PQfnumber(res, "classid");
1818 i_objid = PQfnumber(res, "objid");
1819 i_refobjid = PQfnumber(res, "refobjid");
1821 for (i = 0; i < ntups; i++)
1825 DumpableObject *dobj;
1826 DumpableObject *refdobj;
1828 TableInfo *reftbinfo;
1830 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
1831 objId.oid = atooid(PQgetvalue(res, i, i_objid));
1832 refobjId.tableoid = objId.tableoid;
1833 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
1835 dobj = findObjectByCatalogId(objId);
1839 Assert(dobj->objType == DO_TABLE);
1840 tbinfo = (TableInfo *) dobj;
1841 Assert(tbinfo->relkind == RELKIND_MATVIEW);
1842 dobj = (DumpableObject *) tbinfo->dataObj;
1845 Assert(dobj->objType == DO_REFRESH_MATVIEW);
1847 refdobj = findObjectByCatalogId(refobjId);
1848 if (refdobj == NULL)
1851 Assert(refdobj->objType == DO_TABLE);
1852 reftbinfo = (TableInfo *) refdobj;
1853 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
1854 refdobj = (DumpableObject *) reftbinfo->dataObj;
1855 if (refdobj == NULL)
1857 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
1859 addObjectDependency(dobj, refdobj->dumpId);
1861 if (!reftbinfo->isscannable)
1862 tbinfo->isscannable = false;
1867 destroyPQExpBuffer(query);
1871 * getTableDataFKConstraints -
1872 * add dump-order dependencies reflecting foreign key constraints
1874 * This code is executed only in a data-only dump --- in schema+data dumps
1875 * we handle foreign key issues by not creating the FK constraints until
1876 * after the data is loaded. In a data-only dump, however, we want to
1877 * order the table data objects in such a way that a table's referenced
1878 * tables are restored first. (In the presence of circular references or
1879 * self-references this may be impossible; we'll detect and complain about
1880 * that during the dependency sorting step.)
1883 getTableDataFKConstraints(void)
1885 DumpableObject **dobjs;
1889 /* Search through all the dumpable objects for FK constraints */
1890 getDumpableObjects(&dobjs, &numObjs);
1891 for (i = 0; i < numObjs; i++)
1893 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1895 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1898 /* Not interesting unless both tables are to be dumped */
1899 if (cinfo->contable == NULL ||
1900 cinfo->contable->dataObj == NULL)
1902 ftable = findTableByOid(cinfo->confrelid);
1903 if (ftable == NULL ||
1904 ftable->dataObj == NULL)
1908 * Okay, make referencing table's TABLE_DATA object depend on the
1909 * referenced table's TABLE_DATA object.
1911 addObjectDependency(&cinfo->contable->dataObj->dobj,
1912 ftable->dataObj->dobj.dumpId);
1920 * guessConstraintInheritance:
1921 * In pre-8.4 databases, we can't tell for certain which constraints
1922 * are inherited. We assume a CHECK constraint is inherited if its name
1923 * matches the name of any constraint in the parent. Originally this code
1924 * tried to compare the expression texts, but that can fail for various
1925 * reasons --- for example, if the parent and child tables are in different
1926 * schemas, reverse-listing of function calls may produce different text
1927 * (schema-qualified or not) depending on search path.
1929 * In 8.4 and up we can rely on the conislocal field to decide which
1930 * constraints must be dumped; much safer.
1932 * This function assumes all conislocal flags were initialized to TRUE.
1933 * It clears the flag on anything that seems to be inherited.
1936 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1942 for (i = 0; i < numTables; i++)
1944 TableInfo *tbinfo = &(tblinfo[i]);
1946 TableInfo **parents;
1949 /* Sequences and views never have parents */
1950 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1951 tbinfo->relkind == RELKIND_VIEW)
1954 /* Don't bother computing anything for non-target tables, either */
1955 if (!tbinfo->dobj.dump)
1958 numParents = tbinfo->numParents;
1959 parents = tbinfo->parents;
1961 if (numParents == 0)
1962 continue; /* nothing to see here, move along */
1964 /* scan for inherited CHECK constraints */
1965 for (j = 0; j < tbinfo->ncheck; j++)
1967 ConstraintInfo *constr;
1969 constr = &(tbinfo->checkexprs[j]);
1971 for (k = 0; k < numParents; k++)
1975 parent = parents[k];
1976 for (l = 0; l < parent->ncheck; l++)
1978 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1980 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1982 constr->conislocal = false;
1986 if (!constr->conislocal)
1996 * dump the database definition
1999 dumpDatabase(Archive *fout)
2001 PQExpBuffer dbQry = createPQExpBuffer();
2002 PQExpBuffer delQry = createPQExpBuffer();
2003 PQExpBuffer creaQry = createPQExpBuffer();
2004 PGconn *conn = GetConnection(fout);
2016 const char *datname,
2024 datname = PQdb(conn);
2027 write_msg(NULL, "saving database definition\n");
2029 /* Make sure we are in proper schema */
2030 selectSourceSchema(fout, "pg_catalog");
2032 /* Get the database owner and parameters from pg_database */
2033 if (fout->remoteVersion >= 80400)
2035 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2036 "(%s datdba) AS dba, "
2037 "pg_encoding_to_char(encoding) AS encoding, "
2038 "datcollate, datctype, datfrozenxid, "
2039 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2040 "shobj_description(oid, 'pg_database') AS description "
2045 appendStringLiteralAH(dbQry, datname, fout);
2047 else if (fout->remoteVersion >= 80200)
2049 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2050 "(%s datdba) AS dba, "
2051 "pg_encoding_to_char(encoding) AS encoding, "
2052 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2053 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2054 "shobj_description(oid, 'pg_database') AS description "
2059 appendStringLiteralAH(dbQry, datname, fout);
2061 else if (fout->remoteVersion >= 80000)
2063 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2064 "(%s datdba) AS dba, "
2065 "pg_encoding_to_char(encoding) AS encoding, "
2066 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2067 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2071 appendStringLiteralAH(dbQry, datname, fout);
2073 else if (fout->remoteVersion >= 70100)
2075 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2076 "(%s datdba) AS dba, "
2077 "pg_encoding_to_char(encoding) AS encoding, "
2078 "NULL AS datcollate, NULL AS datctype, "
2079 "0 AS datfrozenxid, "
2080 "NULL AS tablespace "
2084 appendStringLiteralAH(dbQry, datname, fout);
2088 appendPQExpBuffer(dbQry, "SELECT "
2089 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
2091 "(%s datdba) AS dba, "
2092 "pg_encoding_to_char(encoding) AS encoding, "
2093 "NULL AS datcollate, NULL AS datctype, "
2094 "0 AS datfrozenxid, "
2095 "NULL AS tablespace "
2099 appendStringLiteralAH(dbQry, datname, fout);
2102 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2104 i_tableoid = PQfnumber(res, "tableoid");
2105 i_oid = PQfnumber(res, "oid");
2106 i_dba = PQfnumber(res, "dba");
2107 i_encoding = PQfnumber(res, "encoding");
2108 i_collate = PQfnumber(res, "datcollate");
2109 i_ctype = PQfnumber(res, "datctype");
2110 i_frozenxid = PQfnumber(res, "datfrozenxid");
2111 i_tablespace = PQfnumber(res, "tablespace");
2113 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2114 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2115 dba = PQgetvalue(res, 0, i_dba);
2116 encoding = PQgetvalue(res, 0, i_encoding);
2117 collate = PQgetvalue(res, 0, i_collate);
2118 ctype = PQgetvalue(res, 0, i_ctype);
2119 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2120 tablespace = PQgetvalue(res, 0, i_tablespace);
2122 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2124 if (strlen(encoding) > 0)
2126 appendPQExpBuffer(creaQry, " ENCODING = ");
2127 appendStringLiteralAH(creaQry, encoding, fout);
2129 if (strlen(collate) > 0)
2131 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
2132 appendStringLiteralAH(creaQry, collate, fout);
2134 if (strlen(ctype) > 0)
2136 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
2137 appendStringLiteralAH(creaQry, ctype, fout);
2139 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
2140 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2142 appendPQExpBuffer(creaQry, ";\n");
2146 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
2147 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2148 "SET datfrozenxid = '%u'\n"
2151 appendStringLiteralAH(creaQry, datname, fout);
2152 appendPQExpBuffer(creaQry, ";\n");
2156 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2159 dbDumpId = createDumpId();
2162 dbCatId, /* catalog ID */
2163 dbDumpId, /* dump ID */
2165 NULL, /* Namespace */
2166 NULL, /* Tablespace */
2168 false, /* with oids */
2169 "DATABASE", /* Desc */
2170 SECTION_PRE_DATA, /* Section */
2171 creaQry->data, /* Create */
2172 delQry->data, /* Del */
2177 NULL); /* Dumper Arg */
2180 * pg_largeobject and pg_largeobject_metadata come from the old system
2181 * intact, so set their relfrozenxids.
2186 PQExpBuffer loFrozenQry = createPQExpBuffer();
2187 PQExpBuffer loOutQry = createPQExpBuffer();
2193 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2194 "FROM pg_catalog.pg_class\n"
2195 "WHERE oid = %u;\n",
2196 LargeObjectRelationId);
2198 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2200 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2202 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2203 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2204 "SET relfrozenxid = '%u'\n"
2205 "WHERE oid = %u;\n",
2206 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2207 LargeObjectRelationId);
2208 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2209 "pg_largeobject", NULL, NULL, "",
2210 false, "pg_largeobject", SECTION_PRE_DATA,
2211 loOutQry->data, "", NULL,
2218 * pg_largeobject_metadata
2220 if (fout->remoteVersion >= 90000)
2222 resetPQExpBuffer(loFrozenQry);
2223 resetPQExpBuffer(loOutQry);
2225 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2226 "FROM pg_catalog.pg_class\n"
2227 "WHERE oid = %u;\n",
2228 LargeObjectMetadataRelationId);
2230 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2232 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2234 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2235 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2236 "SET relfrozenxid = '%u'\n"
2237 "WHERE oid = %u;\n",
2238 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2239 LargeObjectMetadataRelationId);
2240 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2241 "pg_largeobject_metadata", NULL, NULL, "",
2242 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2243 loOutQry->data, "", NULL,
2250 destroyPQExpBuffer(loFrozenQry);
2251 destroyPQExpBuffer(loOutQry);
2254 /* Dump DB comment if any */
2255 if (fout->remoteVersion >= 80200)
2258 * 8.2 keeps comments on shared objects in a shared table, so we
2259 * cannot use the dumpComment used for other database objects.
2261 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2263 if (comment && strlen(comment))
2265 resetPQExpBuffer(dbQry);
2268 * Generates warning when loaded into a differently-named
2271 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2272 appendStringLiteralAH(dbQry, comment, fout);
2273 appendPQExpBuffer(dbQry, ";\n");
2275 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2276 dba, false, "COMMENT", SECTION_NONE,
2277 dbQry->data, "", NULL,
2278 &dbDumpId, 1, NULL, NULL);
2283 resetPQExpBuffer(dbQry);
2284 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2285 dumpComment(fout, dbQry->data, NULL, "",
2286 dbCatId, 0, dbDumpId);
2291 /* Dump shared security label. */
2292 if (!no_security_labels && fout->remoteVersion >= 90200)
2294 PQExpBuffer seclabelQry = createPQExpBuffer();
2296 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2297 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2298 resetPQExpBuffer(seclabelQry);
2299 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2300 if (strlen(seclabelQry->data))
2301 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2302 dba, false, "SECURITY LABEL", SECTION_NONE,
2303 seclabelQry->data, "", NULL,
2304 &dbDumpId, 1, NULL, NULL);
2305 destroyPQExpBuffer(seclabelQry);
2308 destroyPQExpBuffer(dbQry);
2309 destroyPQExpBuffer(delQry);
2310 destroyPQExpBuffer(creaQry);
2315 * dumpEncoding: put the correct encoding into the archive
2318 dumpEncoding(Archive *AH)
2320 const char *encname = pg_encoding_to_char(AH->encoding);
2321 PQExpBuffer qry = createPQExpBuffer();
2324 write_msg(NULL, "saving encoding = %s\n", encname);
2326 appendPQExpBuffer(qry, "SET client_encoding = ");
2327 appendStringLiteralAH(qry, encname, AH);
2328 appendPQExpBuffer(qry, ";\n");
2330 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2331 "ENCODING", NULL, NULL, "",
2332 false, "ENCODING", SECTION_PRE_DATA,
2333 qry->data, "", NULL,
2337 destroyPQExpBuffer(qry);
2342 * dumpStdStrings: put the correct escape string behavior into the archive
2345 dumpStdStrings(Archive *AH)
2347 const char *stdstrings = AH->std_strings ? "on" : "off";
2348 PQExpBuffer qry = createPQExpBuffer();
2351 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2354 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2357 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2358 "STDSTRINGS", NULL, NULL, "",
2359 false, "STDSTRINGS", SECTION_PRE_DATA,
2360 qry->data, "", NULL,
2364 destroyPQExpBuffer(qry);
2370 * Collect schema-level data about large objects
2373 getBlobs(Archive *fout)
2375 PQExpBuffer blobQry = createPQExpBuffer();
2377 DumpableObject *bdata;
2382 /* Verbose message */
2384 write_msg(NULL, "reading large objects\n");
2386 /* Make sure we are in proper schema */
2387 selectSourceSchema(fout, "pg_catalog");
2389 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2390 if (fout->remoteVersion >= 90000)
2391 appendPQExpBuffer(blobQry,
2392 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2393 " FROM pg_largeobject_metadata",
2395 else if (fout->remoteVersion >= 70100)
2396 appendPQExpBuffer(blobQry,
2397 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2398 " FROM pg_largeobject");
2400 appendPQExpBuffer(blobQry,
2401 "SELECT oid, NULL::oid, NULL::oid"
2402 " FROM pg_class WHERE relkind = 'l'");
2404 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2406 ntups = PQntuples(res);
2410 * Each large object has its own BLOB archive entry.
2412 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2414 for (i = 0; i < ntups; i++)
2416 binfo[i].dobj.objType = DO_BLOB;
2417 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2418 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2419 AssignDumpId(&binfo[i].dobj);
2421 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2422 if (!PQgetisnull(res, i, 1))
2423 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2425 binfo[i].rolname = "";
2426 if (!PQgetisnull(res, i, 2))
2427 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2429 binfo[i].blobacl = NULL;
2433 * If we have any large objects, a "BLOBS" archive entry is needed.
2434 * This is just a placeholder for sorting; it carries no data now.
2436 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2437 bdata->objType = DO_BLOB_DATA;
2438 bdata->catId = nilCatalogId;
2439 AssignDumpId(bdata);
2440 bdata->name = pg_strdup("BLOBS");
2444 destroyPQExpBuffer(blobQry);
2450 * dump the definition (metadata) of the given large object
2453 dumpBlob(Archive *fout, BlobInfo *binfo)
2455 PQExpBuffer cquery = createPQExpBuffer();
2456 PQExpBuffer dquery = createPQExpBuffer();
2458 appendPQExpBuffer(cquery,
2459 "SELECT pg_catalog.lo_create('%s');\n",
2462 appendPQExpBuffer(dquery,
2463 "SELECT pg_catalog.lo_unlink('%s');\n",
2466 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2469 binfo->rolname, false,
2470 "BLOB", SECTION_PRE_DATA,
2471 cquery->data, dquery->data, NULL,
2475 /* set up tag for comment and/or ACL */
2476 resetPQExpBuffer(cquery);
2477 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2479 /* Dump comment if any */
2480 dumpComment(fout, cquery->data,
2481 NULL, binfo->rolname,
2482 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2484 /* Dump security label if any */
2485 dumpSecLabel(fout, cquery->data,
2486 NULL, binfo->rolname,
2487 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2489 /* Dump ACL if any */
2491 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2492 binfo->dobj.name, NULL, cquery->data,
2493 NULL, binfo->rolname, binfo->blobacl);
2495 destroyPQExpBuffer(cquery);
2496 destroyPQExpBuffer(dquery);
2501 * dump the data contents of all large objects
2504 dumpBlobs(Archive *fout, void *arg)
2506 const char *blobQry;
2507 const char *blobFetchQry;
2508 PGconn *conn = GetConnection(fout);
2510 char buf[LOBBUFSIZE];
2516 write_msg(NULL, "saving large objects\n");
2518 /* Make sure we are in proper schema */
2519 selectSourceSchema(fout, "pg_catalog");
2522 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2523 * the already-in-memory dumpable objects instead...
2525 if (fout->remoteVersion >= 90000)
2526 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2527 else if (fout->remoteVersion >= 70100)
2528 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2530 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2532 ExecuteSqlStatement(fout, blobQry);
2534 /* Command to fetch from cursor */
2535 blobFetchQry = "FETCH 1000 IN bloboid";
2540 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2542 /* Process the tuples, if any */
2543 ntups = PQntuples(res);
2544 for (i = 0; i < ntups; i++)
2549 blobOid = atooid(PQgetvalue(res, i, 0));
2551 loFd = lo_open(conn, blobOid, INV_READ);
2553 exit_horribly(NULL, "could not open large object %u: %s",
2554 blobOid, PQerrorMessage(conn));
2556 StartBlob(fout, blobOid);
2558 /* Now read it in chunks, sending data to archive */
2561 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2563 exit_horribly(NULL, "error reading large object %u: %s",
2564 blobOid, PQerrorMessage(conn));
2566 WriteData(fout, buf, cnt);
2569 lo_close(conn, loFd);
2571 EndBlob(fout, blobOid);
2575 } while (ntups > 0);
2581 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2582 PQExpBuffer upgrade_buffer,
2585 PQExpBuffer upgrade_query = createPQExpBuffer();
2586 PGresult *upgrade_res;
2587 Oid pg_type_array_oid;
2589 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2590 appendPQExpBuffer(upgrade_buffer,
2591 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2594 /* we only support old >= 8.3 for binary upgrades */
2595 appendPQExpBuffer(upgrade_query,
2597 "FROM pg_catalog.pg_type "
2598 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2601 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2603 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2605 if (OidIsValid(pg_type_array_oid))
2607 appendPQExpBuffer(upgrade_buffer,
2608 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2609 appendPQExpBuffer(upgrade_buffer,
2610 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2614 PQclear(upgrade_res);
2615 destroyPQExpBuffer(upgrade_query);
2619 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2620 PQExpBuffer upgrade_buffer,
2623 PQExpBuffer upgrade_query = createPQExpBuffer();
2624 PGresult *upgrade_res;
2626 bool toast_set = false;
2628 /* we only support old >= 8.3 for binary upgrades */
2629 appendPQExpBuffer(upgrade_query,
2630 "SELECT c.reltype AS crel, t.reltype AS trel "
2631 "FROM pg_catalog.pg_class c "
2632 "LEFT JOIN pg_catalog.pg_class t ON "
2633 " (c.reltoastrelid = t.oid) "
2634 "WHERE c.oid = '%u'::pg_catalog.oid;",
2637 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2639 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2641 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2644 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2646 /* Toast tables do not have pg_type array rows */
2647 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2648 PQfnumber(upgrade_res, "trel")));
2650 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2651 appendPQExpBuffer(upgrade_buffer,
2652 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2658 PQclear(upgrade_res);
2659 destroyPQExpBuffer(upgrade_query);
2665 binary_upgrade_set_pg_class_oids(Archive *fout,
2666 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2669 PQExpBuffer upgrade_query = createPQExpBuffer();
2670 PGresult *upgrade_res;
2671 Oid pg_class_reltoastrelid;
2672 Oid pg_class_reltoastidxid;
2674 appendPQExpBuffer(upgrade_query,
2675 "SELECT c.reltoastrelid, t.reltoastidxid "
2676 "FROM pg_catalog.pg_class c LEFT JOIN "
2677 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2678 "WHERE c.oid = '%u'::pg_catalog.oid;",
2681 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2683 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2684 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2686 appendPQExpBuffer(upgrade_buffer,
2687 "\n-- For binary upgrade, must preserve pg_class oids\n");
2691 appendPQExpBuffer(upgrade_buffer,
2692 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2694 /* only tables have toast tables, not indexes */
2695 if (OidIsValid(pg_class_reltoastrelid))
2698 * One complexity is that the table definition might not require
2699 * the creation of a TOAST table, and the TOAST table might have
2700 * been created long after table creation, when the table was
2701 * loaded with wide data. By setting the TOAST oid we force
2702 * creation of the TOAST heap and TOAST index by the backend so we
2703 * can cleanly copy the files during binary upgrade.
2706 appendPQExpBuffer(upgrade_buffer,
2707 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2708 pg_class_reltoastrelid);
2710 /* every toast table has an index */
2711 appendPQExpBuffer(upgrade_buffer,
2712 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2713 pg_class_reltoastidxid);
2717 appendPQExpBuffer(upgrade_buffer,
2718 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2721 appendPQExpBuffer(upgrade_buffer, "\n");
2723 PQclear(upgrade_res);
2724 destroyPQExpBuffer(upgrade_query);
2728 * If the DumpableObject is a member of an extension, add a suitable
2729 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2732 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2733 DumpableObject *dobj,
2734 const char *objlabel)
2736 DumpableObject *extobj = NULL;
2739 if (!dobj->ext_member)
2743 * Find the parent extension. We could avoid this search if we wanted to
2744 * add a link field to DumpableObject, but the space costs of that would
2745 * be considerable. We assume that member objects could only have a
2746 * direct dependency on their own extension, not any others.
2748 for (i = 0; i < dobj->nDeps; i++)
2750 extobj = findObjectByDumpId(dobj->dependencies[i]);
2751 if (extobj && extobj->objType == DO_EXTENSION)
2756 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2758 appendPQExpBuffer(upgrade_buffer,
2759 "\n-- For binary upgrade, handle extension membership the hard way\n");
2760 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2761 fmtId(extobj->name),
2767 * read all namespaces in the system catalogs and return them in the
2768 * NamespaceInfo* structure
2770 * numNamespaces is set to the number of namespaces read in
2773 getNamespaces(Archive *fout, int *numNamespaces)
2779 NamespaceInfo *nsinfo;
2787 * Before 7.3, there are no real namespaces; create two dummy entries, one
2788 * for user stuff and one for system stuff.
2790 if (fout->remoteVersion < 70300)
2792 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2794 nsinfo[0].dobj.objType = DO_NAMESPACE;
2795 nsinfo[0].dobj.catId.tableoid = 0;
2796 nsinfo[0].dobj.catId.oid = 0;
2797 AssignDumpId(&nsinfo[0].dobj);
2798 nsinfo[0].dobj.name = pg_strdup("public");
2799 nsinfo[0].rolname = pg_strdup("");
2800 nsinfo[0].nspacl = pg_strdup("");
2802 selectDumpableNamespace(&nsinfo[0]);
2804 nsinfo[1].dobj.objType = DO_NAMESPACE;
2805 nsinfo[1].dobj.catId.tableoid = 0;
2806 nsinfo[1].dobj.catId.oid = 1;
2807 AssignDumpId(&nsinfo[1].dobj);
2808 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2809 nsinfo[1].rolname = pg_strdup("");
2810 nsinfo[1].nspacl = pg_strdup("");
2812 selectDumpableNamespace(&nsinfo[1]);
2819 query = createPQExpBuffer();
2821 /* Make sure we are in proper schema */
2822 selectSourceSchema(fout, "pg_catalog");
2825 * we fetch all namespaces including system ones, so that every object we
2826 * read in can be linked to a containing namespace.
2828 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2829 "(%s nspowner) AS rolname, "
2830 "nspacl FROM pg_namespace",
2833 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2835 ntups = PQntuples(res);
2837 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2839 i_tableoid = PQfnumber(res, "tableoid");
2840 i_oid = PQfnumber(res, "oid");
2841 i_nspname = PQfnumber(res, "nspname");
2842 i_rolname = PQfnumber(res, "rolname");
2843 i_nspacl = PQfnumber(res, "nspacl");
2845 for (i = 0; i < ntups; i++)
2847 nsinfo[i].dobj.objType = DO_NAMESPACE;
2848 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2849 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2850 AssignDumpId(&nsinfo[i].dobj);
2851 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2852 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2853 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2855 /* Decide whether to dump this namespace */
2856 selectDumpableNamespace(&nsinfo[i]);
2858 if (strlen(nsinfo[i].rolname) == 0)
2859 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2860 nsinfo[i].dobj.name);
2864 destroyPQExpBuffer(query);
2866 *numNamespaces = ntups;
2873 * given a namespace OID and an object OID, look up the info read by
2876 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2877 * a system object or not. In 7.3 and later there is no guessing, and we
2878 * don't use objoid at all.
2880 static NamespaceInfo *
2881 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2883 NamespaceInfo *nsinfo;
2885 if (fout->remoteVersion >= 70300)
2887 nsinfo = findNamespaceByOid(nsoid);
2891 /* This code depends on the dummy objects set up by getNamespaces. */
2894 if (objoid > g_last_builtin_oid)
2895 i = 0; /* user object */
2897 i = 1; /* system object */
2898 nsinfo = findNamespaceByOid(i);
2902 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
2909 * read all extensions in the system catalogs and return them in the
2910 * ExtensionInfo* structure
2912 * numExtensions is set to the number of extensions read in
2915 getExtensions(Archive *fout, int *numExtensions)
2921 ExtensionInfo *extinfo;
2926 int i_extrelocatable;
2932 * Before 9.1, there are no extensions.
2934 if (fout->remoteVersion < 90100)
2940 query = createPQExpBuffer();
2942 /* Make sure we are in proper schema */
2943 selectSourceSchema(fout, "pg_catalog");
2945 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2946 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2947 "FROM pg_extension x "
2948 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2950 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2952 ntups = PQntuples(res);
2954 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2956 i_tableoid = PQfnumber(res, "tableoid");
2957 i_oid = PQfnumber(res, "oid");
2958 i_extname = PQfnumber(res, "extname");
2959 i_nspname = PQfnumber(res, "nspname");
2960 i_extrelocatable = PQfnumber(res, "extrelocatable");
2961 i_extversion = PQfnumber(res, "extversion");
2962 i_extconfig = PQfnumber(res, "extconfig");
2963 i_extcondition = PQfnumber(res, "extcondition");
2965 for (i = 0; i < ntups; i++)
2967 extinfo[i].dobj.objType = DO_EXTENSION;
2968 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2969 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2970 AssignDumpId(&extinfo[i].dobj);
2971 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2972 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2973 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2974 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2975 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2976 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2978 /* Decide whether we want to dump it */
2979 selectDumpableExtension(&(extinfo[i]));
2983 destroyPQExpBuffer(query);
2985 *numExtensions = ntups;
2992 * read all types in the system catalogs and return them in the
2993 * TypeInfo* structure
2995 * numTypes is set to the number of types read in
2997 * NB: this must run after getFuncs() because we assume we can do
3001 getTypes(Archive *fout, int *numTypes)
3006 PQExpBuffer query = createPQExpBuffer();
3008 ShellTypeInfo *stinfo;
3025 * we include even the built-in types because those may be used as array
3026 * elements by user-defined types
3028 * we filter out the built-in types when we dump out the types
3030 * same approach for undefined (shell) types and array types
3032 * Note: as of 8.3 we can reliably detect whether a type is an
3033 * auto-generated array type by checking the element type's typarray.
3034 * (Before that the test is capable of generating false positives.) We
3035 * still check for name beginning with '_', though, so as to avoid the
3036 * cost of the subselect probe for all standard types. This would have to
3037 * be revisited if the backend ever allows renaming of array types.
3040 /* Make sure we are in proper schema */
3041 selectSourceSchema(fout, "pg_catalog");
3043 if (fout->remoteVersion >= 90200)
3045 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3046 "typnamespace, typacl, "
3047 "(%s typowner) AS rolname, "
3048 "typinput::oid AS typinput, "
3049 "typoutput::oid AS typoutput, typelem, typrelid, "
3050 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3051 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3052 "typtype, typisdefined, "
3053 "typname[0] = '_' AND typelem != 0 AND "
3054 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3058 else if (fout->remoteVersion >= 80300)
3060 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3061 "typnamespace, '{=U}' AS typacl, "
3062 "(%s typowner) AS rolname, "
3063 "typinput::oid AS typinput, "
3064 "typoutput::oid AS typoutput, typelem, typrelid, "
3065 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3066 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3067 "typtype, typisdefined, "
3068 "typname[0] = '_' AND typelem != 0 AND "
3069 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3073 else if (fout->remoteVersion >= 70300)
3075 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3076 "typnamespace, '{=U}' AS typacl, "
3077 "(%s typowner) AS rolname, "
3078 "typinput::oid AS typinput, "
3079 "typoutput::oid AS typoutput, typelem, typrelid, "
3080 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3081 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3082 "typtype, typisdefined, "
3083 "typname[0] = '_' AND typelem != 0 AS isarray "
3087 else if (fout->remoteVersion >= 70100)
3089 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3090 "0::oid AS typnamespace, '{=U}' AS typacl, "
3091 "(%s typowner) AS rolname, "
3092 "typinput::oid AS typinput, "
3093 "typoutput::oid AS typoutput, typelem, typrelid, "
3094 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3095 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3096 "typtype, typisdefined, "
3097 "typname[0] = '_' AND typelem != 0 AS isarray "
3103 appendPQExpBuffer(query, "SELECT "
3104 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
3106 "0::oid AS typnamespace, '{=U}' AS typacl, "
3107 "(%s typowner) AS rolname, "
3108 "typinput::oid AS typinput, "
3109 "typoutput::oid AS typoutput, typelem, typrelid, "
3110 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3111 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3112 "typtype, typisdefined, "
3113 "typname[0] = '_' AND typelem != 0 AS isarray "
3118 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3120 ntups = PQntuples(res);
3122 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3124 i_tableoid = PQfnumber(res, "tableoid");
3125 i_oid = PQfnumber(res, "oid");
3126 i_typname = PQfnumber(res, "typname");
3127 i_typnamespace = PQfnumber(res, "typnamespace");
3128 i_typacl = PQfnumber(res, "typacl");
3129 i_rolname = PQfnumber(res, "rolname");
3130 i_typinput = PQfnumber(res, "typinput");
3131 i_typoutput = PQfnumber(res, "typoutput");
3132 i_typelem = PQfnumber(res, "typelem");
3133 i_typrelid = PQfnumber(res, "typrelid");
3134 i_typrelkind = PQfnumber(res, "typrelkind");
3135 i_typtype = PQfnumber(res, "typtype");
3136 i_typisdefined = PQfnumber(res, "typisdefined");
3137 i_isarray = PQfnumber(res, "isarray");
3139 for (i = 0; i < ntups; i++)
3141 tyinfo[i].dobj.objType = DO_TYPE;
3142 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3143 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3144 AssignDumpId(&tyinfo[i].dobj);
3145 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3146 tyinfo[i].dobj.namespace =
3148 atooid(PQgetvalue(res, i, i_typnamespace)),
3149 tyinfo[i].dobj.catId.oid);
3150 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3151 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
3152 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3153 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3154 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3155 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3156 tyinfo[i].shellType = NULL;
3158 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3159 tyinfo[i].isDefined = true;
3161 tyinfo[i].isDefined = false;
3163 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3164 tyinfo[i].isArray = true;
3166 tyinfo[i].isArray = false;
3168 /* Decide whether we want to dump it */
3169 selectDumpableType(&tyinfo[i]);
3172 * If it's a domain, fetch info about its constraints, if any
3174 tyinfo[i].nDomChecks = 0;
3175 tyinfo[i].domChecks = NULL;
3176 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3177 getDomainConstraints(fout, &(tyinfo[i]));
3180 * If it's a base type, make a DumpableObject representing a shell
3181 * definition of the type. We will need to dump that ahead of the I/O
3182 * functions for the type. Similarly, range types need a shell
3183 * definition in case they have a canonicalize function.
3185 * Note: the shell type doesn't have a catId. You might think it
3186 * should copy the base type's catId, but then it might capture the
3187 * pg_depend entries for the type, which we don't want.
3189 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3190 tyinfo[i].typtype == TYPTYPE_RANGE))
3192 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3193 stinfo->dobj.objType = DO_SHELL_TYPE;
3194 stinfo->dobj.catId = nilCatalogId;
3195 AssignDumpId(&stinfo->dobj);
3196 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3197 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3198 stinfo->baseType = &(tyinfo[i]);
3199 tyinfo[i].shellType = stinfo;
3202 * Initially mark the shell type as not to be dumped. We'll only
3203 * dump it if the I/O or canonicalize functions need to be dumped;
3204 * this is taken care of while sorting dependencies.
3206 stinfo->dobj.dump = false;
3209 * However, if dumping from pre-7.3, there will be no dependency
3210 * info so we have to fake it here. We only need to worry about
3211 * typinput and typoutput since the other functions only exist
3214 if (fout->remoteVersion < 70300)
3220 typinput = atooid(PQgetvalue(res, i, i_typinput));
3221 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3223 funcInfo = findFuncByOid(typinput);
3224 if (funcInfo && funcInfo->dobj.dump)
3226 /* base type depends on function */
3227 addObjectDependency(&tyinfo[i].dobj,
3228 funcInfo->dobj.dumpId);
3229 /* function depends on shell type */
3230 addObjectDependency(&funcInfo->dobj,
3231 stinfo->dobj.dumpId);
3232 /* mark shell type as to be dumped */
3233 stinfo->dobj.dump = true;
3236 funcInfo = findFuncByOid(typoutput);
3237 if (funcInfo && funcInfo->dobj.dump)
3239 /* base type depends on function */
3240 addObjectDependency(&tyinfo[i].dobj,
3241 funcInfo->dobj.dumpId);
3242 /* function depends on shell type */
3243 addObjectDependency(&funcInfo->dobj,
3244 stinfo->dobj.dumpId);
3245 /* mark shell type as to be dumped */
3246 stinfo->dobj.dump = true;
3251 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3252 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3253 tyinfo[i].dobj.name);
3260 destroyPQExpBuffer(query);
3267 * read all operators in the system catalogs and return them in the
3268 * OprInfo* structure
3270 * numOprs is set to the number of operators read in
3273 getOperators(Archive *fout, int *numOprs)
3278 PQExpBuffer query = createPQExpBuffer();
3289 * find all operators, including builtin operators; we filter out
3290 * system-defined operators at dump-out time.
3293 /* Make sure we are in proper schema */
3294 selectSourceSchema(fout, "pg_catalog");
3296 if (fout->remoteVersion >= 70300)
3298 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3300 "(%s oprowner) AS rolname, "
3302 "oprcode::oid AS oprcode "
3306 else if (fout->remoteVersion >= 70100)
3308 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3309 "0::oid AS oprnamespace, "
3310 "(%s oprowner) AS rolname, "
3312 "oprcode::oid AS oprcode "
3318 appendPQExpBuffer(query, "SELECT "
3319 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3321 "0::oid AS oprnamespace, "
3322 "(%s oprowner) AS rolname, "
3324 "oprcode::oid AS oprcode "
3329 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3331 ntups = PQntuples(res);
3334 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3336 i_tableoid = PQfnumber(res, "tableoid");
3337 i_oid = PQfnumber(res, "oid");
3338 i_oprname = PQfnumber(res, "oprname");
3339 i_oprnamespace = PQfnumber(res, "oprnamespace");
3340 i_rolname = PQfnumber(res, "rolname");
3341 i_oprkind = PQfnumber(res, "oprkind");
3342 i_oprcode = PQfnumber(res, "oprcode");
3344 for (i = 0; i < ntups; i++)
3346 oprinfo[i].dobj.objType = DO_OPERATOR;
3347 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3348 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3349 AssignDumpId(&oprinfo[i].dobj);
3350 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3351 oprinfo[i].dobj.namespace =
3353 atooid(PQgetvalue(res, i, i_oprnamespace)),
3354 oprinfo[i].dobj.catId.oid);
3355 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3356 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3357 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3359 /* Decide whether we want to dump it */
3360 selectDumpableObject(&(oprinfo[i].dobj));
3362 if (strlen(oprinfo[i].rolname) == 0)
3363 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3364 oprinfo[i].dobj.name);
3369 destroyPQExpBuffer(query);
3376 * read all collations in the system catalogs and return them in the
3377 * CollInfo* structure
3379 * numCollations is set to the number of collations read in
3382 getCollations(Archive *fout, int *numCollations)
3392 int i_collnamespace;
3395 /* Collations didn't exist pre-9.1 */
3396 if (fout->remoteVersion < 90100)
3402 query = createPQExpBuffer();
3405 * find all collations, including builtin collations; we filter out
3406 * system-defined collations at dump-out time.
3409 /* Make sure we are in proper schema */
3410 selectSourceSchema(fout, "pg_catalog");
3412 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3414 "(%s collowner) AS rolname "
3415 "FROM pg_collation",
3418 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3420 ntups = PQntuples(res);
3421 *numCollations = ntups;
3423 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3425 i_tableoid = PQfnumber(res, "tableoid");
3426 i_oid = PQfnumber(res, "oid");
3427 i_collname = PQfnumber(res, "collname");
3428 i_collnamespace = PQfnumber(res, "collnamespace");
3429 i_rolname = PQfnumber(res, "rolname");
3431 for (i = 0; i < ntups; i++)
3433 collinfo[i].dobj.objType = DO_COLLATION;
3434 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3435 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3436 AssignDumpId(&collinfo[i].dobj);
3437 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3438 collinfo[i].dobj.namespace =
3440 atooid(PQgetvalue(res, i, i_collnamespace)),
3441 collinfo[i].dobj.catId.oid);
3442 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3444 /* Decide whether we want to dump it */
3445 selectDumpableObject(&(collinfo[i].dobj));
3450 destroyPQExpBuffer(query);
3457 * read all conversions in the system catalogs and return them in the
3458 * ConvInfo* structure
3460 * numConversions is set to the number of conversions read in
3463 getConversions(Archive *fout, int *numConversions)
3468 PQExpBuffer query = createPQExpBuffer();
3476 /* Conversions didn't exist pre-7.3 */
3477 if (fout->remoteVersion < 70300)
3479 *numConversions = 0;
3484 * find all conversions, including builtin conversions; we filter out
3485 * system-defined conversions at dump-out time.
3488 /* Make sure we are in proper schema */
3489 selectSourceSchema(fout, "pg_catalog");
3491 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3493 "(%s conowner) AS rolname "
3494 "FROM pg_conversion",
3497 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3499 ntups = PQntuples(res);
3500 *numConversions = ntups;
3502 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3504 i_tableoid = PQfnumber(res, "tableoid");
3505 i_oid = PQfnumber(res, "oid");
3506 i_conname = PQfnumber(res, "conname");
3507 i_connamespace = PQfnumber(res, "connamespace");
3508 i_rolname = PQfnumber(res, "rolname");
3510 for (i = 0; i < ntups; i++)
3512 convinfo[i].dobj.objType = DO_CONVERSION;
3513 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3514 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3515 AssignDumpId(&convinfo[i].dobj);
3516 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3517 convinfo[i].dobj.namespace =
3519 atooid(PQgetvalue(res, i, i_connamespace)),
3520 convinfo[i].dobj.catId.oid);
3521 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3523 /* Decide whether we want to dump it */
3524 selectDumpableObject(&(convinfo[i].dobj));
3529 destroyPQExpBuffer(query);
3536 * read all opclasses in the system catalogs and return them in the
3537 * OpclassInfo* structure
3539 * numOpclasses is set to the number of opclasses read in
3542 getOpclasses(Archive *fout, int *numOpclasses)
3547 PQExpBuffer query = createPQExpBuffer();
3548 OpclassInfo *opcinfo;
3556 * find all opclasses, including builtin opclasses; we filter out
3557 * system-defined opclasses at dump-out time.
3560 /* Make sure we are in proper schema */
3561 selectSourceSchema(fout, "pg_catalog");
3563 if (fout->remoteVersion >= 70300)
3565 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3567 "(%s opcowner) AS rolname "
3571 else if (fout->remoteVersion >= 70100)
3573 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3574 "0::oid AS opcnamespace, "
3575 "''::name AS rolname "
3580 appendPQExpBuffer(query, "SELECT "
3581 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3583 "0::oid AS opcnamespace, "
3584 "''::name AS rolname "
3588 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3590 ntups = PQntuples(res);
3591 *numOpclasses = ntups;
3593 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3595 i_tableoid = PQfnumber(res, "tableoid");
3596 i_oid = PQfnumber(res, "oid");
3597 i_opcname = PQfnumber(res, "opcname");
3598 i_opcnamespace = PQfnumber(res, "opcnamespace");
3599 i_rolname = PQfnumber(res, "rolname");
3601 for (i = 0; i < ntups; i++)
3603 opcinfo[i].dobj.objType = DO_OPCLASS;
3604 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3605 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3606 AssignDumpId(&opcinfo[i].dobj);
3607 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3608 opcinfo[i].dobj.namespace =
3610 atooid(PQgetvalue(res, i, i_opcnamespace)),
3611 opcinfo[i].dobj.catId.oid);
3612 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3614 /* Decide whether we want to dump it */
3615 selectDumpableObject(&(opcinfo[i].dobj));
3617 if (fout->remoteVersion >= 70300)
3619 if (strlen(opcinfo[i].rolname) == 0)
3620 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3621 opcinfo[i].dobj.name);
3627 destroyPQExpBuffer(query);
3634 * read all opfamilies in the system catalogs and return them in the
3635 * OpfamilyInfo* structure
3637 * numOpfamilies is set to the number of opfamilies read in
3640 getOpfamilies(Archive *fout, int *numOpfamilies)
3646 OpfamilyInfo *opfinfo;
3653 /* Before 8.3, there is no separate concept of opfamilies */
3654 if (fout->remoteVersion < 80300)
3660 query = createPQExpBuffer();
3663 * find all opfamilies, including builtin opfamilies; we filter out
3664 * system-defined opfamilies at dump-out time.
3667 /* Make sure we are in proper schema */
3668 selectSourceSchema(fout, "pg_catalog");
3670 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3672 "(%s opfowner) AS rolname "
3676 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3678 ntups = PQntuples(res);
3679 *numOpfamilies = ntups;
3681 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3683 i_tableoid = PQfnumber(res, "tableoid");
3684 i_oid = PQfnumber(res, "oid");
3685 i_opfname = PQfnumber(res, "opfname");
3686 i_opfnamespace = PQfnumber(res, "opfnamespace");
3687 i_rolname = PQfnumber(res, "rolname");
3689 for (i = 0; i < ntups; i++)
3691 opfinfo[i].dobj.objType = DO_OPFAMILY;
3692 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3693 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3694 AssignDumpId(&opfinfo[i].dobj);
3695 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3696 opfinfo[i].dobj.namespace =
3698 atooid(PQgetvalue(res, i, i_opfnamespace)),
3699 opfinfo[i].dobj.catId.oid);
3700 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3702 /* Decide whether we want to dump it */
3703 selectDumpableObject(&(opfinfo[i].dobj));
3705 if (fout->remoteVersion >= 70300)
3707 if (strlen(opfinfo[i].rolname) == 0)
3708 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3709 opfinfo[i].dobj.name);
3715 destroyPQExpBuffer(query);
3722 * read all the user-defined aggregates in the system catalogs and
3723 * return them in the AggInfo* structure
3725 * numAggs is set to the number of aggregates read in
3728 getAggregates(Archive *fout, int *numAggs)
3733 PQExpBuffer query = createPQExpBuffer();
3745 /* Make sure we are in proper schema */
3746 selectSourceSchema(fout, "pg_catalog");
3749 * Find all user-defined aggregates. See comment in getFuncs() for the
3750 * rationale behind the filtering logic.
3753 if (fout->remoteVersion >= 80400)
3755 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3756 "pronamespace AS aggnamespace, "
3757 "pronargs, proargtypes, "
3758 "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3759 "(%s proowner) AS rolname, "
3762 "WHERE proisagg AND ("
3764 "(SELECT oid FROM pg_namespace "
3765 "WHERE nspname = 'pg_catalog')",
3767 if (binary_upgrade && fout->remoteVersion >= 90100)
3768 appendPQExpBuffer(query,
3769 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3770 "classid = 'pg_proc'::regclass AND "
3771 "objid = p.oid AND "
3772 "refclassid = 'pg_extension'::regclass AND "
3774 appendPQExpBuffer(query, ")");
3776 else if (fout->remoteVersion >= 80200)
3778 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3779 "pronamespace AS aggnamespace, "
3780 "pronargs, proargtypes, "
3781 "NULL::text AS proiargs,"
3782 "(%s proowner) AS rolname, "
3785 "WHERE proisagg AND ("
3787 "(SELECT oid FROM pg_namespace "
3788 "WHERE nspname = 'pg_catalog'))",
3791 else if (fout->remoteVersion >= 70300)
3793 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3794 "pronamespace AS aggnamespace, "
3795 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3797 "NULL::text AS proiargs, "
3798 "(%s proowner) AS rolname, "
3802 "AND pronamespace != "
3803 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3806 else if (fout->remoteVersion >= 70100)
3808 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3809 "0::oid AS aggnamespace, "
3810 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3811 "aggbasetype AS proargtypes, "
3812 "NULL::text AS proiargs, "
3813 "(%s aggowner) AS rolname, "
3815 "FROM pg_aggregate "
3816 "where oid > '%u'::oid",
3818 g_last_builtin_oid);
3822 appendPQExpBuffer(query, "SELECT "
3823 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3825 "0::oid AS aggnamespace, "
3826 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3827 "aggbasetype AS proargtypes, "
3828 "NULL::text AS proiargs, "
3829 "(%s aggowner) AS rolname, "
3831 "FROM pg_aggregate "
3832 "where oid > '%u'::oid",
3834 g_last_builtin_oid);
3837 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3839 ntups = PQntuples(res);
3842 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3844 i_tableoid = PQfnumber(res, "tableoid");
3845 i_oid = PQfnumber(res, "oid");
3846 i_aggname = PQfnumber(res, "aggname");
3847 i_aggnamespace = PQfnumber(res, "aggnamespace");
3848 i_pronargs = PQfnumber(res, "pronargs");
3849 i_proargtypes = PQfnumber(res, "proargtypes");
3850 i_rolname = PQfnumber(res, "rolname");
3851 i_aggacl = PQfnumber(res, "aggacl");
3852 i_proiargs = PQfnumber(res, "proiargs");
3854 for (i = 0; i < ntups; i++)
3856 agginfo[i].aggfn.dobj.objType = DO_AGG;
3857 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3858 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3859 AssignDumpId(&agginfo[i].aggfn.dobj);
3860 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3861 agginfo[i].aggfn.dobj.namespace =
3863 atooid(PQgetvalue(res, i, i_aggnamespace)),
3864 agginfo[i].aggfn.dobj.catId.oid);
3865 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3866 if (strlen(agginfo[i].aggfn.rolname) == 0)
3867 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3868 agginfo[i].aggfn.dobj.name);
3869 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3870 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3871 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3872 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3873 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3874 if (agginfo[i].aggfn.nargs == 0)
3875 agginfo[i].aggfn.argtypes = NULL;
3878 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3879 if (fout->remoteVersion >= 70300)
3880 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3881 agginfo[i].aggfn.argtypes,
3882 agginfo[i].aggfn.nargs);
3884 /* it's just aggbasetype */
3885 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3888 /* Decide whether we want to dump it */
3889 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3894 destroyPQExpBuffer(query);
3901 * read all the user-defined functions in the system catalogs and
3902 * return them in the FuncInfo* structure
3904 * numFuncs is set to the number of functions read in
3907 getFuncs(Archive *fout, int *numFuncs)
3912 PQExpBuffer query = createPQExpBuffer();
3926 /* Make sure we are in proper schema */
3927 selectSourceSchema(fout, "pg_catalog");
3930 * Find all user-defined functions. Normally we can exclude functions in
3931 * pg_catalog, which is worth doing since there are several thousand of
3932 * 'em. However, there are some extensions that create functions in
3933 * pg_catalog. In normal dumps we can still ignore those --- but in
3934 * binary-upgrade mode, we must dump the member objects of the extension,
3935 * so be sure to fetch any such functions.
3937 * Also, in 9.2 and up, exclude functions that are internally dependent on
3938 * something else, since presumably those will be created as a result of
3939 * creating the something else. This currently only acts to suppress
3940 * constructor functions for range types. Note that this is OK only
3941 * because the constructors don't have any dependencies the range type
3942 * doesn't have; otherwise we might not get creation ordering correct.
3945 if (fout->remoteVersion >= 80400)
3947 appendPQExpBuffer(query,
3948 "SELECT tableoid, oid, proname, prolang, "
3949 "pronargs, proargtypes, prorettype, proacl, "
3951 "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3952 "(%s proowner) AS rolname "
3954 "WHERE NOT proisagg AND ("
3956 "(SELECT oid FROM pg_namespace "
3957 "WHERE nspname = 'pg_catalog')",
3959 if (fout->remoteVersion >= 90200)
3960 appendPQExpBuffer(query,
3961 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3962 "WHERE classid = 'pg_proc'::regclass AND "
3963 "objid = p.oid AND deptype = 'i')");
3964 if (binary_upgrade && fout->remoteVersion >= 90100)
3965 appendPQExpBuffer(query,
3966 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3967 "classid = 'pg_proc'::regclass AND "
3968 "objid = p.oid AND "
3969 "refclassid = 'pg_extension'::regclass AND "
3971 appendPQExpBuffer(query, ")");
3973 else if (fout->remoteVersion >= 70300)
3975 appendPQExpBuffer(query,
3976 "SELECT tableoid, oid, proname, prolang, "
3977 "pronargs, proargtypes, prorettype, proacl, "
3979 "NULL::text AS proiargs,"
3980 "(%s proowner) AS rolname "
3982 "WHERE NOT proisagg AND ("
3984 "(SELECT oid FROM pg_namespace "
3985 "WHERE nspname = 'pg_catalog'))",
3988 else if (fout->remoteVersion >= 70100)
3990 appendPQExpBuffer(query,
3991 "SELECT tableoid, oid, proname, prolang, "
3992 "pronargs, proargtypes, prorettype, "
3993 "'{=X}' AS proacl, "
3994 "0::oid AS pronamespace, "
3995 "NULL::text AS proiargs,"
3996 "(%s proowner) AS rolname "
3998 "WHERE pg_proc.oid > '%u'::oid",
4000 g_last_builtin_oid);
4004 appendPQExpBuffer(query,
4006 "(SELECT oid FROM pg_class "
4007 " WHERE relname = 'pg_proc') AS tableoid, "
4008 "oid, proname, prolang, "
4009 "pronargs, proargtypes, prorettype, "
4010 "'{=X}' AS proacl, "
4011 "0::oid AS pronamespace, "
4012 "NULL::text AS proiargs,"
4013 "(%s proowner) AS rolname "
4015 "where pg_proc.oid > '%u'::oid",
4017 g_last_builtin_oid);
4020 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4022 ntups = PQntuples(res);
4026 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
4028 i_tableoid = PQfnumber(res, "tableoid");
4029 i_oid = PQfnumber(res, "oid");
4030 i_proname = PQfnumber(res, "proname");
4031 i_pronamespace = PQfnumber(res, "pronamespace");
4032 i_rolname = PQfnumber(res, "rolname");
4033 i_prolang = PQfnumber(res, "prolang");
4034 i_pronargs = PQfnumber(res, "pronargs");
4035 i_proargtypes = PQfnumber(res, "proargtypes");
4036 i_prorettype = PQfnumber(res, "prorettype");
4037 i_proacl = PQfnumber(res, "proacl");
4038 i_proiargs = PQfnumber(res, "proiargs");
4040 for (i = 0; i < ntups; i++)
4042 finfo[i].dobj.objType = DO_FUNC;
4043 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4044 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4045 AssignDumpId(&finfo[i].dobj);
4046 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
4047 finfo[i].dobj.namespace =
4049 atooid(PQgetvalue(res, i, i_pronamespace)),
4050 finfo[i].dobj.catId.oid);
4051 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4052 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
4053 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
4054 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
4055 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
4056 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
4057 if (finfo[i].nargs == 0)
4058 finfo[i].argtypes = NULL;
4061 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
4062 parseOidArray(PQgetvalue(res, i, i_proargtypes),
4063 finfo[i].argtypes, finfo[i].nargs);
4066 /* Decide whether we want to dump it */
4067 selectDumpableObject(&(finfo[i].dobj));
4069 if (strlen(finfo[i].rolname) == 0)
4071 "WARNING: owner of function \"%s\" appears to be invalid\n",
4072 finfo[i].dobj.name);
4077 destroyPQExpBuffer(query);
4084 * read all the user-defined tables (no indexes, no catalogs)
4085 * in the system catalogs return them in the TableInfo* structure
4087 * numTables is set to the number of tables read in
4090 getTables(Archive *fout, int *numTables)
4095 PQExpBuffer query = createPQExpBuffer();
4105 int i_relhastriggers;
4111 int i_toastfrozenxid;
4112 int i_relpersistence;
4116 int i_reltablespace;
4118 int i_toastreloptions;
4121 /* Make sure we are in proper schema */
4122 selectSourceSchema(fout, "pg_catalog");
4125 * Find all the tables and table-like objects.
4127 * We include system catalogs, so that we can work if a user table is
4128 * defined to inherit from a system catalog (pretty weird, but...)
4130 * We ignore relations that are not ordinary tables, sequences, views,
4131 * materialized views, composite types, or foreign tables.
4133 * Composite-type table entries won't be dumped as such, but we have to
4134 * make a DumpableObject for them so that we can track dependencies of the
4135 * composite type (pg_depend entries for columns of the composite type
4136 * link to the pg_class entry not the pg_type entry).
4138 * Note: in this phase we should collect only a minimal amount of
4139 * information about each table, basically just enough to decide if it is
4140 * interesting. We must fetch all tables in this phase because otherwise
4141 * we cannot correctly identify inherited columns, owned sequences, etc.
4144 if (fout->remoteVersion >= 90100)
4147 * Left join to pick up dependency info linking sequences to their
4148 * owning column, if any (note this dependency is AUTO as of 8.2)
4150 appendPQExpBuffer(query,
4151 "SELECT c.tableoid, c.oid, c.relname, "
4152 "c.relacl, c.relkind, c.relnamespace, "
4153 "(%s c.relowner) AS rolname, "
4154 "c.relchecks, c.relhastriggers, "
4155 "c.relhasindex, c.relhasrules, c.relhasoids, "
4156 "c.relfrozenxid, tc.oid AS toid, "
4157 "tc.relfrozenxid AS tfrozenxid, "
4158 "c.relpersistence, pg_relation_is_scannable(c.oid) as isscannable, "
4159 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4160 "d.refobjid AS owning_tab, "
4161 "d.refobjsubid AS owning_col, "
4162 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4163 "array_to_string(c.reloptions, ', ') AS reloptions, "
4164 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4166 "LEFT JOIN pg_depend d ON "
4167 "(c.relkind = '%c' AND "
4168 "d.classid = c.tableoid AND d.objid = c.oid AND "
4169 "d.objsubid = 0 AND "
4170 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4171 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4172 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4176 RELKIND_RELATION, RELKIND_SEQUENCE,
4177 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4178 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4180 else if (fout->remoteVersion >= 90000)
4183 * Left join to pick up dependency info linking sequences to their
4184 * owning column, if any (note this dependency is AUTO as of 8.2)
4186 appendPQExpBuffer(query,
4187 "SELECT c.tableoid, c.oid, c.relname, "
4188 "c.relacl, c.relkind, c.relnamespace, "
4189 "(%s c.relowner) AS rolname, "
4190 "c.relchecks, c.relhastriggers, "
4191 "c.relhasindex, c.relhasrules, c.relhasoids, "
4192 "c.relfrozenxid, tc.oid AS toid, "
4193 "tc.relfrozenxid AS tfrozenxid, "
4194 "'p' AS relpersistence, 't'::bool as isscannable, "
4195 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4196 "d.refobjid AS owning_tab, "
4197 "d.refobjsubid AS owning_col, "
4198 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4199 "array_to_string(c.reloptions, ', ') AS reloptions, "
4200 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4202 "LEFT JOIN pg_depend d ON "
4203 "(c.relkind = '%c' AND "
4204 "d.classid = c.tableoid AND d.objid = c.oid AND "
4205 "d.objsubid = 0 AND "
4206 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4207 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4208 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4212 RELKIND_RELATION, RELKIND_SEQUENCE,
4213 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4215 else if (fout->remoteVersion >= 80400)
4218 * Left join to pick up dependency info linking sequences to their
4219 * owning column, if any (note this dependency is AUTO as of 8.2)
4221 appendPQExpBuffer(query,
4222 "SELECT c.tableoid, c.oid, c.relname, "
4223 "c.relacl, c.relkind, c.relnamespace, "
4224 "(%s c.relowner) AS rolname, "
4225 "c.relchecks, c.relhastriggers, "
4226 "c.relhasindex, c.relhasrules, c.relhasoids, "
4227 "c.relfrozenxid, tc.oid AS toid, "
4228 "tc.relfrozenxid AS tfrozenxid, "
4229 "'p' AS relpersistence, 't'::bool as isscannable, "
4230 "NULL AS reloftype, "
4231 "d.refobjid AS owning_tab, "
4232 "d.refobjsubid AS owning_col, "
4233 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4234 "array_to_string(c.reloptions, ', ') AS reloptions, "
4235 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4237 "LEFT JOIN pg_depend d ON "
4238 "(c.relkind = '%c' AND "
4239 "d.classid = c.tableoid AND d.objid = c.oid AND "
4240 "d.objsubid = 0 AND "
4241 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4242 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4243 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4247 RELKIND_RELATION, RELKIND_SEQUENCE,
4248 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4250 else if (fout->remoteVersion >= 80200)
4253 * Left join to pick up dependency info linking sequences to their
4254 * owning column, if any (note this dependency is AUTO as of 8.2)
4256 appendPQExpBuffer(query,
4257 "SELECT c.tableoid, c.oid, c.relname, "
4258 "c.relacl, c.relkind, c.relnamespace, "
4259 "(%s c.relowner) AS rolname, "
4260 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4261 "c.relhasindex, c.relhasrules, c.relhasoids, "
4262 "c.relfrozenxid, tc.oid AS toid, "
4263 "tc.relfrozenxid AS tfrozenxid, "
4264 "'p' AS relpersistence, 't'::bool as isscannable, "
4265 "NULL AS reloftype, "
4266 "d.refobjid AS owning_tab, "
4267 "d.refobjsubid AS owning_col, "
4268 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4269 "array_to_string(c.reloptions, ', ') AS reloptions, "
4270 "NULL AS toast_reloptions "
4272 "LEFT JOIN pg_depend d ON "
4273 "(c.relkind = '%c' AND "
4274 "d.classid = c.tableoid AND d.objid = c.oid AND "
4275 "d.objsubid = 0 AND "
4276 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4277 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4278 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4282 RELKIND_RELATION, RELKIND_SEQUENCE,
4283 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4285 else if (fout->remoteVersion >= 80000)
4288 * Left join to pick up dependency info linking sequences to their
4289 * owning column, if any
4291 appendPQExpBuffer(query,
4292 "SELECT c.tableoid, c.oid, relname, "
4293 "relacl, relkind, relnamespace, "
4294 "(%s relowner) AS rolname, "
4295 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4296 "relhasindex, relhasrules, relhasoids, "
4297 "0 AS relfrozenxid, "
4300 "'p' AS relpersistence, 't'::bool as isscannable, "
4301 "NULL AS reloftype, "
4302 "d.refobjid AS owning_tab, "
4303 "d.refobjsubid AS owning_col, "
4304 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4305 "NULL AS reloptions, "
4306 "NULL AS toast_reloptions "
4308 "LEFT JOIN pg_depend d ON "
4309 "(c.relkind = '%c' AND "
4310 "d.classid = c.tableoid AND d.objid = c.oid AND "
4311 "d.objsubid = 0 AND "
4312 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4313 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4317 RELKIND_RELATION, RELKIND_SEQUENCE,
4318 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4320 else if (fout->remoteVersion >= 70300)
4323 * Left join to pick up dependency info linking sequences to their
4324 * owning column, if any
4326 appendPQExpBuffer(query,
4327 "SELECT c.tableoid, c.oid, relname, "
4328 "relacl, relkind, relnamespace, "
4329 "(%s relowner) AS rolname, "
4330 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4331 "relhasindex, relhasrules, relhasoids, "
4332 "0 AS relfrozenxid, "
4335 "'p' AS relpersistence, 't'::bool as isscannable, "
4336 "NULL AS reloftype, "
4337 "d.refobjid AS owning_tab, "
4338 "d.refobjsubid AS owning_col, "
4339 "NULL AS reltablespace, "
4340 "NULL AS reloptions, "
4341 "NULL AS toast_reloptions "
4343 "LEFT JOIN pg_depend d ON "
4344 "(c.relkind = '%c' AND "
4345 "d.classid = c.tableoid AND d.objid = c.oid AND "
4346 "d.objsubid = 0 AND "
4347 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4348 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4352 RELKIND_RELATION, RELKIND_SEQUENCE,
4353 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4355 else if (fout->remoteVersion >= 70200)
4357 appendPQExpBuffer(query,
4358 "SELECT tableoid, oid, relname, relacl, relkind, "
4359 "0::oid AS relnamespace, "
4360 "(%s relowner) AS rolname, "
4361 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4362 "relhasindex, relhasrules, relhasoids, "
4363 "0 AS relfrozenxid, "
4366 "'p' AS relpersistence, 't'::bool as isscannable, "
4367 "NULL AS reloftype, "
4368 "NULL::oid AS owning_tab, "
4369 "NULL::int4 AS owning_col, "
4370 "NULL AS reltablespace, "
4371 "NULL AS reloptions, "
4372 "NULL AS toast_reloptions "
4374 "WHERE relkind IN ('%c', '%c', '%c') "
4377 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4379 else if (fout->remoteVersion >= 70100)
4381 /* all tables have oids in 7.1 */
4382 appendPQExpBuffer(query,
4383 "SELECT tableoid, oid, relname, relacl, relkind, "
4384 "0::oid AS relnamespace, "
4385 "(%s relowner) AS rolname, "
4386 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4387 "relhasindex, relhasrules, "
4388 "'t'::bool AS relhasoids, "
4389 "0 AS relfrozenxid, "
4392 "'p' AS relpersistence, 't'::bool as isscannable, "
4393 "NULL AS reloftype, "
4394 "NULL::oid AS owning_tab, "
4395 "NULL::int4 AS owning_col, "
4396 "NULL AS reltablespace, "
4397 "NULL AS reloptions, "
4398 "NULL AS toast_reloptions "
4400 "WHERE relkind IN ('%c', '%c', '%c') "
4403 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4408 * Before 7.1, view relkind was not set to 'v', so we must check if we
4409 * have a view by looking for a rule in pg_rewrite.
4411 appendPQExpBuffer(query,
4413 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4414 "oid, relname, relacl, "
4415 "CASE WHEN relhasrules and relkind = 'r' "
4416 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4417 " r.ev_class = c.oid AND r.ev_type = '1') "
4418 "THEN '%c'::\"char\" "
4419 "ELSE relkind END AS relkind,"
4420 "0::oid AS relnamespace, "
4421 "(%s relowner) AS rolname, "
4422 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4423 "relhasindex, relhasrules, "
4424 "'t'::bool AS relhasoids, "
4425 "0 as relfrozenxid, "
4428 "'p' AS relpersistence, 't'::bool as isscannable, "
4429 "NULL AS reloftype, "
4430 "NULL::oid AS owning_tab, "
4431 "NULL::int4 AS owning_col, "
4432 "NULL AS reltablespace, "
4433 "NULL AS reloptions, "
4434 "NULL AS toast_reloptions "
4436 "WHERE relkind IN ('%c', '%c') "
4440 RELKIND_RELATION, RELKIND_SEQUENCE);
4443 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4445 ntups = PQntuples(res);
4450 * Extract data from result and lock dumpable tables. We do the locking
4451 * before anything else, to minimize the window wherein a table could
4452 * disappear under us.
4454 * Note that we have to save info about all tables here, even when dumping
4455 * only one, because we don't yet know which tables might be inheritance
4456 * ancestors of the target table.
4458 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4460 i_reltableoid = PQfnumber(res, "tableoid");
4461 i_reloid = PQfnumber(res, "oid");
4462 i_relname = PQfnumber(res, "relname");
4463 i_relnamespace = PQfnumber(res, "relnamespace");
4464 i_relacl = PQfnumber(res, "relacl");
4465 i_relkind = PQfnumber(res, "relkind");
4466 i_rolname = PQfnumber(res, "rolname");
4467 i_relchecks = PQfnumber(res, "relchecks");
4468 i_relhastriggers = PQfnumber(res, "relhastriggers");
4469 i_relhasindex = PQfnumber(res, "relhasindex");
4470 i_relhasrules = PQfnumber(res, "relhasrules");
4471 i_relhasoids = PQfnumber(res, "relhasoids");
4472 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4473 i_toastoid = PQfnumber(res, "toid");
4474 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4475 i_relpersistence = PQfnumber(res, "relpersistence");
4476 i_isscannable = PQfnumber(res, "isscannable");
4477 i_owning_tab = PQfnumber(res, "owning_tab");
4478 i_owning_col = PQfnumber(res, "owning_col");
4479 i_reltablespace = PQfnumber(res, "reltablespace");
4480 i_reloptions = PQfnumber(res, "reloptions");
4481 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4482 i_reloftype = PQfnumber(res, "reloftype");
4484 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4487 * Arrange to fail instead of waiting forever for a table lock.
4489 * NB: this coding assumes that the only queries issued within the
4490 * following loop are LOCK TABLEs; else the timeout may be undesirably
4491 * applied to other things too.
4493 resetPQExpBuffer(query);
4494 appendPQExpBuffer(query, "SET statement_timeout = ");
4495 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4496 ExecuteSqlStatement(fout, query->data);
4499 for (i = 0; i < ntups; i++)
4501 tblinfo[i].dobj.objType = DO_TABLE;
4502 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4503 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4504 AssignDumpId(&tblinfo[i].dobj);
4505 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4506 tblinfo[i].dobj.namespace =
4508 atooid(PQgetvalue(res, i, i_relnamespace)),
4509 tblinfo[i].dobj.catId.oid);
4510 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4511 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4512 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4513 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4514 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4515 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4516 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4517 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4518 tblinfo[i].isscannable = (strcmp(PQgetvalue(res, i, i_isscannable), "t") == 0);
4519 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4520 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4521 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4522 if (PQgetisnull(res, i, i_reloftype))
4523 tblinfo[i].reloftype = NULL;
4525 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4526 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4527 if (PQgetisnull(res, i, i_owning_tab))
4529 tblinfo[i].owning_tab = InvalidOid;
4530 tblinfo[i].owning_col = 0;
4534 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4535 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4537 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4538 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4539 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4541 /* other fields were zeroed above */
4544 * Decide whether we want to dump this table.
4546 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4547 tblinfo[i].dobj.dump = false;
4549 selectDumpableTable(&tblinfo[i]);
4550 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4553 * Read-lock target tables to make sure they aren't DROPPED or altered
4554 * in schema before we get around to dumping them.
4556 * Note that we don't explicitly lock parents of the target tables; we
4557 * assume our lock on the child is enough to prevent schema
4558 * alterations to parent tables.
4560 * NOTE: it'd be kinda nice to lock other relations too, not only
4561 * plain tables, but the backend doesn't presently allow that.
4563 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4565 resetPQExpBuffer(query);
4566 appendPQExpBuffer(query,
4567 "LOCK TABLE %s IN ACCESS SHARE MODE",
4568 fmtQualifiedId(fout,
4569 tblinfo[i].dobj.namespace->dobj.name,
4570 tblinfo[i].dobj.name));
4571 ExecuteSqlStatement(fout, query->data);
4574 /* Emit notice if join for owner failed */
4575 if (strlen(tblinfo[i].rolname) == 0)
4576 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4577 tblinfo[i].dobj.name);
4580 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4582 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4587 destroyPQExpBuffer(query);
4594 * identify owned sequences and mark them as dumpable if owning table is
4596 * We used to do this in getTables(), but it's better to do it after the
4597 * index used by findTableByOid() has been set up.
4600 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4605 * Force sequences that are "owned" by table columns to be dumped whenever
4606 * their owning table is being dumped.
4608 for (i = 0; i < numTables; i++)
4610 TableInfo *seqinfo = &tblinfo[i];
4611 TableInfo *owning_tab;
4613 if (!OidIsValid(seqinfo->owning_tab))
4614 continue; /* not an owned sequence */
4615 if (seqinfo->dobj.dump)
4616 continue; /* no need to search */
4617 owning_tab = findTableByOid(seqinfo->owning_tab);
4618 if (owning_tab && owning_tab->dobj.dump)
4620 seqinfo->interesting = true;
4621 seqinfo->dobj.dump = true;
4628 * read all the inheritance information
4629 * from the system catalogs return them in the InhInfo* structure
4631 * numInherits is set to the number of pairs read in
4634 getInherits(Archive *fout, int *numInherits)
4639 PQExpBuffer query = createPQExpBuffer();
4645 /* Make sure we are in proper schema */
4646 selectSourceSchema(fout, "pg_catalog");
4648 /* find all the inheritance information */
4650 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4652 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4654 ntups = PQntuples(res);
4656 *numInherits = ntups;
4658 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4660 i_inhrelid = PQfnumber(res, "inhrelid");
4661 i_inhparent = PQfnumber(res, "inhparent");
4663 for (i = 0; i < ntups; i++)
4665 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4666 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4671 destroyPQExpBuffer(query);
4678 * get information about every index on a dumpable table
4680 * Note: index data is not returned directly to the caller, but it
4681 * does get entered into the DumpableObject tables.
4684 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4688 PQExpBuffer query = createPQExpBuffer();
4691 ConstraintInfo *constrinfo;
4710 for (i = 0; i < numTables; i++)
4712 TableInfo *tbinfo = &tblinfo[i];
4714 /* Only plain tables and materialized views have indexes. */
4715 if (tbinfo->relkind != RELKIND_RELATION &&
4716 tbinfo->relkind != RELKIND_MATVIEW)
4718 if (!tbinfo->hasindex)
4721 /* Ignore indexes of tables not to be dumped */
4722 if (!tbinfo->dobj.dump)
4726 write_msg(NULL, "reading indexes for table \"%s\"\n",
4729 /* Make sure we are in proper schema so indexdef is right */
4730 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4733 * The point of the messy-looking outer join is to find a constraint
4734 * that is related by an internal dependency link to the index. If we
4735 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4736 * assume an index won't have more than one internal dependency.
4738 * As of 9.0 we don't need to look at pg_depend but can check for a
4739 * match to pg_constraint.conindid. The check on conrelid is
4740 * redundant but useful because that column is indexed while conindid
4743 resetPQExpBuffer(query);
4744 if (fout->remoteVersion >= 90000)
4746 appendPQExpBuffer(query,
4747 "SELECT t.tableoid, t.oid, "
4748 "t.relname AS indexname, "
4749 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4750 "t.relnatts AS indnkeys, "
4751 "i.indkey, i.indisclustered, "
4752 "c.contype, c.conname, "
4753 "c.condeferrable, c.condeferred, "
4754 "c.tableoid AS contableoid, "
4756 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4757 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4758 "array_to_string(t.reloptions, ', ') AS options "
4759 "FROM pg_catalog.pg_index i "
4760 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4761 "LEFT JOIN pg_catalog.pg_constraint c "
4762 "ON (i.indrelid = c.conrelid AND "
4763 "i.indexrelid = c.conindid AND "
4764 "c.contype IN ('p','u','x')) "
4765 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4766 "ORDER BY indexname",
4767 tbinfo->dobj.catId.oid);
4769 else if (fout->remoteVersion >= 80200)
4771 appendPQExpBuffer(query,
4772 "SELECT t.tableoid, t.oid, "
4773 "t.relname AS indexname, "
4774 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4775 "t.relnatts AS indnkeys, "
4776 "i.indkey, i.indisclustered, "
4777 "c.contype, c.conname, "
4778 "c.condeferrable, c.condeferred, "
4779 "c.tableoid AS contableoid, "
4782 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4783 "array_to_string(t.reloptions, ', ') AS options "
4784 "FROM pg_catalog.pg_index i "
4785 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4786 "LEFT JOIN pg_catalog.pg_depend d "
4787 "ON (d.classid = t.tableoid "
4788 "AND d.objid = t.oid "
4789 "AND d.deptype = 'i') "
4790 "LEFT JOIN pg_catalog.pg_constraint c "
4791 "ON (d.refclassid = c.tableoid "
4792 "AND d.refobjid = c.oid) "
4793 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4794 "ORDER BY indexname",
4795 tbinfo->dobj.catId.oid);
4797 else if (fout->remoteVersion >= 80000)
4799 appendPQExpBuffer(query,
4800 "SELECT t.tableoid, t.oid, "
4801 "t.relname AS indexname, "
4802 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4803 "t.relnatts AS indnkeys, "
4804 "i.indkey, i.indisclustered, "
4805 "c.contype, c.conname, "
4806 "c.condeferrable, c.condeferred, "
4807 "c.tableoid AS contableoid, "
4810 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4812 "FROM pg_catalog.pg_index i "
4813 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4814 "LEFT JOIN pg_catalog.pg_depend d "
4815 "ON (d.classid = t.tableoid "
4816 "AND d.objid = t.oid "
4817 "AND d.deptype = 'i') "
4818 "LEFT JOIN pg_catalog.pg_constraint c "
4819 "ON (d.refclassid = c.tableoid "
4820 "AND d.refobjid = c.oid) "
4821 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4822 "ORDER BY indexname",
4823 tbinfo->dobj.catId.oid);
4825 else if (fout->remoteVersion >= 70300)
4827 appendPQExpBuffer(query,
4828 "SELECT t.tableoid, t.oid, "
4829 "t.relname AS indexname, "
4830 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4831 "t.relnatts AS indnkeys, "
4832 "i.indkey, i.indisclustered, "
4833 "c.contype, c.conname, "
4834 "c.condeferrable, c.condeferred, "
4835 "c.tableoid AS contableoid, "
4838 "NULL AS tablespace, "
4840 "FROM pg_catalog.pg_index i "
4841 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4842 "LEFT JOIN pg_catalog.pg_depend d "
4843 "ON (d.classid = t.tableoid "
4844 "AND d.objid = t.oid "
4845 "AND d.deptype = 'i') "
4846 "LEFT JOIN pg_catalog.pg_constraint c "
4847 "ON (d.refclassid = c.tableoid "
4848 "AND d.refobjid = c.oid) "
4849 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4850 "ORDER BY indexname",
4851 tbinfo->dobj.catId.oid);
4853 else if (fout->remoteVersion >= 70100)
4855 appendPQExpBuffer(query,
4856 "SELECT t.tableoid, t.oid, "
4857 "t.relname AS indexname, "
4858 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4859 "t.relnatts AS indnkeys, "
4860 "i.indkey, false AS indisclustered, "
4861 "CASE WHEN i.indisprimary THEN 'p'::char "
4862 "ELSE '0'::char END AS contype, "
4863 "t.relname AS conname, "
4864 "false AS condeferrable, "
4865 "false AS condeferred, "
4866 "0::oid AS contableoid, "
4869 "NULL AS tablespace, "
4871 "FROM pg_index i, pg_class t "
4872 "WHERE t.oid = i.indexrelid "
4873 "AND i.indrelid = '%u'::oid "
4874 "ORDER BY indexname",
4875 tbinfo->dobj.catId.oid);
4879 appendPQExpBuffer(query,
4881 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4883 "t.relname AS indexname, "
4884 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4885 "t.relnatts AS indnkeys, "
4886 "i.indkey, false AS indisclustered, "
4887 "CASE WHEN i.indisprimary THEN 'p'::char "
4888 "ELSE '0'::char END AS contype, "
4889 "t.relname AS conname, "
4890 "false AS condeferrable, "
4891 "false AS condeferred, "
4892 "0::oid AS contableoid, "
4895 "NULL AS tablespace, "
4897 "FROM pg_index i, pg_class t "
4898 "WHERE t.oid = i.indexrelid "
4899 "AND i.indrelid = '%u'::oid "
4900 "ORDER BY indexname",
4901 tbinfo->dobj.catId.oid);
4904 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4906 ntups = PQntuples(res);
4908 i_tableoid = PQfnumber(res, "tableoid");
4909 i_oid = PQfnumber(res, "oid");
4910 i_indexname = PQfnumber(res, "indexname");
4911 i_indexdef = PQfnumber(res, "indexdef");
4912 i_indnkeys = PQfnumber(res, "indnkeys");
4913 i_indkey = PQfnumber(res, "indkey");
4914 i_indisclustered = PQfnumber(res, "indisclustered");
4915 i_contype = PQfnumber(res, "contype");
4916 i_conname = PQfnumber(res, "conname");
4917 i_condeferrable = PQfnumber(res, "condeferrable");
4918 i_condeferred = PQfnumber(res, "condeferred");
4919 i_contableoid = PQfnumber(res, "contableoid");
4920 i_conoid = PQfnumber(res, "conoid");
4921 i_condef = PQfnumber(res, "condef");
4922 i_tablespace = PQfnumber(res, "tablespace");
4923 i_options = PQfnumber(res, "options");
4925 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4926 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4928 for (j = 0; j < ntups; j++)
4932 indxinfo[j].dobj.objType = DO_INDEX;
4933 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4934 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4935 AssignDumpId(&indxinfo[j].dobj);
4936 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4937 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4938 indxinfo[j].indextable = tbinfo;
4939 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4940 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4941 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4942 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4945 * In pre-7.4 releases, indkeys may contain more entries than
4946 * indnkeys says (since indnkeys will be 1 for a functional
4947 * index). We don't actually care about this case since we don't
4948 * examine indkeys except for indexes associated with PRIMARY and
4949 * UNIQUE constraints, which are never functional indexes. But we
4950 * have to allocate enough space to keep parseOidArray from
4953 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4954 parseOidArray(PQgetvalue(res, j, i_indkey),
4955 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4956 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4957 contype = *(PQgetvalue(res, j, i_contype));
4959 if (contype == 'p' || contype == 'u' || contype == 'x')
4962 * If we found a constraint matching the index, create an
4965 * In a pre-7.3 database, we take this path iff the index was
4966 * marked indisprimary.
4968 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4969 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4970 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4971 AssignDumpId(&constrinfo[j].dobj);
4972 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4973 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4974 constrinfo[j].contable = tbinfo;
4975 constrinfo[j].condomain = NULL;
4976 constrinfo[j].contype = contype;
4978 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4980 constrinfo[j].condef = NULL;
4981 constrinfo[j].confrelid = InvalidOid;
4982 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4983 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4984 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4985 constrinfo[j].conislocal = true;
4986 constrinfo[j].separate = true;
4988 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4990 /* If pre-7.3 DB, better make sure table comes first */
4991 addObjectDependency(&constrinfo[j].dobj,
4992 tbinfo->dobj.dumpId);
4996 /* Plain secondary index */
4997 indxinfo[j].indexconstraint = 0;
5004 destroyPQExpBuffer(query);
5010 * Get info about constraints on dumpable tables.
5012 * Currently handles foreign keys only.
5013 * Unique and primary key constraints are handled with indexes,
5014 * while check constraints are processed in getTableAttrs().
5017 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
5021 ConstraintInfo *constrinfo;
5031 /* pg_constraint was created in 7.3, so nothing to do if older */
5032 if (fout->remoteVersion < 70300)
5035 query = createPQExpBuffer();
5037 for (i = 0; i < numTables; i++)
5039 TableInfo *tbinfo = &tblinfo[i];
5041 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5045 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
5049 * select table schema to ensure constraint expr is qualified if
5052 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5054 resetPQExpBuffer(query);
5055 appendPQExpBuffer(query,
5056 "SELECT tableoid, oid, conname, confrelid, "
5057 "pg_catalog.pg_get_constraintdef(oid) AS condef "
5058 "FROM pg_catalog.pg_constraint "
5059 "WHERE conrelid = '%u'::pg_catalog.oid "
5060 "AND contype = 'f'",
5061 tbinfo->dobj.catId.oid);
5062 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5064 ntups = PQntuples(res);
5066 i_contableoid = PQfnumber(res, "tableoid");
5067 i_conoid = PQfnumber(res, "oid");
5068 i_conname = PQfnumber(res, "conname");
5069 i_confrelid = PQfnumber(res, "confrelid");
5070 i_condef = PQfnumber(res, "condef");
5072 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5074 for (j = 0; j < ntups; j++)
5076 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
5077 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5078 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5079 AssignDumpId(&constrinfo[j].dobj);
5080 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5081 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5082 constrinfo[j].contable = tbinfo;
5083 constrinfo[j].condomain = NULL;
5084 constrinfo[j].contype = 'f';
5085 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5086 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
5087 constrinfo[j].conindex = 0;
5088 constrinfo[j].condeferrable = false;
5089 constrinfo[j].condeferred = false;
5090 constrinfo[j].conislocal = true;
5091 constrinfo[j].separate = true;
5097 destroyPQExpBuffer(query);
5101 * getDomainConstraints
5103 * Get info about constraints on a domain.
5106 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
5109 ConstraintInfo *constrinfo;
5118 /* pg_constraint was created in 7.3, so nothing to do if older */
5119 if (fout->remoteVersion < 70300)
5123 * select appropriate schema to ensure names in constraint are properly
5126 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
5128 query = createPQExpBuffer();
5130 if (fout->remoteVersion >= 90100)
5131 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5132 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5134 "FROM pg_catalog.pg_constraint "
5135 "WHERE contypid = '%u'::pg_catalog.oid "
5137 tyinfo->dobj.catId.oid);
5139 else if (fout->remoteVersion >= 70400)
5140 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5141 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5142 "true as convalidated "
5143 "FROM pg_catalog.pg_constraint "
5144 "WHERE contypid = '%u'::pg_catalog.oid "
5146 tyinfo->dobj.catId.oid);
5148 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5149 "'CHECK (' || consrc || ')' AS consrc, "
5150 "true as convalidated "
5151 "FROM pg_catalog.pg_constraint "
5152 "WHERE contypid = '%u'::pg_catalog.oid "
5154 tyinfo->dobj.catId.oid);
5156 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5158 ntups = PQntuples(res);
5160 i_tableoid = PQfnumber(res, "tableoid");
5161 i_oid = PQfnumber(res, "oid");
5162 i_conname = PQfnumber(res, "conname");
5163 i_consrc = PQfnumber(res, "consrc");
5165 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5167 tyinfo->nDomChecks = ntups;
5168 tyinfo->domChecks = constrinfo;
5170 for (i = 0; i < ntups; i++)
5172 bool validated = PQgetvalue(res, i, 4)[0] == 't';
5174 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5175 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5176 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5177 AssignDumpId(&constrinfo[i].dobj);
5178 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5179 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5180 constrinfo[i].contable = NULL;
5181 constrinfo[i].condomain = tyinfo;
5182 constrinfo[i].contype = 'c';
5183 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5184 constrinfo[i].confrelid = InvalidOid;
5185 constrinfo[i].conindex = 0;
5186 constrinfo[i].condeferrable = false;
5187 constrinfo[i].condeferred = false;
5188 constrinfo[i].conislocal = true;
5190 constrinfo[i].separate = !validated;
5193 * Make the domain depend on the constraint, ensuring it won't be
5194 * output till any constraint dependencies are OK. If the constraint
5195 * has not been validated, it's going to be dumped after the domain
5196 * anyway, so this doesn't matter.
5199 addObjectDependency(&tyinfo->dobj,
5200 constrinfo[i].dobj.dumpId);
5205 destroyPQExpBuffer(query);
5210 * get basic information about every rule in the system
5212 * numRules is set to the number of rules read in
5215 getRules(Archive *fout, int *numRules)
5220 PQExpBuffer query = createPQExpBuffer();
5230 /* Make sure we are in proper schema */
5231 selectSourceSchema(fout, "pg_catalog");
5233 if (fout->remoteVersion >= 80300)
5235 appendPQExpBuffer(query, "SELECT "
5236 "tableoid, oid, rulename, "
5237 "ev_class AS ruletable, ev_type, is_instead, "
5242 else if (fout->remoteVersion >= 70100)
5244 appendPQExpBuffer(query, "SELECT "
5245 "tableoid, oid, rulename, "
5246 "ev_class AS ruletable, ev_type, is_instead, "
5247 "'O'::char AS ev_enabled "
5253 appendPQExpBuffer(query, "SELECT "
5254 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5256 "ev_class AS ruletable, ev_type, is_instead, "
5257 "'O'::char AS ev_enabled "
5262 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5264 ntups = PQntuples(res);
5268 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5270 i_tableoid = PQfnumber(res, "tableoid");
5271 i_oid = PQfnumber(res, "oid");
5272 i_rulename = PQfnumber(res, "rulename");
5273 i_ruletable = PQfnumber(res, "ruletable");
5274 i_ev_type = PQfnumber(res, "ev_type");
5275 i_is_instead = PQfnumber(res, "is_instead");
5276 i_ev_enabled = PQfnumber(res, "ev_enabled");
5278 for (i = 0; i < ntups; i++)
5282 ruleinfo[i].dobj.objType = DO_RULE;
5283 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5284 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5285 AssignDumpId(&ruleinfo[i].dobj);
5286 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5287 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5288 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5289 if (ruleinfo[i].ruletable == NULL)
5290 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5291 ruletableoid, ruleinfo[i].dobj.catId.oid);
5292 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5293 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5294 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5295 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5296 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5297 if (ruleinfo[i].ruletable)
5300 * If the table is a view or materialized view, force its ON
5301 * SELECT rule to be sorted before the view itself --- this
5302 * ensures that any dependencies for the rule affect the table's
5303 * positioning. Other rules are forced to appear after their
5306 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
5307 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
5308 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5310 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5311 ruleinfo[i].dobj.dumpId);
5312 /* We'll merge the rule into CREATE VIEW, if possible */
5313 ruleinfo[i].separate = false;
5317 addObjectDependency(&ruleinfo[i].dobj,
5318 ruleinfo[i].ruletable->dobj.dumpId);
5319 ruleinfo[i].separate = true;
5323 ruleinfo[i].separate = true;
5326 * If we're forced to break a dependency loop by dumping a view as a
5327 * table and separate _RETURN rule, we'll move the view's reloptions
5328 * to the rule. (This is necessary because tables and views have
5329 * different valid reloptions, so we can't apply the options until the
5330 * backend knows it's a view.) Otherwise the rule's reloptions stay
5333 ruleinfo[i].reloptions = NULL;
5338 destroyPQExpBuffer(query);
5345 * get information about every trigger on a dumpable table
5347 * Note: trigger data is not returned directly to the caller, but it
5348 * does get entered into the DumpableObject tables.
5351 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5355 PQExpBuffer query = createPQExpBuffer();
5357 TriggerInfo *tginfo;
5375 for (i = 0; i < numTables; i++)
5377 TableInfo *tbinfo = &tblinfo[i];
5379 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5383 write_msg(NULL, "reading triggers for table \"%s\"\n",
5387 * select table schema to ensure regproc name is qualified if needed
5389 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5391 resetPQExpBuffer(query);
5392 if (fout->remoteVersion >= 90000)
5395 * NB: think not to use pretty=true in pg_get_triggerdef. It
5396 * could result in non-forward-compatible dumps of WHEN clauses
5397 * due to under-parenthesization.
5399 appendPQExpBuffer(query,
5401 "tgfoid::pg_catalog.regproc AS tgfname, "
5402 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5403 "tgenabled, tableoid, oid "
5404 "FROM pg_catalog.pg_trigger t "
5405 "WHERE tgrelid = '%u'::pg_catalog.oid "
5406 "AND NOT tgisinternal",
5407 tbinfo->dobj.catId.oid);
5409 else if (fout->remoteVersion >= 80300)
5412 * We ignore triggers that are tied to a foreign-key constraint
5414 appendPQExpBuffer(query,
5416 "tgfoid::pg_catalog.regproc AS tgfname, "
5417 "tgtype, tgnargs, tgargs, tgenabled, "
5418 "tgisconstraint, tgconstrname, tgdeferrable, "
5419 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5420 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5421 "FROM pg_catalog.pg_trigger t "
5422 "WHERE tgrelid = '%u'::pg_catalog.oid "
5423 "AND tgconstraint = 0",
5424 tbinfo->dobj.catId.oid);
5426 else if (fout->remoteVersion >= 70300)
5429 * We ignore triggers that are tied to a foreign-key constraint,
5430 * but in these versions we have to grovel through pg_constraint
5433 appendPQExpBuffer(query,
5435 "tgfoid::pg_catalog.regproc AS tgfname, "
5436 "tgtype, tgnargs, tgargs, tgenabled, "
5437 "tgisconstraint, tgconstrname, tgdeferrable, "
5438 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5439 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5440 "FROM pg_catalog.pg_trigger t "
5441 "WHERE tgrelid = '%u'::pg_catalog.oid "
5442 "AND (NOT tgisconstraint "
5444 " (SELECT 1 FROM pg_catalog.pg_depend d "
5445 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5446 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5447 tbinfo->dobj.catId.oid);
5449 else if (fout->remoteVersion >= 70100)
5451 appendPQExpBuffer(query,
5452 "SELECT tgname, tgfoid::regproc AS tgfname, "
5453 "tgtype, tgnargs, tgargs, tgenabled, "
5454 "tgisconstraint, tgconstrname, tgdeferrable, "
5455 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5456 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5457 " AS tgconstrrelname "
5459 "WHERE tgrelid = '%u'::oid",
5460 tbinfo->dobj.catId.oid);
5464 appendPQExpBuffer(query,
5465 "SELECT tgname, tgfoid::regproc AS tgfname, "
5466 "tgtype, tgnargs, tgargs, tgenabled, "
5467 "tgisconstraint, tgconstrname, tgdeferrable, "
5468 "tgconstrrelid, tginitdeferred, "
5469 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5471 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5472 " AS tgconstrrelname "
5474 "WHERE tgrelid = '%u'::oid",
5475 tbinfo->dobj.catId.oid);
5477 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5479 ntups = PQntuples(res);
5481 i_tableoid = PQfnumber(res, "tableoid");
5482 i_oid = PQfnumber(res, "oid");
5483 i_tgname = PQfnumber(res, "tgname");
5484 i_tgfname = PQfnumber(res, "tgfname");
5485 i_tgtype = PQfnumber(res, "tgtype");
5486 i_tgnargs = PQfnumber(res, "tgnargs");
5487 i_tgargs = PQfnumber(res, "tgargs");
5488 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5489 i_tgconstrname = PQfnumber(res, "tgconstrname");
5490 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5491 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5492 i_tgenabled = PQfnumber(res, "tgenabled");
5493 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5494 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5495 i_tgdef = PQfnumber(res, "tgdef");
5497 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5499 for (j = 0; j < ntups; j++)
5501 tginfo[j].dobj.objType = DO_TRIGGER;
5502 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5503 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5504 AssignDumpId(&tginfo[j].dobj);
5505 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5506 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5507 tginfo[j].tgtable = tbinfo;
5508 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5511 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5513 /* remaining fields are not valid if we have tgdef */
5514 tginfo[j].tgfname = NULL;
5515 tginfo[j].tgtype = 0;
5516 tginfo[j].tgnargs = 0;
5517 tginfo[j].tgargs = NULL;
5518 tginfo[j].tgisconstraint = false;
5519 tginfo[j].tgdeferrable = false;
5520 tginfo[j].tginitdeferred = false;
5521 tginfo[j].tgconstrname = NULL;
5522 tginfo[j].tgconstrrelid = InvalidOid;
5523 tginfo[j].tgconstrrelname = NULL;
5527 tginfo[j].tgdef = NULL;
5529 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5530 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5531 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5532 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5533 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5534 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5535 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5537 if (tginfo[j].tgisconstraint)
5539 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5540 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5541 if (OidIsValid(tginfo[j].tgconstrrelid))
5543 if (PQgetisnull(res, j, i_tgconstrrelname))
5544 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5545 tginfo[j].dobj.name,
5547 tginfo[j].tgconstrrelid);
5548 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5551 tginfo[j].tgconstrrelname = NULL;
5555 tginfo[j].tgconstrname = NULL;
5556 tginfo[j].tgconstrrelid = InvalidOid;
5557 tginfo[j].tgconstrrelname = NULL;
5565 destroyPQExpBuffer(query);
5570 * get information about event triggers
5573 getEventTriggers(Archive *fout, int *numEventTriggers)
5576 PQExpBuffer query = createPQExpBuffer();
5578 EventTriggerInfo *evtinfo;
5589 /* Before 9.3, there are no event triggers */
5590 if (fout->remoteVersion < 90300)
5592 *numEventTriggers = 0;
5596 /* Make sure we are in proper schema */
5597 selectSourceSchema(fout, "pg_catalog");
5599 appendPQExpBuffer(query,
5600 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5601 "evtevent, (%s evtowner) AS evtowner, "
5602 "array_to_string(array("
5603 "select quote_literal(x) "
5604 " from unnest(evttags) as t(x)), ', ') as evttags, "
5605 "e.evtfoid::regproc as evtfname "
5606 "FROM pg_event_trigger e "
5610 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5612 ntups = PQntuples(res);
5614 *numEventTriggers = ntups;
5616 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5618 i_tableoid = PQfnumber(res, "tableoid");
5619 i_oid = PQfnumber(res, "oid");
5620 i_evtname = PQfnumber(res, "evtname");
5621 i_evtevent = PQfnumber(res, "evtevent");
5622 i_evtowner = PQfnumber(res, "evtowner");
5623 i_evttags = PQfnumber(res, "evttags");
5624 i_evtfname = PQfnumber(res, "evtfname");
5625 i_evtenabled = PQfnumber(res, "evtenabled");
5627 for (i = 0; i < ntups; i++)
5629 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5630 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5631 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5632 AssignDumpId(&evtinfo[i].dobj);
5633 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5634 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5635 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5636 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5637 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5638 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5639 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5644 destroyPQExpBuffer(query);
5651 * get basic information about every procedural language in the system
5653 * numProcLangs is set to the number of langs read in
5655 * NB: this must run after getFuncs() because we assume we can do
5659 getProcLangs(Archive *fout, int *numProcLangs)
5664 PQExpBuffer query = createPQExpBuffer();
5665 ProcLangInfo *planginfo;
5670 int i_lanplcallfoid;
5676 /* Make sure we are in proper schema */
5677 selectSourceSchema(fout, "pg_catalog");
5679 if (fout->remoteVersion >= 90000)
5681 /* pg_language has a laninline column */
5682 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5683 "lanname, lanpltrusted, lanplcallfoid, "
5684 "laninline, lanvalidator, lanacl, "
5685 "(%s lanowner) AS lanowner "
5691 else if (fout->remoteVersion >= 80300)
5693 /* pg_language has a lanowner column */
5694 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5695 "lanname, lanpltrusted, lanplcallfoid, "
5696 "lanvalidator, lanacl, "
5697 "(%s lanowner) AS lanowner "
5703 else if (fout->remoteVersion >= 80100)
5705 /* Languages are owned by the bootstrap superuser, OID 10 */
5706 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5707 "(%s '10') AS lanowner "
5713 else if (fout->remoteVersion >= 70400)
5715 /* Languages are owned by the bootstrap superuser, sysid 1 */
5716 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5717 "(%s '1') AS lanowner "
5723 else if (fout->remoteVersion >= 70100)
5725 /* No clear notion of an owner at all before 7.4 ... */
5726 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5732 appendPQExpBuffer(query, "SELECT "
5733 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5734 "oid, * FROM pg_language "
5739 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5741 ntups = PQntuples(res);
5743 *numProcLangs = ntups;
5745 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5747 i_tableoid = PQfnumber(res, "tableoid");
5748 i_oid = PQfnumber(res, "oid");
5749 i_lanname = PQfnumber(res, "lanname");
5750 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5751 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5752 /* these may fail and return -1: */
5753 i_laninline = PQfnumber(res, "laninline");
5754 i_lanvalidator = PQfnumber(res, "lanvalidator");
5755 i_lanacl = PQfnumber(res, "lanacl");
5756 i_lanowner = PQfnumber(res, "lanowner");
5758 for (i = 0; i < ntups; i++)
5760 planginfo[i].dobj.objType = DO_PROCLANG;
5761 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5762 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5763 AssignDumpId(&planginfo[i].dobj);
5765 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5766 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5767 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5768 if (i_laninline >= 0)
5769 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5771 planginfo[i].laninline = InvalidOid;
5772 if (i_lanvalidator >= 0)
5773 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5775 planginfo[i].lanvalidator = InvalidOid;
5777 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5779 planginfo[i].lanacl = pg_strdup("{=U}");
5780 if (i_lanowner >= 0)
5781 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5783 planginfo[i].lanowner = pg_strdup("");
5785 if (fout->remoteVersion < 70300)
5788 * We need to make a dependency to ensure the function will be
5789 * dumped first. (In 7.3 and later the regular dependency
5790 * mechanism will handle this for us.)
5792 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5795 addObjectDependency(&planginfo[i].dobj,
5796 funcInfo->dobj.dumpId);
5802 destroyPQExpBuffer(query);
5809 * get basic information about every cast in the system
5811 * numCasts is set to the number of casts read in
5814 getCasts(Archive *fout, int *numCasts)
5819 PQExpBuffer query = createPQExpBuffer();
5829 /* Make sure we are in proper schema */
5830 selectSourceSchema(fout, "pg_catalog");
5832 if (fout->remoteVersion >= 80400)
5834 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5835 "castsource, casttarget, castfunc, castcontext, "
5837 "FROM pg_cast ORDER BY 3,4");
5839 else if (fout->remoteVersion >= 70300)
5841 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5842 "castsource, casttarget, castfunc, castcontext, "
5843 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5844 "FROM pg_cast ORDER BY 3,4");
5848 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5849 "t1.oid AS castsource, t2.oid AS casttarget, "
5850 "p.oid AS castfunc, 'e' AS castcontext, "
5851 "'f' AS castmethod "
5852 "FROM pg_type t1, pg_type t2, pg_proc p "
5853 "WHERE p.pronargs = 1 AND "
5854 "p.proargtypes[0] = t1.oid AND "
5855 "p.prorettype = t2.oid AND p.proname = t2.typname "
5859 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5861 ntups = PQntuples(res);
5865 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5867 i_tableoid = PQfnumber(res, "tableoid");
5868 i_oid = PQfnumber(res, "oid");
5869 i_castsource = PQfnumber(res, "castsource");
5870 i_casttarget = PQfnumber(res, "casttarget");
5871 i_castfunc = PQfnumber(res, "castfunc");
5872 i_castcontext = PQfnumber(res, "castcontext");
5873 i_castmethod = PQfnumber(res, "castmethod");
5875 for (i = 0; i < ntups; i++)
5877 PQExpBufferData namebuf;
5878 TypeInfo *sTypeInfo;
5879 TypeInfo *tTypeInfo;
5881 castinfo[i].dobj.objType = DO_CAST;
5882 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5883 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5884 AssignDumpId(&castinfo[i].dobj);
5885 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5886 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5887 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5888 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5889 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5892 * Try to name cast as concatenation of typnames. This is only used
5893 * for purposes of sorting. If we fail to find either type, the name
5894 * will be an empty string.
5896 initPQExpBuffer(&namebuf);
5897 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5898 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5899 if (sTypeInfo && tTypeInfo)
5900 appendPQExpBuffer(&namebuf, "%s %s",
5901 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5902 castinfo[i].dobj.name = namebuf.data;
5904 if (OidIsValid(castinfo[i].castfunc))
5907 * We need to make a dependency to ensure the function will be
5908 * dumped first. (In 7.3 and later the regular dependency
5909 * mechanism will handle this for us.)
5913 funcInfo = findFuncByOid(castinfo[i].castfunc);
5915 addObjectDependency(&castinfo[i].dobj,
5916 funcInfo->dobj.dumpId);
5922 destroyPQExpBuffer(query);
5929 * for each interesting table, read info about its attributes
5930 * (names, types, default values, CHECK constraints, etc)
5932 * This is implemented in a very inefficient way right now, looping
5933 * through the tblinfo and doing a join per table to find the attrs and their
5934 * types. However, because we want type names and so forth to be named
5935 * relative to the schema of each table, we couldn't do it in just one
5936 * query. (Maybe one query per schema?)
5941 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5945 PQExpBuffer q = createPQExpBuffer();
5950 int i_attstattarget;
5961 int i_attfdwoptions;
5966 for (i = 0; i < numTables; i++)
5968 TableInfo *tbinfo = &tblinfo[i];
5970 /* Don't bother to collect info for sequences */
5971 if (tbinfo->relkind == RELKIND_SEQUENCE)
5974 /* Don't bother with uninteresting tables, either */
5975 if (!tbinfo->interesting)
5979 * Make sure we are in proper schema for this table; this allows
5980 * correct retrieval of formatted type names and default exprs
5982 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5984 /* find all the user attributes and their types */
5987 * we must read the attribute names in attribute number order! because
5988 * we will use the attnum to index into the attnames array later. We
5989 * actually ask to order by "attrelid, attnum" because (at least up to
5990 * 7.3) the planner is not smart enough to realize it needn't re-sort
5991 * the output of an indexscan on pg_attribute_relid_attnum_index.
5994 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5997 resetPQExpBuffer(q);
5999 if (fout->remoteVersion >= 90200)
6002 * attfdwoptions is new in 9.2.
6004 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6005 "a.attstattarget, a.attstorage, t.typstorage, "
6006 "a.attnotnull, a.atthasdef, a.attisdropped, "
6007 "a.attlen, a.attalign, a.attislocal, "
6008 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6009 "array_to_string(a.attoptions, ', ') AS attoptions, "
6010 "CASE WHEN a.attcollation <> t.typcollation "
6011 "THEN a.attcollation ELSE 0 END AS attcollation, "
6012 "pg_catalog.array_to_string(ARRAY("
6013 "SELECT pg_catalog.quote_ident(option_name) || "
6014 "' ' || pg_catalog.quote_literal(option_value) "
6015 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
6016 "ORDER BY option_name"
6017 "), E',\n ') AS attfdwoptions "
6018 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6019 "ON a.atttypid = t.oid "
6020 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6021 "AND a.attnum > 0::pg_catalog.int2 "
6022 "ORDER BY a.attrelid, a.attnum",
6023 tbinfo->dobj.catId.oid);
6025 else if (fout->remoteVersion >= 90100)
6028 * attcollation is new in 9.1. Since we only want to dump COLLATE
6029 * clauses for attributes whose collation is different from their
6030 * type's default, we use a CASE here to suppress uninteresting
6031 * attcollations cheaply.
6033 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6034 "a.attstattarget, a.attstorage, t.typstorage, "
6035 "a.attnotnull, a.atthasdef, a.attisdropped, "
6036 "a.attlen, a.attalign, a.attislocal, "
6037 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6038 "array_to_string(a.attoptions, ', ') AS attoptions, "
6039 "CASE WHEN a.attcollation <> t.typcollation "
6040 "THEN a.attcollation ELSE 0 END AS attcollation, "
6041 "NULL AS attfdwoptions "
6042 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6043 "ON a.atttypid = t.oid "
6044 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6045 "AND a.attnum > 0::pg_catalog.int2 "
6046 "ORDER BY a.attrelid, a.attnum",
6047 tbinfo->dobj.catId.oid);
6049 else if (fout->remoteVersion >= 90000)
6051 /* attoptions is new in 9.0 */
6052 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6053 "a.attstattarget, a.attstorage, t.typstorage, "
6054 "a.attnotnull, a.atthasdef, a.attisdropped, "
6055 "a.attlen, a.attalign, a.attislocal, "
6056 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6057 "array_to_string(a.attoptions, ', ') AS attoptions, "
6058 "0 AS attcollation, "
6059 "NULL AS attfdwoptions "
6060 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6061 "ON a.atttypid = t.oid "
6062 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6063 "AND a.attnum > 0::pg_catalog.int2 "
6064 "ORDER BY a.attrelid, a.attnum",
6065 tbinfo->dobj.catId.oid);
6067 else if (fout->remoteVersion >= 70300)
6069 /* need left join here to not fail on dropped columns ... */
6070 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6071 "a.attstattarget, a.attstorage, t.typstorage, "
6072 "a.attnotnull, a.atthasdef, a.attisdropped, "
6073 "a.attlen, a.attalign, a.attislocal, "
6074 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6075 "'' AS attoptions, 0 AS attcollation, "
6076 "NULL AS attfdwoptions "
6077 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6078 "ON a.atttypid = t.oid "
6079 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6080 "AND a.attnum > 0::pg_catalog.int2 "
6081 "ORDER BY a.attrelid, a.attnum",
6082 tbinfo->dobj.catId.oid);
6084 else if (fout->remoteVersion >= 70100)
6087 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
6088 * we don't dump it because we can't tell whether it's been
6089 * explicitly set or was just a default.
6091 * attislocal doesn't exist before 7.3, either; in older databases
6092 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
6094 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6095 "-1 AS attstattarget, a.attstorage, "
6096 "t.typstorage, a.attnotnull, a.atthasdef, "
6097 "false AS attisdropped, a.attlen, "
6098 "a.attalign, true AS attislocal, "
6099 "format_type(t.oid,a.atttypmod) AS atttypname, "
6100 "'' AS attoptions, 0 AS attcollation, "
6101 "NULL AS attfdwoptions "
6102 "FROM pg_attribute a LEFT JOIN pg_type t "
6103 "ON a.atttypid = t.oid "
6104 "WHERE a.attrelid = '%u'::oid "
6105 "AND a.attnum > 0::int2 "
6106 "ORDER BY a.attrelid, a.attnum",
6107 tbinfo->dobj.catId.oid);
6111 /* format_type not available before 7.1 */
6112 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
6113 "-1 AS attstattarget, "
6114 "attstorage, attstorage AS typstorage, "
6115 "attnotnull, atthasdef, false AS attisdropped, "
6116 "attlen, attalign, "
6117 "true AS attislocal, "
6118 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
6119 "'' AS attoptions, 0 AS attcollation, "
6120 "NULL AS attfdwoptions "
6121 "FROM pg_attribute a "
6122 "WHERE attrelid = '%u'::oid "
6123 "AND attnum > 0::int2 "
6124 "ORDER BY attrelid, attnum",
6125 tbinfo->dobj.catId.oid);
6128 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6130 ntups = PQntuples(res);
6132 i_attnum = PQfnumber(res, "attnum");
6133 i_attname = PQfnumber(res, "attname");
6134 i_atttypname = PQfnumber(res, "atttypname");
6135 i_atttypmod = PQfnumber(res, "atttypmod");
6136 i_attstattarget = PQfnumber(res, "attstattarget");
6137 i_attstorage = PQfnumber(res, "attstorage");
6138 i_typstorage = PQfnumber(res, "typstorage");
6139 i_attnotnull = PQfnumber(res, "attnotnull");
6140 i_atthasdef = PQfnumber(res, "atthasdef");
6141 i_attisdropped = PQfnumber(res, "attisdropped");
6142 i_attlen = PQfnumber(res, "attlen");
6143 i_attalign = PQfnumber(res, "attalign");
6144 i_attislocal = PQfnumber(res, "attislocal");
6145 i_attoptions = PQfnumber(res, "attoptions");
6146 i_attcollation = PQfnumber(res, "attcollation");
6147 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
6149 tbinfo->numatts = ntups;
6150 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
6151 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
6152 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
6153 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
6154 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
6155 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
6156 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
6157 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
6158 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
6159 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
6160 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
6161 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
6162 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
6163 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
6164 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
6165 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
6166 hasdefaults = false;
6168 for (j = 0; j < ntups; j++)
6170 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
6172 "invalid column numbering in table \"%s\"\n",
6174 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6175 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6176 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6177 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6178 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6179 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6180 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6181 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6182 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6183 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6184 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6185 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6186 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6187 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6188 tbinfo->attrdefs[j] = NULL; /* fix below */
6189 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6191 /* these flags will be set in flagInhAttrs() */
6192 tbinfo->inhNotNull[j] = false;
6198 * Get info about column defaults
6202 AttrDefInfo *attrdefs;
6206 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6209 resetPQExpBuffer(q);
6210 if (fout->remoteVersion >= 70300)
6212 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6213 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6214 "FROM pg_catalog.pg_attrdef "
6215 "WHERE adrelid = '%u'::pg_catalog.oid",
6216 tbinfo->dobj.catId.oid);
6218 else if (fout->remoteVersion >= 70200)
6220 /* 7.2 did not have OIDs in pg_attrdef */
6221 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6222 "pg_get_expr(adbin, adrelid) AS adsrc "
6224 "WHERE adrelid = '%u'::oid",
6225 tbinfo->dobj.catId.oid);
6227 else if (fout->remoteVersion >= 70100)
6229 /* no pg_get_expr, so must rely on adsrc */
6230 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6232 "WHERE adrelid = '%u'::oid",
6233 tbinfo->dobj.catId.oid);
6237 /* no pg_get_expr, no tableoid either */
6238 appendPQExpBuffer(q, "SELECT "
6239 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6240 "oid, adnum, adsrc "
6242 "WHERE adrelid = '%u'::oid",
6243 tbinfo->dobj.catId.oid);
6245 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6247 numDefaults = PQntuples(res);
6248 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6250 for (j = 0; j < numDefaults; j++)
6254 adnum = atoi(PQgetvalue(res, j, 2));
6256 if (adnum <= 0 || adnum > ntups)
6258 "invalid adnum value %d for table \"%s\"\n",
6259 adnum, tbinfo->dobj.name);
6262 * dropped columns shouldn't have defaults, but just in case,
6265 if (tbinfo->attisdropped[adnum - 1])
6268 attrdefs[j].dobj.objType = DO_ATTRDEF;
6269 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6270 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6271 AssignDumpId(&attrdefs[j].dobj);
6272 attrdefs[j].adtable = tbinfo;
6273 attrdefs[j].adnum = adnum;
6274 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6276 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6277 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6279 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6282 * Defaults on a VIEW must always be dumped as separate ALTER
6283 * TABLE commands. Defaults on regular tables are dumped as
6284 * part of the CREATE TABLE if possible, which it won't be if
6285 * the column is not going to be emitted explicitly.
6287 if (tbinfo->relkind == RELKIND_VIEW)
6289 attrdefs[j].separate = true;
6290 /* needed in case pre-7.3 DB: */
6291 addObjectDependency(&attrdefs[j].dobj,
6292 tbinfo->dobj.dumpId);
6294 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6296 /* column will be suppressed, print default separately */
6297 attrdefs[j].separate = true;
6298 /* needed in case pre-7.3 DB: */
6299 addObjectDependency(&attrdefs[j].dobj,
6300 tbinfo->dobj.dumpId);
6304 attrdefs[j].separate = false;
6307 * Mark the default as needing to appear before the table,
6308 * so that any dependencies it has must be emitted before
6309 * the CREATE TABLE. If this is not possible, we'll
6310 * change to "separate" mode while sorting dependencies.
6312 addObjectDependency(&tbinfo->dobj,
6313 attrdefs[j].dobj.dumpId);
6316 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6322 * Get info about table CHECK constraints
6324 if (tbinfo->ncheck > 0)
6326 ConstraintInfo *constrs;
6330 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6333 resetPQExpBuffer(q);
6334 if (fout->remoteVersion >= 90200)
6337 * convalidated is new in 9.2 (actually, it is there in 9.1,
6338 * but it wasn't ever false for check constraints until 9.2).
6340 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6341 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6342 "conislocal, convalidated "
6343 "FROM pg_catalog.pg_constraint "
6344 "WHERE conrelid = '%u'::pg_catalog.oid "
6345 " AND contype = 'c' "
6347 tbinfo->dobj.catId.oid);
6349 else if (fout->remoteVersion >= 80400)
6351 /* conislocal is new in 8.4 */
6352 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6353 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6354 "conislocal, true AS convalidated "
6355 "FROM pg_catalog.pg_constraint "
6356 "WHERE conrelid = '%u'::pg_catalog.oid "
6357 " AND contype = 'c' "
6359 tbinfo->dobj.catId.oid);
6361 else if (fout->remoteVersion >= 70400)
6363 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6364 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6365 "true AS conislocal, true AS convalidated "
6366 "FROM pg_catalog.pg_constraint "
6367 "WHERE conrelid = '%u'::pg_catalog.oid "
6368 " AND contype = 'c' "
6370 tbinfo->dobj.catId.oid);
6372 else if (fout->remoteVersion >= 70300)
6374 /* no pg_get_constraintdef, must use consrc */
6375 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6376 "'CHECK (' || consrc || ')' AS consrc, "
6377 "true AS conislocal, true AS convalidated "
6378 "FROM pg_catalog.pg_constraint "
6379 "WHERE conrelid = '%u'::pg_catalog.oid "
6380 " AND contype = 'c' "
6382 tbinfo->dobj.catId.oid);
6384 else if (fout->remoteVersion >= 70200)
6386 /* 7.2 did not have OIDs in pg_relcheck */
6387 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6388 "rcname AS conname, "
6389 "'CHECK (' || rcsrc || ')' AS consrc, "
6390 "true AS conislocal, true AS convalidated "
6392 "WHERE rcrelid = '%u'::oid "
6394 tbinfo->dobj.catId.oid);
6396 else if (fout->remoteVersion >= 70100)
6398 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6399 "rcname AS conname, "
6400 "'CHECK (' || rcsrc || ')' AS consrc, "
6401 "true AS conislocal, true AS convalidated "
6403 "WHERE rcrelid = '%u'::oid "
6405 tbinfo->dobj.catId.oid);
6409 /* no tableoid in 7.0 */
6410 appendPQExpBuffer(q, "SELECT "
6411 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6412 "oid, rcname AS conname, "
6413 "'CHECK (' || rcsrc || ')' AS consrc, "
6414 "true AS conislocal, true AS convalidated "
6416 "WHERE rcrelid = '%u'::oid "
6418 tbinfo->dobj.catId.oid);
6420 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6422 numConstrs = PQntuples(res);
6423 if (numConstrs != tbinfo->ncheck)
6425 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6426 "expected %d check constraints on table \"%s\" but found %d\n",
6428 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6429 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6433 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6434 tbinfo->checkexprs = constrs;
6436 for (j = 0; j < numConstrs; j++)
6438 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6440 constrs[j].dobj.objType = DO_CONSTRAINT;
6441 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6442 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6443 AssignDumpId(&constrs[j].dobj);
6444 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6445 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6446 constrs[j].contable = tbinfo;
6447 constrs[j].condomain = NULL;
6448 constrs[j].contype = 'c';
6449 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6450 constrs[j].confrelid = InvalidOid;
6451 constrs[j].conindex = 0;
6452 constrs[j].condeferrable = false;
6453 constrs[j].condeferred = false;
6454 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6457 * An unvalidated constraint needs to be dumped separately, so
6458 * that potentially-violating existing data is loaded before
6461 constrs[j].separate = !validated;
6463 constrs[j].dobj.dump = tbinfo->dobj.dump;
6466 * Mark the constraint as needing to appear before the table
6467 * --- this is so that any other dependencies of the
6468 * constraint will be emitted before we try to create the
6469 * table. If the constraint is to be dumped separately, it
6470 * will be dumped after data is loaded anyway, so don't do it.
6471 * (There's an automatic dependency in the opposite direction
6472 * anyway, so don't need to add one manually here.)
6474 if (!constrs[j].separate)
6475 addObjectDependency(&tbinfo->dobj,
6476 constrs[j].dobj.dumpId);
6479 * If the constraint is inherited, this will be detected later
6480 * (in pre-8.4 databases). We also detect later if the
6481 * constraint must be split out from the table definition.
6488 destroyPQExpBuffer(q);
6492 * Test whether a column should be printed as part of table's CREATE TABLE.
6493 * Column number is zero-based.
6495 * Normally this is always true, but it's false for dropped columns, as well
6496 * as those that were inherited without any local definition. (If we print
6497 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6498 * However, in binary_upgrade mode, we must print all such columns anyway and
6499 * fix the attislocal/attisdropped state later, so as to keep control of the
6500 * physical column order.
6502 * This function exists because there are scattered nonobvious places that
6503 * must be kept in sync with this decision.
6506 shouldPrintColumn(TableInfo *tbinfo, int colno)
6510 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6516 * read all text search parsers in the system catalogs and return them
6517 * in the TSParserInfo* structure
6519 * numTSParsers is set to the number of parsers read in
6522 getTSParsers(Archive *fout, int *numTSParsers)
6528 TSParserInfo *prsinfo;
6539 /* Before 8.3, there is no built-in text search support */
6540 if (fout->remoteVersion < 80300)
6546 query = createPQExpBuffer();
6549 * find all text search objects, including builtin ones; we filter out
6550 * system-defined objects at dump-out time.
6553 /* Make sure we are in proper schema */
6554 selectSourceSchema(fout, "pg_catalog");
6556 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6557 "prsstart::oid, prstoken::oid, "
6558 "prsend::oid, prsheadline::oid, prslextype::oid "
6559 "FROM pg_ts_parser");
6561 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6563 ntups = PQntuples(res);
6564 *numTSParsers = ntups;
6566 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6568 i_tableoid = PQfnumber(res, "tableoid");
6569 i_oid = PQfnumber(res, "oid");
6570 i_prsname = PQfnumber(res, "prsname");
6571 i_prsnamespace = PQfnumber(res, "prsnamespace");
6572 i_prsstart = PQfnumber(res, "prsstart");
6573 i_prstoken = PQfnumber(res, "prstoken");
6574 i_prsend = PQfnumber(res, "prsend");
6575 i_prsheadline = PQfnumber(res, "prsheadline");
6576 i_prslextype = PQfnumber(res, "prslextype");
6578 for (i = 0; i < ntups; i++)
6580 prsinfo[i].dobj.objType = DO_TSPARSER;
6581 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6582 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6583 AssignDumpId(&prsinfo[i].dobj);
6584 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6585 prsinfo[i].dobj.namespace =
6587 atooid(PQgetvalue(res, i, i_prsnamespace)),
6588 prsinfo[i].dobj.catId.oid);
6589 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6590 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6591 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6592 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6593 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6595 /* Decide whether we want to dump it */
6596 selectDumpableObject(&(prsinfo[i].dobj));
6601 destroyPQExpBuffer(query);
6607 * getTSDictionaries:
6608 * read all text search dictionaries in the system catalogs and return them
6609 * in the TSDictInfo* structure
6611 * numTSDicts is set to the number of dictionaries read in
6614 getTSDictionaries(Archive *fout, int *numTSDicts)
6620 TSDictInfo *dictinfo;
6624 int i_dictnamespace;
6627 int i_dictinitoption;
6629 /* Before 8.3, there is no built-in text search support */
6630 if (fout->remoteVersion < 80300)
6636 query = createPQExpBuffer();
6638 /* Make sure we are in proper schema */
6639 selectSourceSchema(fout, "pg_catalog");
6641 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6642 "dictnamespace, (%s dictowner) AS rolname, "
6643 "dicttemplate, dictinitoption "
6647 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6649 ntups = PQntuples(res);
6650 *numTSDicts = ntups;
6652 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6654 i_tableoid = PQfnumber(res, "tableoid");
6655 i_oid = PQfnumber(res, "oid");
6656 i_dictname = PQfnumber(res, "dictname");
6657 i_dictnamespace = PQfnumber(res, "dictnamespace");
6658 i_rolname = PQfnumber(res, "rolname");
6659 i_dictinitoption = PQfnumber(res, "dictinitoption");
6660 i_dicttemplate = PQfnumber(res, "dicttemplate");
6662 for (i = 0; i < ntups; i++)
6664 dictinfo[i].dobj.objType = DO_TSDICT;
6665 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6666 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6667 AssignDumpId(&dictinfo[i].dobj);
6668 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6669 dictinfo[i].dobj.namespace =
6671 atooid(PQgetvalue(res, i, i_dictnamespace)),
6672 dictinfo[i].dobj.catId.oid);
6673 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6674 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6675 if (PQgetisnull(res, i, i_dictinitoption))
6676 dictinfo[i].dictinitoption = NULL;
6678 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6680 /* Decide whether we want to dump it */
6681 selectDumpableObject(&(dictinfo[i].dobj));
6686 destroyPQExpBuffer(query);
6693 * read all text search templates in the system catalogs and return them
6694 * in the TSTemplateInfo* structure
6696 * numTSTemplates is set to the number of templates read in
6699 getTSTemplates(Archive *fout, int *numTSTemplates)
6705 TSTemplateInfo *tmplinfo;
6709 int i_tmplnamespace;
6713 /* Before 8.3, there is no built-in text search support */
6714 if (fout->remoteVersion < 80300)
6716 *numTSTemplates = 0;
6720 query = createPQExpBuffer();
6722 /* Make sure we are in proper schema */
6723 selectSourceSchema(fout, "pg_catalog");
6725 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6726 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6727 "FROM pg_ts_template");
6729 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6731 ntups = PQntuples(res);
6732 *numTSTemplates = ntups;
6734 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6736 i_tableoid = PQfnumber(res, "tableoid");
6737 i_oid = PQfnumber(res, "oid");
6738 i_tmplname = PQfnumber(res, "tmplname");
6739 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6740 i_tmplinit = PQfnumber(res, "tmplinit");
6741 i_tmpllexize = PQfnumber(res, "tmpllexize");
6743 for (i = 0; i < ntups; i++)
6745 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6746 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6747 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6748 AssignDumpId(&tmplinfo[i].dobj);
6749 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6750 tmplinfo[i].dobj.namespace =
6752 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6753 tmplinfo[i].dobj.catId.oid);
6754 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6755 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6757 /* Decide whether we want to dump it */
6758 selectDumpableObject(&(tmplinfo[i].dobj));
6763 destroyPQExpBuffer(query);
6769 * getTSConfigurations:
6770 * read all text search configurations in the system catalogs and return
6771 * them in the TSConfigInfo* structure
6773 * numTSConfigs is set to the number of configurations read in
6776 getTSConfigurations(Archive *fout, int *numTSConfigs)
6782 TSConfigInfo *cfginfo;
6790 /* Before 8.3, there is no built-in text search support */
6791 if (fout->remoteVersion < 80300)
6797 query = createPQExpBuffer();
6799 /* Make sure we are in proper schema */
6800 selectSourceSchema(fout, "pg_catalog");
6802 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6803 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6804 "FROM pg_ts_config",
6807 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6809 ntups = PQntuples(res);
6810 *numTSConfigs = ntups;
6812 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6814 i_tableoid = PQfnumber(res, "tableoid");
6815 i_oid = PQfnumber(res, "oid");
6816 i_cfgname = PQfnumber(res, "cfgname");
6817 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6818 i_rolname = PQfnumber(res, "rolname");
6819 i_cfgparser = PQfnumber(res, "cfgparser");
6821 for (i = 0; i < ntups; i++)
6823 cfginfo[i].dobj.objType = DO_TSCONFIG;
6824 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6825 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6826 AssignDumpId(&cfginfo[i].dobj);
6827 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6828 cfginfo[i].dobj.namespace =
6830 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6831 cfginfo[i].dobj.catId.oid);
6832 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6833 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6835 /* Decide whether we want to dump it */
6836 selectDumpableObject(&(cfginfo[i].dobj));
6841 destroyPQExpBuffer(query);
6847 * getForeignDataWrappers:
6848 * read all foreign-data wrappers in the system catalogs and return
6849 * them in the FdwInfo* structure
6851 * numForeignDataWrappers is set to the number of fdws read in
6854 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6859 PQExpBuffer query = createPQExpBuffer();
6870 /* Before 8.4, there are no foreign-data wrappers */
6871 if (fout->remoteVersion < 80400)
6873 *numForeignDataWrappers = 0;
6877 /* Make sure we are in proper schema */
6878 selectSourceSchema(fout, "pg_catalog");
6880 if (fout->remoteVersion >= 90100)
6882 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6883 "(%s fdwowner) AS rolname, "
6884 "fdwhandler::pg_catalog.regproc, "
6885 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6886 "array_to_string(ARRAY("
6887 "SELECT quote_ident(option_name) || ' ' || "
6888 "quote_literal(option_value) "
6889 "FROM pg_options_to_table(fdwoptions) "
6890 "ORDER BY option_name"
6891 "), E',\n ') AS fdwoptions "
6892 "FROM pg_foreign_data_wrapper",
6897 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6898 "(%s fdwowner) AS rolname, "
6899 "'-' AS fdwhandler, "
6900 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6901 "array_to_string(ARRAY("
6902 "SELECT quote_ident(option_name) || ' ' || "
6903 "quote_literal(option_value) "
6904 "FROM pg_options_to_table(fdwoptions) "
6905 "ORDER BY option_name"
6906 "), E',\n ') AS fdwoptions "
6907 "FROM pg_foreign_data_wrapper",
6911 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6913 ntups = PQntuples(res);
6914 *numForeignDataWrappers = ntups;
6916 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6918 i_tableoid = PQfnumber(res, "tableoid");
6919 i_oid = PQfnumber(res, "oid");
6920 i_fdwname = PQfnumber(res, "fdwname");
6921 i_rolname = PQfnumber(res, "rolname");
6922 i_fdwhandler = PQfnumber(res, "fdwhandler");
6923 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6924 i_fdwacl = PQfnumber(res, "fdwacl");
6925 i_fdwoptions = PQfnumber(res, "fdwoptions");
6927 for (i = 0; i < ntups; i++)
6929 fdwinfo[i].dobj.objType = DO_FDW;
6930 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6931 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6932 AssignDumpId(&fdwinfo[i].dobj);
6933 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6934 fdwinfo[i].dobj.namespace = NULL;
6935 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6936 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6937 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6938 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6939 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6941 /* Decide whether we want to dump it */
6942 selectDumpableObject(&(fdwinfo[i].dobj));
6947 destroyPQExpBuffer(query);
6953 * getForeignServers:
6954 * read all foreign servers in the system catalogs and return
6955 * them in the ForeignServerInfo * structure
6957 * numForeignServers is set to the number of servers read in
6960 getForeignServers(Archive *fout, int *numForeignServers)
6965 PQExpBuffer query = createPQExpBuffer();
6966 ForeignServerInfo *srvinfo;
6977 /* Before 8.4, there are no foreign servers */
6978 if (fout->remoteVersion < 80400)
6980 *numForeignServers = 0;
6984 /* Make sure we are in proper schema */
6985 selectSourceSchema(fout, "pg_catalog");
6987 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6988 "(%s srvowner) AS rolname, "
6989 "srvfdw, srvtype, srvversion, srvacl,"
6990 "array_to_string(ARRAY("
6991 "SELECT quote_ident(option_name) || ' ' || "
6992 "quote_literal(option_value) "
6993 "FROM pg_options_to_table(srvoptions) "
6994 "ORDER BY option_name"
6995 "), E',\n ') AS srvoptions "
6996 "FROM pg_foreign_server",
6999 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7001 ntups = PQntuples(res);
7002 *numForeignServers = ntups;
7004 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
7006 i_tableoid = PQfnumber(res, "tableoid");
7007 i_oid = PQfnumber(res, "oid");
7008 i_srvname = PQfnumber(res, "srvname");
7009 i_rolname = PQfnumber(res, "rolname");
7010 i_srvfdw = PQfnumber(res, "srvfdw");
7011 i_srvtype = PQfnumber(res, "srvtype");
7012 i_srvversion = PQfnumber(res, "srvversion");
7013 i_srvacl = PQfnumber(res, "srvacl");
7014 i_srvoptions = PQfnumber(res, "srvoptions");
7016 for (i = 0; i < ntups; i++)
7018 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
7019 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7020 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7021 AssignDumpId(&srvinfo[i].dobj);
7022 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
7023 srvinfo[i].dobj.namespace = NULL;
7024 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7025 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
7026 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
7027 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
7028 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
7029 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
7031 /* Decide whether we want to dump it */
7032 selectDumpableObject(&(srvinfo[i].dobj));
7037 destroyPQExpBuffer(query);
7044 * read all default ACL information in the system catalogs and return
7045 * them in the DefaultACLInfo structure
7047 * numDefaultACLs is set to the number of ACLs read in
7050 getDefaultACLs(Archive *fout, int *numDefaultACLs)
7052 DefaultACLInfo *daclinfo;
7058 int i_defaclnamespace;
7059 int i_defaclobjtype;
7064 if (fout->remoteVersion < 90000)
7066 *numDefaultACLs = 0;
7070 query = createPQExpBuffer();
7072 /* Make sure we are in proper schema */
7073 selectSourceSchema(fout, "pg_catalog");
7075 appendPQExpBuffer(query, "SELECT oid, tableoid, "
7076 "(%s defaclrole) AS defaclrole, "
7080 "FROM pg_default_acl",
7083 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7085 ntups = PQntuples(res);
7086 *numDefaultACLs = ntups;
7088 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
7090 i_oid = PQfnumber(res, "oid");
7091 i_tableoid = PQfnumber(res, "tableoid");
7092 i_defaclrole = PQfnumber(res, "defaclrole");
7093 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
7094 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
7095 i_defaclacl = PQfnumber(res, "defaclacl");
7097 for (i = 0; i < ntups; i++)
7099 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
7101 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
7102 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7103 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7104 AssignDumpId(&daclinfo[i].dobj);
7105 /* cheesy ... is it worth coming up with a better object name? */
7106 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
7108 if (nspid != InvalidOid)
7109 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
7110 daclinfo[i].dobj.catId.oid);
7112 daclinfo[i].dobj.namespace = NULL;
7114 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
7115 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
7116 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
7118 /* Decide whether we want to dump it */
7119 selectDumpableDefaultACL(&(daclinfo[i]));
7124 destroyPQExpBuffer(query);
7132 * This routine is used to dump any comments associated with the
7133 * object handed to this routine. The routine takes a constant character
7134 * string for the target part of the comment-creation command, plus
7135 * the namespace and owner of the object (for labeling the ArchiveEntry),
7136 * plus catalog ID and subid which are the lookup key for pg_description,
7137 * plus the dump ID for the object (for setting a dependency).
7138 * If a matching pg_description entry is found, it is dumped.
7140 * Note: although this routine takes a dumpId for dependency purposes,
7141 * that purpose is just to mark the dependency in the emitted dump file
7142 * for possible future use by pg_restore. We do NOT use it for determining
7143 * ordering of the comment in the dump file, because this routine is called
7144 * after dependency sorting occurs. This routine should be called just after
7145 * calling ArchiveEntry() for the specified object.
7148 dumpComment(Archive *fout, const char *target,
7149 const char *namespace, const char *owner,
7150 CatalogId catalogId, int subid, DumpId dumpId)
7152 CommentItem *comments;
7155 /* Comments are schema not data ... except blob comments are data */
7156 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
7167 /* Search for comments associated with catalogId, using table */
7168 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
7171 /* Is there one matching the subid? */
7172 while (ncomments > 0)
7174 if (comments->objsubid == subid)
7180 /* If a comment exists, build COMMENT ON statement */
7183 PQExpBuffer query = createPQExpBuffer();
7185 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7186 appendStringLiteralAH(query, comments->descr, fout);
7187 appendPQExpBuffer(query, ";\n");
7190 * We mark comments as SECTION_NONE because they really belong in the
7191 * same section as their parent, whether that is pre-data or
7194 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7195 target, namespace, NULL, owner,
7196 false, "COMMENT", SECTION_NONE,
7197 query->data, "", NULL,
7201 destroyPQExpBuffer(query);
7206 * dumpTableComment --
7208 * As above, but dump comments for both the specified table (or view)
7212 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7213 const char *reltypename)
7215 CommentItem *comments;
7220 /* Comments are SCHEMA not data */
7224 /* Search for comments associated with relation, using table */
7225 ncomments = findComments(fout,
7226 tbinfo->dobj.catId.tableoid,
7227 tbinfo->dobj.catId.oid,
7230 /* If comments exist, build COMMENT ON statements */
7234 query = createPQExpBuffer();
7235 target = createPQExpBuffer();
7237 while (ncomments > 0)
7239 const char *descr = comments->descr;
7240 int objsubid = comments->objsubid;
7244 resetPQExpBuffer(target);
7245 appendPQExpBuffer(target, "%s %s", reltypename,
7246 fmtId(tbinfo->dobj.name));
7248 resetPQExpBuffer(query);
7249 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7250 appendStringLiteralAH(query, descr, fout);
7251 appendPQExpBuffer(query, ";\n");
7253 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7255 tbinfo->dobj.namespace->dobj.name,
7256 NULL, tbinfo->rolname,
7257 false, "COMMENT", SECTION_NONE,
7258 query->data, "", NULL,
7259 &(tbinfo->dobj.dumpId), 1,
7262 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7264 resetPQExpBuffer(target);
7265 appendPQExpBuffer(target, "COLUMN %s.",
7266 fmtId(tbinfo->dobj.name));
7267 appendPQExpBuffer(target, "%s",
7268 fmtId(tbinfo->attnames[objsubid - 1]));
7270 resetPQExpBuffer(query);
7271 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7272 appendStringLiteralAH(query, descr, fout);
7273 appendPQExpBuffer(query, ";\n");
7275 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7277 tbinfo->dobj.namespace->dobj.name,
7278 NULL, tbinfo->rolname,
7279 false, "COMMENT", SECTION_NONE,
7280 query->data, "", NULL,
7281 &(tbinfo->dobj.dumpId), 1,
7289 destroyPQExpBuffer(query);
7290 destroyPQExpBuffer(target);
7296 * Find the comment(s), if any, associated with the given object. All the
7297 * objsubid values associated with the given classoid/objoid are found with
7301 findComments(Archive *fout, Oid classoid, Oid objoid,
7302 CommentItem **items)
7304 /* static storage for table of comments */
7305 static CommentItem *comments = NULL;
7306 static int ncomments = -1;
7308 CommentItem *middle = NULL;
7313 /* Get comments if we didn't already */
7315 ncomments = collectComments(fout, &comments);
7318 * Pre-7.2, pg_description does not contain classoid, so collectComments
7319 * just stores a zero. If there's a collision on object OID, well, you
7320 * get duplicate comments.
7322 if (fout->remoteVersion < 70200)
7326 * Do binary search to find some item matching the object.
7329 high = &comments[ncomments - 1];
7332 middle = low + (high - low) / 2;
7334 if (classoid < middle->classoid)
7336 else if (classoid > middle->classoid)
7338 else if (objoid < middle->objoid)
7340 else if (objoid > middle->objoid)
7343 break; /* found a match */
7346 if (low > high) /* no matches */
7353 * Now determine how many items match the object. The search loop
7354 * invariant still holds: only items between low and high inclusive could
7358 while (middle > low)
7360 if (classoid != middle[-1].classoid ||
7361 objoid != middle[-1].objoid)
7370 while (middle <= high)
7372 if (classoid != middle->classoid ||
7373 objoid != middle->objoid)
7383 * collectComments --
7385 * Construct a table of all comments available for database objects.
7386 * We used to do per-object queries for the comments, but it's much faster
7387 * to pull them all over at once, and on most databases the memory cost
7390 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7393 collectComments(Archive *fout, CommentItem **items)
7403 CommentItem *comments;
7406 * Note we do NOT change source schema here; preserve the caller's
7410 query = createPQExpBuffer();
7412 if (fout->remoteVersion >= 70300)
7414 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7415 "FROM pg_catalog.pg_description "
7416 "ORDER BY classoid, objoid, objsubid");
7418 else if (fout->remoteVersion >= 70200)
7420 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7421 "FROM pg_description "
7422 "ORDER BY classoid, objoid, objsubid");
7426 /* Note: this will fail to find attribute comments in pre-7.2... */
7427 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7428 "FROM pg_description "
7432 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7434 /* Construct lookup table containing OIDs in numeric form */
7436 i_description = PQfnumber(res, "description");
7437 i_classoid = PQfnumber(res, "classoid");
7438 i_objoid = PQfnumber(res, "objoid");
7439 i_objsubid = PQfnumber(res, "objsubid");
7441 ntups = PQntuples(res);
7443 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7445 for (i = 0; i < ntups; i++)
7447 comments[i].descr = PQgetvalue(res, i, i_description);
7448 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7449 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7450 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7453 /* Do NOT free the PGresult since we are keeping pointers into it */
7454 destroyPQExpBuffer(query);
7461 * dumpDumpableObject
7463 * This routine and its subsidiaries are responsible for creating
7464 * ArchiveEntries (TOC objects) for each object to be dumped.
7467 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7469 switch (dobj->objType)
7472 dumpNamespace(fout, (NamespaceInfo *) dobj);
7475 dumpExtension(fout, (ExtensionInfo *) dobj);
7478 dumpType(fout, (TypeInfo *) dobj);
7481 dumpShellType(fout, (ShellTypeInfo *) dobj);
7484 dumpFunc(fout, (FuncInfo *) dobj);
7487 dumpAgg(fout, (AggInfo *) dobj);
7490 dumpOpr(fout, (OprInfo *) dobj);
7493 dumpOpclass(fout, (OpclassInfo *) dobj);
7496 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7499 dumpCollation(fout, (CollInfo *) dobj);
7502 dumpConversion(fout, (ConvInfo *) dobj);
7505 dumpTable(fout, (TableInfo *) dobj);
7508 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7511 dumpIndex(fout, (IndxInfo *) dobj);
7513 case DO_REFRESH_MATVIEW:
7514 refreshMatViewData(fout, (TableDataInfo *) dobj);
7517 dumpRule(fout, (RuleInfo *) dobj);
7520 dumpTrigger(fout, (TriggerInfo *) dobj);
7522 case DO_EVENT_TRIGGER:
7523 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7526 dumpConstraint(fout, (ConstraintInfo *) dobj);
7528 case DO_FK_CONSTRAINT:
7529 dumpConstraint(fout, (ConstraintInfo *) dobj);
7532 dumpProcLang(fout, (ProcLangInfo *) dobj);
7535 dumpCast(fout, (CastInfo *) dobj);
7538 if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7539 dumpSequenceData(fout, (TableDataInfo *) dobj);
7541 dumpTableData(fout, (TableDataInfo *) dobj);
7544 /* table rowtypes and array types are never dumped separately */
7547 dumpTSParser(fout, (TSParserInfo *) dobj);
7550 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7553 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7556 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7559 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7561 case DO_FOREIGN_SERVER:
7562 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7564 case DO_DEFAULT_ACL:
7565 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7568 dumpBlob(fout, (BlobInfo *) dobj);
7571 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7572 dobj->name, NULL, NULL, "",
7573 false, "BLOBS", SECTION_DATA,
7578 case DO_PRE_DATA_BOUNDARY:
7579 case DO_POST_DATA_BOUNDARY:
7580 /* never dumped, nothing to do */
7587 * writes out to fout the queries to recreate a user-defined namespace
7590 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7597 /* Skip if not to be dumped */
7598 if (!nspinfo->dobj.dump || dataOnly)
7601 /* don't dump dummy namespace from pre-7.3 source */
7602 if (strlen(nspinfo->dobj.name) == 0)
7605 q = createPQExpBuffer();
7606 delq = createPQExpBuffer();
7607 labelq = createPQExpBuffer();
7609 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7611 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7613 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7615 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7618 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7620 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7624 false, "SCHEMA", SECTION_PRE_DATA,
7625 q->data, delq->data, NULL,
7629 /* Dump Schema Comments and Security Labels */
7630 dumpComment(fout, labelq->data,
7631 NULL, nspinfo->rolname,
7632 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7633 dumpSecLabel(fout, labelq->data,
7634 NULL, nspinfo->rolname,
7635 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7637 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7638 qnspname, NULL, nspinfo->dobj.name, NULL,
7639 nspinfo->rolname, nspinfo->nspacl);
7643 destroyPQExpBuffer(q);
7644 destroyPQExpBuffer(delq);
7645 destroyPQExpBuffer(labelq);
7650 * writes out to fout the queries to recreate an extension
7653 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7660 /* Skip if not to be dumped */
7661 if (!extinfo->dobj.dump || dataOnly)
7664 q = createPQExpBuffer();
7665 delq = createPQExpBuffer();
7666 labelq = createPQExpBuffer();
7668 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7670 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7672 if (!binary_upgrade)
7675 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7676 * problem if the extension already exists in the target database;
7677 * this is essential for installed-by-default extensions such as
7680 * In binary-upgrade mode, that doesn't work well, so instead we skip
7681 * built-in extensions based on their OIDs; see
7682 * selectDumpableExtension.
7684 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7685 qextname, fmtId(extinfo->namespace));
7692 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7695 * We unconditionally create the extension, so we must drop it if it
7696 * exists. This could happen if the user deleted 'plpgsql' and then
7697 * readded it, causing its oid to be greater than FirstNormalObjectId.
7698 * The FirstNormalObjectId test was kept to avoid repeatedly dropping
7699 * and recreating extensions like 'plpgsql'.
7701 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7703 appendPQExpBuffer(q,
7704 "SELECT binary_upgrade.create_empty_extension(");
7705 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7706 appendPQExpBuffer(q, ", ");
7707 appendStringLiteralAH(q, extinfo->namespace, fout);
7708 appendPQExpBuffer(q, ", ");
7709 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7710 appendStringLiteralAH(q, extinfo->extversion, fout);
7711 appendPQExpBuffer(q, ", ");
7714 * Note that we're pushing extconfig (an OID array) back into
7715 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7716 * preserved in binary upgrade.
7718 if (strlen(extinfo->extconfig) > 2)
7719 appendStringLiteralAH(q, extinfo->extconfig, fout);
7721 appendPQExpBuffer(q, "NULL");
7722 appendPQExpBuffer(q, ", ");
7723 if (strlen(extinfo->extcondition) > 2)
7724 appendStringLiteralAH(q, extinfo->extcondition, fout);
7726 appendPQExpBuffer(q, "NULL");
7727 appendPQExpBuffer(q, ", ");
7728 appendPQExpBuffer(q, "ARRAY[");
7730 for (i = 0; i < extinfo->dobj.nDeps; i++)
7732 DumpableObject *extobj;
7734 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7735 if (extobj && extobj->objType == DO_EXTENSION)
7738 appendPQExpBuffer(q, ",");
7739 appendStringLiteralAH(q, extobj->name, fout);
7742 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7743 appendPQExpBuffer(q, ");\n");
7746 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7748 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7752 false, "EXTENSION", SECTION_PRE_DATA,
7753 q->data, delq->data, NULL,
7757 /* Dump Extension Comments and Security Labels */
7758 dumpComment(fout, labelq->data,
7760 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7761 dumpSecLabel(fout, labelq->data,
7763 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7767 destroyPQExpBuffer(q);
7768 destroyPQExpBuffer(delq);
7769 destroyPQExpBuffer(labelq);
7774 * writes out to fout the queries to recreate a user-defined type
7777 dumpType(Archive *fout, TypeInfo *tyinfo)
7779 /* Skip if not to be dumped */
7780 if (!tyinfo->dobj.dump || dataOnly)
7783 /* Dump out in proper style */
7784 if (tyinfo->typtype == TYPTYPE_BASE)
7785 dumpBaseType(fout, tyinfo);
7786 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7787 dumpDomain(fout, tyinfo);
7788 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7789 dumpCompositeType(fout, tyinfo);
7790 else if (tyinfo->typtype == TYPTYPE_ENUM)
7791 dumpEnumType(fout, tyinfo);
7792 else if (tyinfo->typtype == TYPTYPE_RANGE)
7793 dumpRangeType(fout, tyinfo);
7795 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7801 * writes out to fout the queries to recreate a user-defined enum type
7804 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7806 PQExpBuffer q = createPQExpBuffer();
7807 PQExpBuffer delq = createPQExpBuffer();
7808 PQExpBuffer labelq = createPQExpBuffer();
7809 PQExpBuffer query = createPQExpBuffer();
7817 /* Set proper schema search path */
7818 selectSourceSchema(fout, "pg_catalog");
7820 if (fout->remoteVersion >= 90100)
7821 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7822 "FROM pg_catalog.pg_enum "
7823 "WHERE enumtypid = '%u'"
7824 "ORDER BY enumsortorder",
7825 tyinfo->dobj.catId.oid);
7827 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7828 "FROM pg_catalog.pg_enum "
7829 "WHERE enumtypid = '%u'"
7831 tyinfo->dobj.catId.oid);
7833 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7835 num = PQntuples(res);
7837 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7840 * DROP must be fully qualified in case same name appears in pg_catalog.
7841 * CASCADE shouldn't be required here as for normal types since the I/O
7842 * functions are generic and do not get dropped.
7844 appendPQExpBuffer(delq, "DROP TYPE %s.",
7845 fmtId(tyinfo->dobj.namespace->dobj.name));
7846 appendPQExpBuffer(delq, "%s;\n",
7850 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7851 tyinfo->dobj.catId.oid);
7853 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7856 if (!binary_upgrade)
7858 /* Labels with server-assigned oids */
7859 for (i = 0; i < num; i++)
7861 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7863 appendPQExpBuffer(q, ",");
7864 appendPQExpBuffer(q, "\n ");
7865 appendStringLiteralAH(q, label, fout);
7869 appendPQExpBuffer(q, "\n);\n");
7873 /* Labels with dump-assigned (preserved) oids */
7874 for (i = 0; i < num; i++)
7876 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7877 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7880 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7881 appendPQExpBuffer(q,
7882 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7884 appendPQExpBuffer(q, "ALTER TYPE %s.",
7885 fmtId(tyinfo->dobj.namespace->dobj.name));
7886 appendPQExpBuffer(q, "%s ADD VALUE ",
7888 appendStringLiteralAH(q, label, fout);
7889 appendPQExpBuffer(q, ";\n\n");
7893 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
7896 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7898 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7900 tyinfo->dobj.namespace->dobj.name,
7902 tyinfo->rolname, false,
7903 "TYPE", SECTION_PRE_DATA,
7904 q->data, delq->data, NULL,
7908 /* Dump Type Comments and Security Labels */
7909 dumpComment(fout, labelq->data,
7910 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7911 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7912 dumpSecLabel(fout, labelq->data,
7913 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7914 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7916 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
7917 qtypname, NULL, tyinfo->dobj.name,
7918 tyinfo->dobj.namespace->dobj.name,
7919 tyinfo->rolname, tyinfo->typacl);
7922 destroyPQExpBuffer(q);
7923 destroyPQExpBuffer(delq);
7924 destroyPQExpBuffer(labelq);
7925 destroyPQExpBuffer(query);
7930 * writes out to fout the queries to recreate a user-defined range type
7933 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7935 PQExpBuffer q = createPQExpBuffer();
7936 PQExpBuffer delq = createPQExpBuffer();
7937 PQExpBuffer labelq = createPQExpBuffer();
7938 PQExpBuffer query = createPQExpBuffer();
7945 * select appropriate schema to ensure names in CREATE are properly
7948 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7950 appendPQExpBuffer(query,
7951 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7952 "opc.opcname AS opcname, "
7953 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7954 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7956 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7957 " ELSE rngcollation END AS collation, "
7958 "rngcanonical, rngsubdiff "
7959 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7960 " pg_catalog.pg_opclass opc "
7961 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7963 tyinfo->dobj.catId.oid);
7965 res = ExecuteSqlQueryForSingleRow(fout, query->data);
7967 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
7970 * DROP must be fully qualified in case same name appears in pg_catalog.
7971 * CASCADE shouldn't be required here as for normal types since the I/O
7972 * functions are generic and do not get dropped.
7974 appendPQExpBuffer(delq, "DROP TYPE %s.",
7975 fmtId(tyinfo->dobj.namespace->dobj.name));
7976 appendPQExpBuffer(delq, "%s;\n",
7980 binary_upgrade_set_type_oids_by_type_oid(fout,
7981 q, tyinfo->dobj.catId.oid);
7983 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7986 appendPQExpBuffer(q, "\n subtype = %s",
7987 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7989 /* print subtype_opclass only if not default for subtype */
7990 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7992 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7993 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7995 /* always schema-qualify, don't try to be smart */
7996 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7998 appendPQExpBuffer(q, "%s", fmtId(opcname));
8001 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
8002 if (OidIsValid(collationOid))
8004 CollInfo *coll = findCollationByOid(collationOid);
8008 /* always schema-qualify, don't try to be smart */
8009 appendPQExpBuffer(q, ",\n collation = %s.",
8010 fmtId(coll->dobj.namespace->dobj.name));
8011 appendPQExpBuffer(q, "%s",
8012 fmtId(coll->dobj.name));
8016 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
8017 if (strcmp(procname, "-") != 0)
8018 appendPQExpBuffer(q, ",\n canonical = %s", procname);
8020 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
8021 if (strcmp(procname, "-") != 0)
8022 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
8024 appendPQExpBuffer(q, "\n);\n");
8026 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8029 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8031 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8033 tyinfo->dobj.namespace->dobj.name,
8035 tyinfo->rolname, false,
8036 "TYPE", SECTION_PRE_DATA,
8037 q->data, delq->data, NULL,
8041 /* Dump Type Comments and Security Labels */
8042 dumpComment(fout, labelq->data,
8043 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8044 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8045 dumpSecLabel(fout, labelq->data,
8046 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8047 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8049 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8050 qtypname, NULL, tyinfo->dobj.name,
8051 tyinfo->dobj.namespace->dobj.name,
8052 tyinfo->rolname, tyinfo->typacl);
8055 destroyPQExpBuffer(q);
8056 destroyPQExpBuffer(delq);
8057 destroyPQExpBuffer(labelq);
8058 destroyPQExpBuffer(query);
8063 * writes out to fout the queries to recreate a user-defined base type
8066 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
8068 PQExpBuffer q = createPQExpBuffer();
8069 PQExpBuffer delq = createPQExpBuffer();
8070 PQExpBuffer labelq = createPQExpBuffer();
8071 PQExpBuffer query = createPQExpBuffer();
8088 char *typispreferred;
8093 char *typcollatable;
8095 bool typdefault_is_literal = false;
8097 /* Set proper schema search path so regproc references list correctly */
8098 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8100 /* Fetch type-specific details */
8101 if (fout->remoteVersion >= 90100)
8103 appendPQExpBuffer(query, "SELECT typlen, "
8104 "typinput, typoutput, typreceive, typsend, "
8105 "typmodin, typmodout, typanalyze, "
8106 "typreceive::pg_catalog.oid AS typreceiveoid, "
8107 "typsend::pg_catalog.oid AS typsendoid, "
8108 "typmodin::pg_catalog.oid AS typmodinoid, "
8109 "typmodout::pg_catalog.oid AS typmodoutoid, "
8110 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8111 "typcategory, typispreferred, "
8112 "typdelim, typbyval, typalign, typstorage, "
8113 "(typcollation <> 0) AS typcollatable, "
8114 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8115 "FROM pg_catalog.pg_type "
8116 "WHERE oid = '%u'::pg_catalog.oid",
8117 tyinfo->dobj.catId.oid);
8119 else if (fout->remoteVersion >= 80400)
8121 appendPQExpBuffer(query, "SELECT typlen, "
8122 "typinput, typoutput, typreceive, typsend, "
8123 "typmodin, typmodout, typanalyze, "
8124 "typreceive::pg_catalog.oid AS typreceiveoid, "
8125 "typsend::pg_catalog.oid AS typsendoid, "
8126 "typmodin::pg_catalog.oid AS typmodinoid, "
8127 "typmodout::pg_catalog.oid AS typmodoutoid, "
8128 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8129 "typcategory, typispreferred, "
8130 "typdelim, typbyval, typalign, typstorage, "
8131 "false AS typcollatable, "
8132 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8133 "FROM pg_catalog.pg_type "
8134 "WHERE oid = '%u'::pg_catalog.oid",
8135 tyinfo->dobj.catId.oid);
8137 else if (fout->remoteVersion >= 80300)
8139 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
8140 appendPQExpBuffer(query, "SELECT typlen, "
8141 "typinput, typoutput, typreceive, typsend, "
8142 "typmodin, typmodout, typanalyze, "
8143 "typreceive::pg_catalog.oid AS typreceiveoid, "
8144 "typsend::pg_catalog.oid AS typsendoid, "
8145 "typmodin::pg_catalog.oid AS typmodinoid, "
8146 "typmodout::pg_catalog.oid AS typmodoutoid, "
8147 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8148 "'U' AS typcategory, false AS typispreferred, "
8149 "typdelim, typbyval, typalign, typstorage, "
8150 "false AS typcollatable, "
8151 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8152 "FROM pg_catalog.pg_type "
8153 "WHERE oid = '%u'::pg_catalog.oid",
8154 tyinfo->dobj.catId.oid);
8156 else if (fout->remoteVersion >= 80000)
8158 appendPQExpBuffer(query, "SELECT typlen, "
8159 "typinput, typoutput, typreceive, typsend, "
8160 "'-' AS typmodin, '-' AS typmodout, "
8162 "typreceive::pg_catalog.oid AS typreceiveoid, "
8163 "typsend::pg_catalog.oid AS typsendoid, "
8164 "0 AS typmodinoid, 0 AS typmodoutoid, "
8165 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8166 "'U' AS typcategory, false AS typispreferred, "
8167 "typdelim, typbyval, typalign, typstorage, "
8168 "false AS typcollatable, "
8169 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8170 "FROM pg_catalog.pg_type "
8171 "WHERE oid = '%u'::pg_catalog.oid",
8172 tyinfo->dobj.catId.oid);
8174 else if (fout->remoteVersion >= 70400)
8176 appendPQExpBuffer(query, "SELECT typlen, "
8177 "typinput, typoutput, typreceive, typsend, "
8178 "'-' AS typmodin, '-' AS typmodout, "
8179 "'-' AS typanalyze, "
8180 "typreceive::pg_catalog.oid AS typreceiveoid, "
8181 "typsend::pg_catalog.oid AS typsendoid, "
8182 "0 AS typmodinoid, 0 AS typmodoutoid, "
8183 "0 AS typanalyzeoid, "
8184 "'U' AS typcategory, false AS typispreferred, "
8185 "typdelim, typbyval, typalign, typstorage, "
8186 "false AS typcollatable, "
8187 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8188 "FROM pg_catalog.pg_type "
8189 "WHERE oid = '%u'::pg_catalog.oid",
8190 tyinfo->dobj.catId.oid);
8192 else if (fout->remoteVersion >= 70300)
8194 appendPQExpBuffer(query, "SELECT typlen, "
8195 "typinput, typoutput, "
8196 "'-' AS typreceive, '-' AS typsend, "
8197 "'-' AS typmodin, '-' AS typmodout, "
8198 "'-' AS typanalyze, "
8199 "0 AS typreceiveoid, 0 AS typsendoid, "
8200 "0 AS typmodinoid, 0 AS typmodoutoid, "
8201 "0 AS typanalyzeoid, "
8202 "'U' AS typcategory, false AS typispreferred, "
8203 "typdelim, typbyval, typalign, typstorage, "
8204 "false AS typcollatable, "
8205 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8206 "FROM pg_catalog.pg_type "
8207 "WHERE oid = '%u'::pg_catalog.oid",
8208 tyinfo->dobj.catId.oid);
8210 else if (fout->remoteVersion >= 70200)
8213 * Note: although pre-7.3 catalogs contain typreceive and typsend,
8214 * ignore them because they are not right.
8216 appendPQExpBuffer(query, "SELECT typlen, "
8217 "typinput, typoutput, "
8218 "'-' AS typreceive, '-' AS typsend, "
8219 "'-' AS typmodin, '-' AS typmodout, "
8220 "'-' AS typanalyze, "
8221 "0 AS typreceiveoid, 0 AS typsendoid, "
8222 "0 AS typmodinoid, 0 AS typmodoutoid, "
8223 "0 AS typanalyzeoid, "
8224 "'U' AS typcategory, false AS typispreferred, "
8225 "typdelim, typbyval, typalign, typstorage, "
8226 "false AS typcollatable, "
8227 "NULL AS typdefaultbin, typdefault "
8229 "WHERE oid = '%u'::oid",
8230 tyinfo->dobj.catId.oid);
8232 else if (fout->remoteVersion >= 70100)
8235 * Ignore pre-7.2 typdefault; the field exists but has an unusable
8238 appendPQExpBuffer(query, "SELECT typlen, "
8239 "typinput, typoutput, "
8240 "'-' AS typreceive, '-' AS typsend, "
8241 "'-' AS typmodin, '-' AS typmodout, "
8242 "'-' AS typanalyze, "
8243 "0 AS typreceiveoid, 0 AS typsendoid, "
8244 "0 AS typmodinoid, 0 AS typmodoutoid, "
8245 "0 AS typanalyzeoid, "
8246 "'U' AS typcategory, false AS typispreferred, "
8247 "typdelim, typbyval, typalign, typstorage, "
8248 "false AS typcollatable, "
8249 "NULL AS typdefaultbin, NULL AS typdefault "
8251 "WHERE oid = '%u'::oid",
8252 tyinfo->dobj.catId.oid);
8256 appendPQExpBuffer(query, "SELECT typlen, "
8257 "typinput, typoutput, "
8258 "'-' AS typreceive, '-' AS typsend, "
8259 "'-' AS typmodin, '-' AS typmodout, "
8260 "'-' AS typanalyze, "
8261 "0 AS typreceiveoid, 0 AS typsendoid, "
8262 "0 AS typmodinoid, 0 AS typmodoutoid, "
8263 "0 AS typanalyzeoid, "
8264 "'U' AS typcategory, false AS typispreferred, "
8265 "typdelim, typbyval, typalign, "
8266 "'p'::char AS typstorage, "
8267 "false AS typcollatable, "
8268 "NULL AS typdefaultbin, NULL AS typdefault "
8270 "WHERE oid = '%u'::oid",
8271 tyinfo->dobj.catId.oid);
8274 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8276 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8277 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8278 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8279 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8280 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8281 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8282 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8283 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8284 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8285 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8286 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8287 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8288 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8289 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8290 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8291 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8292 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8293 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8294 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8295 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8296 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8297 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8298 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8300 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8301 typdefault_is_literal = true; /* it needs quotes */
8306 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8309 * DROP must be fully qualified in case same name appears in pg_catalog.
8310 * The reason we include CASCADE is that the circular dependency between
8311 * the type and its I/O functions makes it impossible to drop the type any
8314 appendPQExpBuffer(delq, "DROP TYPE %s.",
8315 fmtId(tyinfo->dobj.namespace->dobj.name));
8316 appendPQExpBuffer(delq, "%s CASCADE;\n",
8319 /* We might already have a shell type, but setting pg_type_oid is harmless */
8321 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8322 tyinfo->dobj.catId.oid);
8324 appendPQExpBuffer(q,
8325 "CREATE TYPE %s (\n"
8326 " INTERNALLENGTH = %s",
8328 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8330 if (fout->remoteVersion >= 70300)
8332 /* regproc result is correctly quoted as of 7.3 */
8333 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8334 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8335 if (OidIsValid(typreceiveoid))
8336 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8337 if (OidIsValid(typsendoid))
8338 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8339 if (OidIsValid(typmodinoid))
8340 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8341 if (OidIsValid(typmodoutoid))
8342 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8343 if (OidIsValid(typanalyzeoid))
8344 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8348 /* regproc delivers an unquoted name before 7.3 */
8349 /* cannot combine these because fmtId uses static result area */
8350 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8351 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8352 /* receive/send/typmodin/typmodout/analyze need not be printed */
8355 if (strcmp(typcollatable, "t") == 0)
8356 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8358 if (typdefault != NULL)
8360 appendPQExpBuffer(q, ",\n DEFAULT = ");
8361 if (typdefault_is_literal)
8362 appendStringLiteralAH(q, typdefault, fout);
8364 appendPQExpBufferStr(q, typdefault);
8367 if (OidIsValid(tyinfo->typelem))
8371 /* reselect schema in case changed by function dump */
8372 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8373 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8374 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8378 if (strcmp(typcategory, "U") != 0)
8380 appendPQExpBuffer(q, ",\n CATEGORY = ");
8381 appendStringLiteralAH(q, typcategory, fout);
8384 if (strcmp(typispreferred, "t") == 0)
8385 appendPQExpBuffer(q, ",\n PREFERRED = true");
8387 if (typdelim && strcmp(typdelim, ",") != 0)
8389 appendPQExpBuffer(q, ",\n DELIMITER = ");
8390 appendStringLiteralAH(q, typdelim, fout);
8393 if (strcmp(typalign, "c") == 0)
8394 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8395 else if (strcmp(typalign, "s") == 0)
8396 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8397 else if (strcmp(typalign, "i") == 0)
8398 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8399 else if (strcmp(typalign, "d") == 0)
8400 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8402 if (strcmp(typstorage, "p") == 0)
8403 appendPQExpBuffer(q, ",\n STORAGE = plain");
8404 else if (strcmp(typstorage, "e") == 0)
8405 appendPQExpBuffer(q, ",\n STORAGE = external");
8406 else if (strcmp(typstorage, "x") == 0)
8407 appendPQExpBuffer(q, ",\n STORAGE = extended");
8408 else if (strcmp(typstorage, "m") == 0)
8409 appendPQExpBuffer(q, ",\n STORAGE = main");
8411 if (strcmp(typbyval, "t") == 0)
8412 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8414 appendPQExpBuffer(q, "\n);\n");
8416 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8419 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8421 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8423 tyinfo->dobj.namespace->dobj.name,
8425 tyinfo->rolname, false,
8426 "TYPE", SECTION_PRE_DATA,
8427 q->data, delq->data, NULL,
8431 /* Dump Type Comments and Security Labels */
8432 dumpComment(fout, labelq->data,
8433 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8434 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8435 dumpSecLabel(fout, labelq->data,
8436 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8437 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8439 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8440 qtypname, NULL, tyinfo->dobj.name,
8441 tyinfo->dobj.namespace->dobj.name,
8442 tyinfo->rolname, tyinfo->typacl);
8445 destroyPQExpBuffer(q);
8446 destroyPQExpBuffer(delq);
8447 destroyPQExpBuffer(labelq);
8448 destroyPQExpBuffer(query);
8453 * writes out to fout the queries to recreate a user-defined domain
8456 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8458 PQExpBuffer q = createPQExpBuffer();
8459 PQExpBuffer delq = createPQExpBuffer();
8460 PQExpBuffer labelq = createPQExpBuffer();
8461 PQExpBuffer query = createPQExpBuffer();
8469 bool typdefault_is_literal = false;
8471 /* Set proper schema search path so type references list correctly */
8472 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8474 /* Fetch domain specific details */
8475 if (fout->remoteVersion >= 90100)
8477 /* typcollation is new in 9.1 */
8478 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8479 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8480 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8482 "CASE WHEN t.typcollation <> u.typcollation "
8483 "THEN t.typcollation ELSE 0 END AS typcollation "
8484 "FROM pg_catalog.pg_type t "
8485 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8486 "WHERE t.oid = '%u'::pg_catalog.oid",
8487 tyinfo->dobj.catId.oid);
8491 /* We assume here that remoteVersion must be at least 70300 */
8492 appendPQExpBuffer(query, "SELECT typnotnull, "
8493 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8494 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8495 "typdefault, 0 AS typcollation "
8496 "FROM pg_catalog.pg_type "
8497 "WHERE oid = '%u'::pg_catalog.oid",
8498 tyinfo->dobj.catId.oid);
8501 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8503 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8504 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8505 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8506 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8507 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8509 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8510 typdefault_is_literal = true; /* it needs quotes */
8514 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8517 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8518 tyinfo->dobj.catId.oid);
8520 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8522 appendPQExpBuffer(q,
8523 "CREATE DOMAIN %s AS %s",
8527 /* Print collation only if different from base type's collation */
8528 if (OidIsValid(typcollation))
8532 coll = findCollationByOid(typcollation);
8535 /* always schema-qualify, don't try to be smart */
8536 appendPQExpBuffer(q, " COLLATE %s.",
8537 fmtId(coll->dobj.namespace->dobj.name));
8538 appendPQExpBuffer(q, "%s",
8539 fmtId(coll->dobj.name));
8543 if (typnotnull[0] == 't')
8544 appendPQExpBuffer(q, " NOT NULL");
8546 if (typdefault != NULL)
8548 appendPQExpBuffer(q, " DEFAULT ");
8549 if (typdefault_is_literal)
8550 appendStringLiteralAH(q, typdefault, fout);
8552 appendPQExpBufferStr(q, typdefault);
8558 * Add any CHECK constraints for the domain
8560 for (i = 0; i < tyinfo->nDomChecks; i++)
8562 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8564 if (!domcheck->separate)
8565 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8566 fmtId(domcheck->dobj.name), domcheck->condef);
8569 appendPQExpBuffer(q, ";\n");
8572 * DROP must be fully qualified in case same name appears in pg_catalog
8574 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8575 fmtId(tyinfo->dobj.namespace->dobj.name));
8576 appendPQExpBuffer(delq, "%s;\n",
8579 appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8582 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8584 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8586 tyinfo->dobj.namespace->dobj.name,
8588 tyinfo->rolname, false,
8589 "DOMAIN", SECTION_PRE_DATA,
8590 q->data, delq->data, NULL,
8594 /* Dump Domain Comments and Security Labels */
8595 dumpComment(fout, labelq->data,
8596 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8597 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8598 dumpSecLabel(fout, labelq->data,
8599 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8600 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8602 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8603 qtypname, NULL, tyinfo->dobj.name,
8604 tyinfo->dobj.namespace->dobj.name,
8605 tyinfo->rolname, tyinfo->typacl);
8607 destroyPQExpBuffer(q);
8608 destroyPQExpBuffer(delq);
8609 destroyPQExpBuffer(labelq);
8610 destroyPQExpBuffer(query);
8615 * writes out to fout the queries to recreate a user-defined stand-alone
8619 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8621 PQExpBuffer q = createPQExpBuffer();
8622 PQExpBuffer dropped = createPQExpBuffer();
8623 PQExpBuffer delq = createPQExpBuffer();
8624 PQExpBuffer labelq = createPQExpBuffer();
8625 PQExpBuffer query = createPQExpBuffer();
8639 /* Set proper schema search path so type references list correctly */
8640 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8642 /* Fetch type specific details */
8643 if (fout->remoteVersion >= 90100)
8646 * attcollation is new in 9.1. Since we only want to dump COLLATE
8647 * clauses for attributes whose collation is different from their
8648 * type's default, we use a CASE here to suppress uninteresting
8649 * attcollations cheaply. atttypid will be 0 for dropped columns;
8650 * collation does not matter for those.
8652 appendPQExpBuffer(query, "SELECT a.attname, "
8653 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8654 "a.attlen, a.attalign, a.attisdropped, "
8655 "CASE WHEN a.attcollation <> at.typcollation "
8656 "THEN a.attcollation ELSE 0 END AS attcollation, "
8658 "FROM pg_catalog.pg_type ct "
8659 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8660 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8661 "WHERE ct.oid = '%u'::pg_catalog.oid "
8662 "ORDER BY a.attnum ",
8663 tyinfo->dobj.catId.oid);
8668 * We assume here that remoteVersion must be at least 70300. Since
8669 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8672 appendPQExpBuffer(query, "SELECT a.attname, "
8673 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8674 "a.attlen, a.attalign, a.attisdropped, "
8675 "0 AS attcollation, "
8677 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8678 "WHERE ct.oid = '%u'::pg_catalog.oid "
8679 "AND a.attrelid = ct.typrelid "
8680 "ORDER BY a.attnum ",
8681 tyinfo->dobj.catId.oid);
8684 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8686 ntups = PQntuples(res);
8688 i_attname = PQfnumber(res, "attname");
8689 i_atttypdefn = PQfnumber(res, "atttypdefn");
8690 i_attlen = PQfnumber(res, "attlen");
8691 i_attalign = PQfnumber(res, "attalign");
8692 i_attisdropped = PQfnumber(res, "attisdropped");
8693 i_attcollation = PQfnumber(res, "attcollation");
8694 i_typrelid = PQfnumber(res, "typrelid");
8698 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8700 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8701 tyinfo->dobj.catId.oid);
8702 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8705 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8707 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8711 for (i = 0; i < ntups; i++)
8720 attname = PQgetvalue(res, i, i_attname);
8721 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8722 attlen = PQgetvalue(res, i, i_attlen);
8723 attalign = PQgetvalue(res, i, i_attalign);
8724 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8725 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8727 if (attisdropped && !binary_upgrade)
8730 /* Format properly if not first attr */
8731 if (actual_atts++ > 0)
8732 appendPQExpBuffer(q, ",");
8733 appendPQExpBuffer(q, "\n\t");
8737 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8739 /* Add collation if not default for the column type */
8740 if (OidIsValid(attcollation))
8744 coll = findCollationByOid(attcollation);
8747 /* always schema-qualify, don't try to be smart */
8748 appendPQExpBuffer(q, " COLLATE %s.",
8749 fmtId(coll->dobj.namespace->dobj.name));
8750 appendPQExpBuffer(q, "%s",
8751 fmtId(coll->dobj.name));
8758 * This is a dropped attribute and we're in binary_upgrade mode.
8759 * Insert a placeholder for it in the CREATE TYPE command, and set
8760 * length and alignment with direct UPDATE to the catalogs
8761 * afterwards. See similar code in dumpTableSchema().
8763 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8765 /* stash separately for insertion after the CREATE TYPE */
8766 appendPQExpBuffer(dropped,
8767 "\n-- For binary upgrade, recreate dropped column.\n");
8768 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8770 "attalign = '%s', attbyval = false\n"
8771 "WHERE attname = ", attlen, attalign);
8772 appendStringLiteralAH(dropped, attname, fout);
8773 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8774 appendStringLiteralAH(dropped, qtypname, fout);
8775 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8777 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8779 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8783 appendPQExpBuffer(q, "\n);\n");
8784 appendPQExpBufferStr(q, dropped->data);
8787 * DROP must be fully qualified in case same name appears in pg_catalog
8789 appendPQExpBuffer(delq, "DROP TYPE %s.",
8790 fmtId(tyinfo->dobj.namespace->dobj.name));
8791 appendPQExpBuffer(delq, "%s;\n",
8794 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8797 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8799 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8801 tyinfo->dobj.namespace->dobj.name,
8803 tyinfo->rolname, false,
8804 "TYPE", SECTION_PRE_DATA,
8805 q->data, delq->data, NULL,
8810 /* Dump Type Comments and Security Labels */
8811 dumpComment(fout, labelq->data,
8812 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8813 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8814 dumpSecLabel(fout, labelq->data,
8815 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8816 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8818 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8819 qtypname, NULL, tyinfo->dobj.name,
8820 tyinfo->dobj.namespace->dobj.name,
8821 tyinfo->rolname, tyinfo->typacl);
8824 destroyPQExpBuffer(q);
8825 destroyPQExpBuffer(dropped);
8826 destroyPQExpBuffer(delq);
8827 destroyPQExpBuffer(labelq);
8828 destroyPQExpBuffer(query);
8830 /* Dump any per-column comments */
8831 dumpCompositeTypeColComments(fout, tyinfo);
8835 * dumpCompositeTypeColComments
8836 * writes out to fout the queries to recreate comments on the columns of
8837 * a user-defined stand-alone composite type
8840 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8842 CommentItem *comments;
8853 query = createPQExpBuffer();
8855 /* We assume here that remoteVersion must be at least 70300 */
8856 appendPQExpBuffer(query,
8857 "SELECT c.tableoid, a.attname, a.attnum "
8858 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8859 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8860 " AND NOT a.attisdropped "
8861 "ORDER BY a.attnum ",
8864 /* Fetch column attnames */
8865 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8867 ntups = PQntuples(res);
8871 destroyPQExpBuffer(query);
8875 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8877 /* Search for comments associated with type's pg_class OID */
8878 ncomments = findComments(fout,
8883 /* If no comments exist, we're done */
8887 destroyPQExpBuffer(query);
8891 /* Build COMMENT ON statements */
8892 target = createPQExpBuffer();
8894 i_attnum = PQfnumber(res, "attnum");
8895 i_attname = PQfnumber(res, "attname");
8896 while (ncomments > 0)
8898 const char *attname;
8901 for (i = 0; i < ntups; i++)
8903 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8905 attname = PQgetvalue(res, i, i_attname);
8909 if (attname) /* just in case we don't find it */
8911 const char *descr = comments->descr;
8913 resetPQExpBuffer(target);
8914 appendPQExpBuffer(target, "COLUMN %s.",
8915 fmtId(tyinfo->dobj.name));
8916 appendPQExpBuffer(target, "%s",
8919 resetPQExpBuffer(query);
8920 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8921 appendStringLiteralAH(query, descr, fout);
8922 appendPQExpBuffer(query, ";\n");
8924 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8926 tyinfo->dobj.namespace->dobj.name,
8927 NULL, tyinfo->rolname,
8928 false, "COMMENT", SECTION_NONE,
8929 query->data, "", NULL,
8930 &(tyinfo->dobj.dumpId), 1,
8939 destroyPQExpBuffer(query);
8940 destroyPQExpBuffer(target);
8945 * writes out to fout the queries to create a shell type
8947 * We dump a shell definition in advance of the I/O functions for the type.
8950 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8954 /* Skip if not to be dumped */
8955 if (!stinfo->dobj.dump || dataOnly)
8958 q = createPQExpBuffer();
8961 * Note the lack of a DROP command for the shell type; any required DROP
8962 * is driven off the base type entry, instead. This interacts with
8963 * _printTocEntry()'s use of the presence of a DROP command to decide
8964 * whether an entry needs an ALTER OWNER command. We don't want to alter
8965 * the shell type's owner immediately on creation; that should happen only
8966 * after it's filled in, otherwise the backend complains.
8970 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8971 stinfo->baseType->dobj.catId.oid);
8973 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8974 fmtId(stinfo->dobj.name));
8976 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8978 stinfo->dobj.namespace->dobj.name,
8980 stinfo->baseType->rolname, false,
8981 "SHELL TYPE", SECTION_PRE_DATA,
8986 destroyPQExpBuffer(q);
8990 * Determine whether we want to dump definitions for procedural languages.
8991 * Since the languages themselves don't have schemas, we can't rely on
8992 * the normal schema-based selection mechanism. We choose to dump them
8993 * whenever neither --schema nor --table was given. (Before 8.1, we used
8994 * the dump flag of the PL's call handler function, but in 8.1 this will
8995 * probably always be false since call handlers are created in pg_catalog.)
8997 * For some backwards compatibility with the older behavior, we forcibly
8998 * dump a PL if its handler function (and validator if any) are in a
8999 * dumpable namespace. That case is not checked here.
9001 * Also, if the PL belongs to an extension, we do not use this heuristic.
9002 * That case isn't checked here either.
9005 shouldDumpProcLangs(void)
9007 if (!include_everything)
9009 /* And they're schema not data */
9017 * writes out to fout the queries to recreate a user-defined
9018 * procedural language
9021 dumpProcLang(Archive *fout, ProcLangInfo *plang)
9030 FuncInfo *inlineInfo = NULL;
9031 FuncInfo *validatorInfo = NULL;
9033 /* Skip if not to be dumped */
9034 if (!plang->dobj.dump || dataOnly)
9038 * Try to find the support function(s). It is not an error if we don't
9039 * find them --- if the functions are in the pg_catalog schema, as is
9040 * standard in 8.1 and up, then we won't have loaded them. (In this case
9041 * we will emit a parameterless CREATE LANGUAGE command, which will
9042 * require PL template knowledge in the backend to reload.)
9045 funcInfo = findFuncByOid(plang->lanplcallfoid);
9046 if (funcInfo != NULL && !funcInfo->dobj.dump)
9047 funcInfo = NULL; /* treat not-dumped same as not-found */
9049 if (OidIsValid(plang->laninline))
9051 inlineInfo = findFuncByOid(plang->laninline);
9052 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
9056 if (OidIsValid(plang->lanvalidator))
9058 validatorInfo = findFuncByOid(plang->lanvalidator);
9059 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
9060 validatorInfo = NULL;
9064 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
9065 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
9068 * However, for a language that belongs to an extension, we must not use
9069 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
9070 * told to (via dobj.dump). Generally the support functions will belong
9071 * to the same extension and so have the same dump flags ... if they
9072 * don't, this might not work terribly nicely.
9074 useParams = (funcInfo != NULL &&
9075 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
9076 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
9078 if (!plang->dobj.ext_member)
9080 if (!useParams && !shouldDumpProcLangs())
9084 defqry = createPQExpBuffer();
9085 delqry = createPQExpBuffer();
9086 labelq = createPQExpBuffer();
9088 qlanname = pg_strdup(fmtId(plang->dobj.name));
9091 * If dumping a HANDLER clause, treat the language as being in the handler
9092 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
9093 * it doesn't really have a schema.
9096 lanschema = funcInfo->dobj.namespace->dobj.name;
9100 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
9105 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
9106 plang->lanpltrusted ? "TRUSTED " : "",
9108 appendPQExpBuffer(defqry, " HANDLER %s",
9109 fmtId(funcInfo->dobj.name));
9110 if (OidIsValid(plang->laninline))
9112 appendPQExpBuffer(defqry, " INLINE ");
9113 /* Cope with possibility that inline is in different schema */
9114 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
9115 appendPQExpBuffer(defqry, "%s.",
9116 fmtId(inlineInfo->dobj.namespace->dobj.name));
9117 appendPQExpBuffer(defqry, "%s",
9118 fmtId(inlineInfo->dobj.name));
9120 if (OidIsValid(plang->lanvalidator))
9122 appendPQExpBuffer(defqry, " VALIDATOR ");
9123 /* Cope with possibility that validator is in different schema */
9124 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
9125 appendPQExpBuffer(defqry, "%s.",
9126 fmtId(validatorInfo->dobj.namespace->dobj.name));
9127 appendPQExpBuffer(defqry, "%s",
9128 fmtId(validatorInfo->dobj.name));
9134 * If not dumping parameters, then use CREATE OR REPLACE so that the
9135 * command will not fail if the language is preinstalled in the target
9136 * database. We restrict the use of REPLACE to this case so as to
9137 * eliminate the risk of replacing a language with incompatible
9138 * parameter settings: this command will only succeed at all if there
9139 * is a pg_pltemplate entry, and if there is one, the existing entry
9140 * must match it too.
9142 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
9145 appendPQExpBuffer(defqry, ";\n");
9147 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
9150 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
9152 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
9154 lanschema, NULL, plang->lanowner,
9155 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
9156 defqry->data, delqry->data, NULL,
9160 /* Dump Proc Lang Comments and Security Labels */
9161 dumpComment(fout, labelq->data,
9163 plang->dobj.catId, 0, plang->dobj.dumpId);
9164 dumpSecLabel(fout, labelq->data,
9166 plang->dobj.catId, 0, plang->dobj.dumpId);
9168 if (plang->lanpltrusted)
9169 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
9170 qlanname, NULL, plang->dobj.name,
9172 plang->lanowner, plang->lanacl);
9176 destroyPQExpBuffer(defqry);
9177 destroyPQExpBuffer(delqry);
9178 destroyPQExpBuffer(labelq);
9182 * format_function_arguments: generate function name and argument list
9184 * This is used when we can rely on pg_get_function_arguments to format
9185 * the argument list.
9188 format_function_arguments(FuncInfo *finfo, char *funcargs)
9192 initPQExpBuffer(&fn);
9193 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9198 * format_function_arguments_old: generate function name and argument list
9200 * The argument type names are qualified if needed. The function name
9201 * is never qualified.
9203 * This is used only with pre-8.4 servers, so we aren't expecting to see
9204 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9206 * Any or all of allargtypes, argmodes, argnames may be NULL.
9209 format_function_arguments_old(Archive *fout,
9210 FuncInfo *finfo, int nallargs,
9218 initPQExpBuffer(&fn);
9219 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9220 for (j = 0; j < nallargs; j++)
9224 const char *argmode;
9225 const char *argname;
9227 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9228 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9232 switch (argmodes[j][0])
9237 case PROARGMODE_OUT:
9240 case PROARGMODE_INOUT:
9244 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9252 argname = argnames ? argnames[j] : (char *) NULL;
9253 if (argname && argname[0] == '\0')
9256 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9257 (j > 0) ? ", " : "",
9259 argname ? fmtId(argname) : "",
9264 appendPQExpBuffer(&fn, ")");
9269 * format_function_signature: generate function name and argument list
9271 * This is like format_function_arguments_old except that only a minimal
9272 * list of input argument types is generated; this is sufficient to
9273 * reference the function, but not to define it.
9275 * If honor_quotes is false then the function name is never quoted.
9276 * This is appropriate for use in TOC tags, but not in SQL commands.
9279 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9284 initPQExpBuffer(&fn);
9286 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9288 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9289 for (j = 0; j < finfo->nargs; j++)
9293 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9296 appendPQExpBuffer(&fn, "%s%s",
9297 (j > 0) ? ", " : "",
9301 appendPQExpBuffer(&fn, ")");
9308 * dump out one function
9311 dumpFunc(Archive *fout, FuncInfo *finfo)
9319 char *funcsig; /* identity signature */
9320 char *funcfullsig; /* full signature */
9328 char *proallargtypes;
9342 char **allargtypes = NULL;
9343 char **argmodes = NULL;
9344 char **argnames = NULL;
9345 char **configitems = NULL;
9346 int nconfigitems = 0;
9349 /* Skip if not to be dumped */
9350 if (!finfo->dobj.dump || dataOnly)
9353 query = createPQExpBuffer();
9354 q = createPQExpBuffer();
9355 delqry = createPQExpBuffer();
9356 labelq = createPQExpBuffer();
9357 asPart = createPQExpBuffer();
9359 /* Set proper schema search path so type references list correctly */
9360 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9362 /* Fetch function-specific details */
9363 if (fout->remoteVersion >= 90200)
9366 * proleakproof was added at v9.2
9368 appendPQExpBuffer(query,
9369 "SELECT proretset, prosrc, probin, "
9370 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9371 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9372 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9373 "proiswindow, provolatile, proisstrict, prosecdef, "
9374 "proleakproof, proconfig, procost, prorows, "
9375 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9376 "FROM pg_catalog.pg_proc "
9377 "WHERE oid = '%u'::pg_catalog.oid",
9378 finfo->dobj.catId.oid);
9380 else if (fout->remoteVersion >= 80400)
9383 * In 8.4 and up we rely on pg_get_function_arguments and
9384 * pg_get_function_result instead of examining proallargtypes etc.
9386 appendPQExpBuffer(query,
9387 "SELECT proretset, prosrc, probin, "
9388 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9389 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9390 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9391 "proiswindow, provolatile, proisstrict, prosecdef, "
9392 "false AS proleakproof, "
9393 " proconfig, procost, prorows, "
9394 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9395 "FROM pg_catalog.pg_proc "
9396 "WHERE oid = '%u'::pg_catalog.oid",
9397 finfo->dobj.catId.oid);
9399 else if (fout->remoteVersion >= 80300)
9401 appendPQExpBuffer(query,
9402 "SELECT proretset, prosrc, probin, "
9403 "proallargtypes, proargmodes, proargnames, "
9404 "false AS proiswindow, "
9405 "provolatile, proisstrict, prosecdef, "
9406 "false AS proleakproof, "
9407 "proconfig, procost, prorows, "
9408 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9409 "FROM pg_catalog.pg_proc "
9410 "WHERE oid = '%u'::pg_catalog.oid",
9411 finfo->dobj.catId.oid);
9413 else if (fout->remoteVersion >= 80100)
9415 appendPQExpBuffer(query,
9416 "SELECT proretset, prosrc, probin, "
9417 "proallargtypes, proargmodes, proargnames, "
9418 "false AS proiswindow, "
9419 "provolatile, proisstrict, prosecdef, "
9420 "false AS proleakproof, "
9421 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9422 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9423 "FROM pg_catalog.pg_proc "
9424 "WHERE oid = '%u'::pg_catalog.oid",
9425 finfo->dobj.catId.oid);
9427 else if (fout->remoteVersion >= 80000)
9429 appendPQExpBuffer(query,
9430 "SELECT proretset, prosrc, probin, "
9431 "null AS proallargtypes, "
9432 "null AS proargmodes, "
9434 "false AS proiswindow, "
9435 "provolatile, proisstrict, prosecdef, "
9436 "false AS proleakproof, "
9437 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9438 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9439 "FROM pg_catalog.pg_proc "
9440 "WHERE oid = '%u'::pg_catalog.oid",
9441 finfo->dobj.catId.oid);
9443 else if (fout->remoteVersion >= 70300)
9445 appendPQExpBuffer(query,
9446 "SELECT proretset, prosrc, probin, "
9447 "null AS proallargtypes, "
9448 "null AS proargmodes, "
9449 "null AS proargnames, "
9450 "false AS proiswindow, "
9451 "provolatile, proisstrict, prosecdef, "
9452 "false AS proleakproof, "
9453 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9454 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9455 "FROM pg_catalog.pg_proc "
9456 "WHERE oid = '%u'::pg_catalog.oid",
9457 finfo->dobj.catId.oid);
9459 else if (fout->remoteVersion >= 70100)
9461 appendPQExpBuffer(query,
9462 "SELECT proretset, prosrc, probin, "
9463 "null AS proallargtypes, "
9464 "null AS proargmodes, "
9465 "null AS proargnames, "
9466 "false AS proiswindow, "
9467 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9469 "false AS prosecdef, "
9470 "false AS proleakproof, "
9471 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9472 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9474 "WHERE oid = '%u'::oid",
9475 finfo->dobj.catId.oid);
9479 appendPQExpBuffer(query,
9480 "SELECT proretset, prosrc, probin, "
9481 "null AS proallargtypes, "
9482 "null AS proargmodes, "
9483 "null AS proargnames, "
9484 "false AS proiswindow, "
9485 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9486 "false AS proisstrict, "
9487 "false AS prosecdef, "
9488 "false AS proleakproof, "
9489 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9490 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9492 "WHERE oid = '%u'::oid",
9493 finfo->dobj.catId.oid);
9496 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9498 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9499 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9500 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9501 if (fout->remoteVersion >= 80400)
9503 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9504 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9505 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9506 proallargtypes = proargmodes = proargnames = NULL;
9510 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9511 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9512 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9513 funcargs = funciargs = funcresult = NULL;
9515 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9516 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9517 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9518 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9519 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9520 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9521 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9522 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9523 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9526 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9527 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9528 * versions would set it to "-". There are no known cases in which prosrc
9529 * is unused, so the tests below for "-" are probably useless.
9531 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9533 appendPQExpBuffer(asPart, "AS ");
9534 appendStringLiteralAH(asPart, probin, fout);
9535 if (strcmp(prosrc, "-") != 0)
9537 appendPQExpBuffer(asPart, ", ");
9540 * where we have bin, use dollar quoting if allowed and src
9541 * contains quote or backslash; else use regular quoting.
9543 if (disable_dollar_quoting ||
9544 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9545 appendStringLiteralAH(asPart, prosrc, fout);
9547 appendStringLiteralDQ(asPart, prosrc, NULL);
9552 if (strcmp(prosrc, "-") != 0)
9554 appendPQExpBuffer(asPart, "AS ");
9555 /* with no bin, dollar quote src unconditionally if allowed */
9556 if (disable_dollar_quoting)
9557 appendStringLiteralAH(asPart, prosrc, fout);
9559 appendStringLiteralDQ(asPart, prosrc, NULL);
9563 nallargs = finfo->nargs; /* unless we learn different from allargs */
9565 if (proallargtypes && *proallargtypes)
9569 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9570 nitems < finfo->nargs)
9572 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9581 if (proargmodes && *proargmodes)
9585 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9588 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9595 if (proargnames && *proargnames)
9599 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9602 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9609 if (proconfig && *proconfig)
9611 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9613 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9623 /* 8.4 or later; we rely on server-side code for most of the work */
9624 funcfullsig = format_function_arguments(finfo, funcargs);
9625 funcsig = format_function_arguments(finfo, funciargs);
9629 /* pre-8.4, do it ourselves */
9630 funcsig = format_function_arguments_old(fout,
9631 finfo, nallargs, allargtypes,
9632 argmodes, argnames);
9633 funcfullsig = funcsig;
9636 funcsig_tag = format_function_signature(fout, finfo, false);
9639 * DROP must be fully qualified in case same name appears in pg_catalog
9641 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9642 fmtId(finfo->dobj.namespace->dobj.name),
9645 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9647 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9650 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9652 appendPQExpBuffer(q, "RETURNS %s%s",
9653 (proretset[0] == 't') ? "SETOF " : "",
9658 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9660 if (proiswindow[0] == 't')
9661 appendPQExpBuffer(q, " WINDOW");
9663 if (provolatile[0] != PROVOLATILE_VOLATILE)
9665 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9666 appendPQExpBuffer(q, " IMMUTABLE");
9667 else if (provolatile[0] == PROVOLATILE_STABLE)
9668 appendPQExpBuffer(q, " STABLE");
9669 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9670 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9674 if (proisstrict[0] == 't')
9675 appendPQExpBuffer(q, " STRICT");
9677 if (prosecdef[0] == 't')
9678 appendPQExpBuffer(q, " SECURITY DEFINER");
9680 if (proleakproof[0] == 't')
9681 appendPQExpBuffer(q, " LEAKPROOF");
9684 * COST and ROWS are emitted only if present and not default, so as not to
9685 * break backwards-compatibility of the dump without need. Keep this code
9686 * in sync with the defaults in functioncmds.c.
9688 if (strcmp(procost, "0") != 0)
9690 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9692 /* default cost is 1 */
9693 if (strcmp(procost, "1") != 0)
9694 appendPQExpBuffer(q, " COST %s", procost);
9698 /* default cost is 100 */
9699 if (strcmp(procost, "100") != 0)
9700 appendPQExpBuffer(q, " COST %s", procost);
9703 if (proretset[0] == 't' &&
9704 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9705 appendPQExpBuffer(q, " ROWS %s", prorows);
9707 for (i = 0; i < nconfigitems; i++)
9709 /* we feel free to scribble on configitems[] here */
9710 char *configitem = configitems[i];
9713 pos = strchr(configitem, '=');
9717 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9720 * Some GUC variable names are 'LIST' type and hence must not be
9723 if (pg_strcasecmp(configitem, "DateStyle") == 0
9724 || pg_strcasecmp(configitem, "search_path") == 0)
9725 appendPQExpBuffer(q, "%s", pos);
9727 appendStringLiteralAH(q, pos, fout);
9730 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9732 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9735 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9737 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9739 finfo->dobj.namespace->dobj.name,
9741 finfo->rolname, false,
9742 "FUNCTION", SECTION_PRE_DATA,
9743 q->data, delqry->data, NULL,
9747 /* Dump Function Comments and Security Labels */
9748 dumpComment(fout, labelq->data,
9749 finfo->dobj.namespace->dobj.name, finfo->rolname,
9750 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9751 dumpSecLabel(fout, labelq->data,
9752 finfo->dobj.namespace->dobj.name, finfo->rolname,
9753 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9755 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9756 funcsig, NULL, funcsig_tag,
9757 finfo->dobj.namespace->dobj.name,
9758 finfo->rolname, finfo->proacl);
9762 destroyPQExpBuffer(query);
9763 destroyPQExpBuffer(q);
9764 destroyPQExpBuffer(delqry);
9765 destroyPQExpBuffer(labelq);
9766 destroyPQExpBuffer(asPart);
9781 * Dump a user-defined cast
9784 dumpCast(Archive *fout, CastInfo *cast)
9789 FuncInfo *funcInfo = NULL;
9791 /* Skip if not to be dumped */
9792 if (!cast->dobj.dump || dataOnly)
9795 /* Cannot dump if we don't have the cast function's info */
9796 if (OidIsValid(cast->castfunc))
9798 funcInfo = findFuncByOid(cast->castfunc);
9799 if (funcInfo == NULL)
9804 * As per discussion we dump casts if one or more of the underlying
9805 * objects (the conversion function and the two data types) are not
9806 * builtin AND if all of the non-builtin objects are included in the dump.
9807 * Builtin meaning, the namespace name does not start with "pg_".
9809 * However, for a cast that belongs to an extension, we must not use this
9810 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9812 if (!cast->dobj.ext_member)
9814 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9815 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9817 if (sourceInfo == NULL || targetInfo == NULL)
9821 * Skip this cast if all objects are from pg_
9823 if ((funcInfo == NULL ||
9824 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9825 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9826 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9830 * Skip cast if function isn't from pg_ and is not to be dumped.
9833 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9834 !funcInfo->dobj.dump)
9838 * Same for the source type
9840 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9841 !sourceInfo->dobj.dump)
9845 * and the target type.
9847 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9848 !targetInfo->dobj.dump)
9852 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9853 selectSourceSchema(fout, "pg_catalog");
9855 defqry = createPQExpBuffer();
9856 delqry = createPQExpBuffer();
9857 labelq = createPQExpBuffer();
9859 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9860 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9861 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9863 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9864 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9865 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9867 switch (cast->castmethod)
9869 case COERCION_METHOD_BINARY:
9870 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9872 case COERCION_METHOD_INOUT:
9873 appendPQExpBuffer(defqry, "WITH INOUT");
9875 case COERCION_METHOD_FUNCTION:
9878 char *fsig = format_function_signature(fout, funcInfo, true);
9881 * Always qualify the function name, in case it is not in
9882 * pg_catalog schema (format_function_signature won't qualify
9885 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
9886 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
9890 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
9893 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9896 if (cast->castcontext == 'a')
9897 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9898 else if (cast->castcontext == 'i')
9899 appendPQExpBuffer(defqry, " AS IMPLICIT");
9900 appendPQExpBuffer(defqry, ";\n");
9902 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9903 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9904 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9907 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9909 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9911 "pg_catalog", NULL, "",
9912 false, "CAST", SECTION_PRE_DATA,
9913 defqry->data, delqry->data, NULL,
9917 /* Dump Cast Comments */
9918 dumpComment(fout, labelq->data,
9920 cast->dobj.catId, 0, cast->dobj.dumpId);
9922 destroyPQExpBuffer(defqry);
9923 destroyPQExpBuffer(delqry);
9924 destroyPQExpBuffer(labelq);
9929 * write out a single operator definition
9932 dumpOpr(Archive *fout, OprInfo *oprinfo)
9939 PQExpBuffer details;
9963 /* Skip if not to be dumped */
9964 if (!oprinfo->dobj.dump || dataOnly)
9968 * some operators are invalid because they were the result of user
9969 * defining operators before commutators exist
9971 if (!OidIsValid(oprinfo->oprcode))
9974 query = createPQExpBuffer();
9975 q = createPQExpBuffer();
9976 delq = createPQExpBuffer();
9977 labelq = createPQExpBuffer();
9978 oprid = createPQExpBuffer();
9979 details = createPQExpBuffer();
9981 /* Make sure we are in proper schema so regoperator works correctly */
9982 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9984 if (fout->remoteVersion >= 80300)
9986 appendPQExpBuffer(query, "SELECT oprkind, "
9987 "oprcode::pg_catalog.regprocedure, "
9988 "oprleft::pg_catalog.regtype, "
9989 "oprright::pg_catalog.regtype, "
9990 "oprcom::pg_catalog.regoperator, "
9991 "oprnegate::pg_catalog.regoperator, "
9992 "oprrest::pg_catalog.regprocedure, "
9993 "oprjoin::pg_catalog.regprocedure, "
9994 "oprcanmerge, oprcanhash "
9995 "FROM pg_catalog.pg_operator "
9996 "WHERE oid = '%u'::pg_catalog.oid",
9997 oprinfo->dobj.catId.oid);
9999 else if (fout->remoteVersion >= 70300)
10001 appendPQExpBuffer(query, "SELECT oprkind, "
10002 "oprcode::pg_catalog.regprocedure, "
10003 "oprleft::pg_catalog.regtype, "
10004 "oprright::pg_catalog.regtype, "
10005 "oprcom::pg_catalog.regoperator, "
10006 "oprnegate::pg_catalog.regoperator, "
10007 "oprrest::pg_catalog.regprocedure, "
10008 "oprjoin::pg_catalog.regprocedure, "
10009 "(oprlsortop != 0) AS oprcanmerge, "
10011 "FROM pg_catalog.pg_operator "
10012 "WHERE oid = '%u'::pg_catalog.oid",
10013 oprinfo->dobj.catId.oid);
10015 else if (fout->remoteVersion >= 70100)
10017 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10018 "CASE WHEN oprleft = 0 THEN '-' "
10019 "ELSE format_type(oprleft, NULL) END AS oprleft, "
10020 "CASE WHEN oprright = 0 THEN '-' "
10021 "ELSE format_type(oprright, NULL) END AS oprright, "
10022 "oprcom, oprnegate, oprrest, oprjoin, "
10023 "(oprlsortop != 0) AS oprcanmerge, "
10025 "FROM pg_operator "
10026 "WHERE oid = '%u'::oid",
10027 oprinfo->dobj.catId.oid);
10031 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10032 "CASE WHEN oprleft = 0 THEN '-'::name "
10033 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
10034 "CASE WHEN oprright = 0 THEN '-'::name "
10035 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
10036 "oprcom, oprnegate, oprrest, oprjoin, "
10037 "(oprlsortop != 0) AS oprcanmerge, "
10039 "FROM pg_operator "
10040 "WHERE oid = '%u'::oid",
10041 oprinfo->dobj.catId.oid);
10044 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10046 i_oprkind = PQfnumber(res, "oprkind");
10047 i_oprcode = PQfnumber(res, "oprcode");
10048 i_oprleft = PQfnumber(res, "oprleft");
10049 i_oprright = PQfnumber(res, "oprright");
10050 i_oprcom = PQfnumber(res, "oprcom");
10051 i_oprnegate = PQfnumber(res, "oprnegate");
10052 i_oprrest = PQfnumber(res, "oprrest");
10053 i_oprjoin = PQfnumber(res, "oprjoin");
10054 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
10055 i_oprcanhash = PQfnumber(res, "oprcanhash");
10057 oprkind = PQgetvalue(res, 0, i_oprkind);
10058 oprcode = PQgetvalue(res, 0, i_oprcode);
10059 oprleft = PQgetvalue(res, 0, i_oprleft);
10060 oprright = PQgetvalue(res, 0, i_oprright);
10061 oprcom = PQgetvalue(res, 0, i_oprcom);
10062 oprnegate = PQgetvalue(res, 0, i_oprnegate);
10063 oprrest = PQgetvalue(res, 0, i_oprrest);
10064 oprjoin = PQgetvalue(res, 0, i_oprjoin);
10065 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
10066 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
10068 appendPQExpBuffer(details, " PROCEDURE = %s",
10069 convertRegProcReference(fout, oprcode));
10071 appendPQExpBuffer(oprid, "%s (",
10072 oprinfo->dobj.name);
10075 * right unary means there's a left arg and left unary means there's a
10078 if (strcmp(oprkind, "r") == 0 ||
10079 strcmp(oprkind, "b") == 0)
10081 if (fout->remoteVersion >= 70100)
10084 name = fmtId(oprleft);
10085 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
10086 appendPQExpBuffer(oprid, "%s", name);
10089 appendPQExpBuffer(oprid, "NONE");
10091 if (strcmp(oprkind, "l") == 0 ||
10092 strcmp(oprkind, "b") == 0)
10094 if (fout->remoteVersion >= 70100)
10097 name = fmtId(oprright);
10098 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
10099 appendPQExpBuffer(oprid, ", %s)", name);
10102 appendPQExpBuffer(oprid, ", NONE)");
10104 name = convertOperatorReference(fout, oprcom);
10106 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
10108 name = convertOperatorReference(fout, oprnegate);
10110 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
10112 if (strcmp(oprcanmerge, "t") == 0)
10113 appendPQExpBuffer(details, ",\n MERGES");
10115 if (strcmp(oprcanhash, "t") == 0)
10116 appendPQExpBuffer(details, ",\n HASHES");
10118 name = convertRegProcReference(fout, oprrest);
10120 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
10122 name = convertRegProcReference(fout, oprjoin);
10124 appendPQExpBuffer(details, ",\n JOIN = %s", name);
10127 * DROP must be fully qualified in case same name appears in pg_catalog
10129 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
10130 fmtId(oprinfo->dobj.namespace->dobj.name),
10133 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
10134 oprinfo->dobj.name, details->data);
10136 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
10138 if (binary_upgrade)
10139 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
10141 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
10142 oprinfo->dobj.name,
10143 oprinfo->dobj.namespace->dobj.name,
10146 false, "OPERATOR", SECTION_PRE_DATA,
10147 q->data, delq->data, NULL,
10151 /* Dump Operator Comments */
10152 dumpComment(fout, labelq->data,
10153 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
10154 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
10158 destroyPQExpBuffer(query);
10159 destroyPQExpBuffer(q);
10160 destroyPQExpBuffer(delq);
10161 destroyPQExpBuffer(labelq);
10162 destroyPQExpBuffer(oprid);
10163 destroyPQExpBuffer(details);
10167 * Convert a function reference obtained from pg_operator
10169 * Returns what to print, or NULL if function references is InvalidOid
10171 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
10172 * argument-types part. In prior versions, the input is a REGPROC display.
10174 static const char *
10175 convertRegProcReference(Archive *fout, const char *proc)
10177 /* In all cases "-" means a null reference */
10178 if (strcmp(proc, "-") == 0)
10181 if (fout->remoteVersion >= 70300)
10187 name = pg_strdup(proc);
10188 /* find non-double-quoted left paren */
10190 for (paren = name; *paren; paren++)
10192 if (*paren == '(' && !inquote)
10198 inquote = !inquote;
10203 /* REGPROC before 7.3 does not quote its result */
10204 return fmtId(proc);
10208 * Convert an operator cross-reference obtained from pg_operator
10210 * Returns what to print, or NULL to print nothing
10212 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10213 * argument-types part, and add OPERATOR() decoration if the name is
10214 * schema-qualified. In older versions, the input is just a numeric OID,
10215 * which we search our operator list for.
10217 static const char *
10218 convertOperatorReference(Archive *fout, const char *opr)
10222 /* In all cases "0" means a null reference */
10223 if (strcmp(opr, "0") == 0)
10226 if (fout->remoteVersion >= 70300)
10234 name = pg_strdup(opr);
10235 /* find non-double-quoted left paren, and check for non-quoted dot */
10238 for (ptr = name; *ptr; ptr++)
10241 inquote = !inquote;
10242 else if (*ptr == '.' && !inquote)
10244 else if (*ptr == '(' && !inquote)
10250 /* If not schema-qualified, don't need to add OPERATOR() */
10253 oname = pg_malloc(strlen(name) + 11);
10254 sprintf(oname, "OPERATOR(%s)", name);
10259 oprInfo = findOprByOid(atooid(opr));
10260 if (oprInfo == NULL)
10262 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10266 return oprInfo->dobj.name;
10270 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10272 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10273 * argument lists of these functions are predetermined. Note that the
10274 * caller should ensure we are in the proper schema, because the results
10275 * are search path dependent!
10277 static const char *
10278 convertTSFunction(Archive *fout, Oid funcOid)
10284 snprintf(query, sizeof(query),
10285 "SELECT '%u'::pg_catalog.regproc", funcOid);
10286 res = ExecuteSqlQueryForSingleRow(fout, query);
10288 result = pg_strdup(PQgetvalue(res, 0, 0));
10298 * write out a single operator class definition
10301 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10306 PQExpBuffer labelq;
10313 int i_opcfamilyname;
10314 int i_opcfamilynsp;
10316 int i_amopstrategy;
10317 int i_amopreqcheck;
10320 int i_sortfamilynsp;
10323 int i_amproclefttype;
10324 int i_amprocrighttype;
10329 char *opcfamilyname;
10330 char *opcfamilynsp;
10332 char *amopstrategy;
10333 char *amopreqcheck;
10336 char *sortfamilynsp;
10339 char *amproclefttype;
10340 char *amprocrighttype;
10344 /* Skip if not to be dumped */
10345 if (!opcinfo->dobj.dump || dataOnly)
10349 * XXX currently we do not implement dumping of operator classes from
10350 * pre-7.3 databases. This could be done but it seems not worth the
10353 if (fout->remoteVersion < 70300)
10356 query = createPQExpBuffer();
10357 q = createPQExpBuffer();
10358 delq = createPQExpBuffer();
10359 labelq = createPQExpBuffer();
10361 /* Make sure we are in proper schema so regoperator works correctly */
10362 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10364 /* Get additional fields from the pg_opclass row */
10365 if (fout->remoteVersion >= 80300)
10367 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10368 "opckeytype::pg_catalog.regtype, "
10369 "opcdefault, opcfamily, "
10370 "opfname AS opcfamilyname, "
10371 "nspname AS opcfamilynsp, "
10372 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10373 "FROM pg_catalog.pg_opclass c "
10374 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10375 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10376 "WHERE c.oid = '%u'::pg_catalog.oid",
10377 opcinfo->dobj.catId.oid);
10381 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10382 "opckeytype::pg_catalog.regtype, "
10383 "opcdefault, NULL AS opcfamily, "
10384 "NULL AS opcfamilyname, "
10385 "NULL AS opcfamilynsp, "
10386 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10387 "FROM pg_catalog.pg_opclass "
10388 "WHERE oid = '%u'::pg_catalog.oid",
10389 opcinfo->dobj.catId.oid);
10392 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10394 i_opcintype = PQfnumber(res, "opcintype");
10395 i_opckeytype = PQfnumber(res, "opckeytype");
10396 i_opcdefault = PQfnumber(res, "opcdefault");
10397 i_opcfamily = PQfnumber(res, "opcfamily");
10398 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10399 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10400 i_amname = PQfnumber(res, "amname");
10402 opcintype = PQgetvalue(res, 0, i_opcintype);
10403 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10404 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10405 /* opcfamily will still be needed after we PQclear res */
10406 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10407 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10408 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10409 /* amname will still be needed after we PQclear res */
10410 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10413 * DROP must be fully qualified in case same name appears in pg_catalog
10415 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10416 fmtId(opcinfo->dobj.namespace->dobj.name));
10417 appendPQExpBuffer(delq, ".%s",
10418 fmtId(opcinfo->dobj.name));
10419 appendPQExpBuffer(delq, " USING %s;\n",
10422 /* Build the fixed portion of the CREATE command */
10423 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10424 fmtId(opcinfo->dobj.name));
10425 if (strcmp(opcdefault, "t") == 0)
10426 appendPQExpBuffer(q, "DEFAULT ");
10427 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10430 if (strlen(opcfamilyname) > 0 &&
10431 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10432 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10434 appendPQExpBuffer(q, " FAMILY ");
10435 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10436 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10437 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10439 appendPQExpBuffer(q, " AS\n ");
10443 if (strcmp(opckeytype, "-") != 0)
10445 appendPQExpBuffer(q, "STORAGE %s",
10453 * Now fetch and print the OPERATOR entries (pg_amop rows).
10455 * Print only those opfamily members that are tied to the opclass by
10456 * pg_depend entries.
10458 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10459 * older server's opclass in which it is used. This is to avoid
10460 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10461 * older server and then reload into that old version. This can go away
10462 * once 8.3 is so old as to not be of interest to anyone.
10464 resetPQExpBuffer(query);
10466 if (fout->remoteVersion >= 90100)
10468 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10469 "amopopr::pg_catalog.regoperator, "
10470 "opfname AS sortfamily, "
10471 "nspname AS sortfamilynsp "
10472 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10473 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10474 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10475 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10476 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10477 "AND refobjid = '%u'::pg_catalog.oid "
10478 "AND amopfamily = '%s'::pg_catalog.oid "
10479 "ORDER BY amopstrategy",
10480 opcinfo->dobj.catId.oid,
10483 else if (fout->remoteVersion >= 80400)
10485 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10486 "amopopr::pg_catalog.regoperator, "
10487 "NULL AS sortfamily, "
10488 "NULL AS sortfamilynsp "
10489 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10490 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10491 "AND refobjid = '%u'::pg_catalog.oid "
10492 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10493 "AND objid = ao.oid "
10494 "ORDER BY amopstrategy",
10495 opcinfo->dobj.catId.oid);
10497 else if (fout->remoteVersion >= 80300)
10499 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10500 "amopopr::pg_catalog.regoperator, "
10501 "NULL AS sortfamily, "
10502 "NULL AS sortfamilynsp "
10503 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10504 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10505 "AND refobjid = '%u'::pg_catalog.oid "
10506 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10507 "AND objid = ao.oid "
10508 "ORDER BY amopstrategy",
10509 opcinfo->dobj.catId.oid);
10514 * Here, we print all entries since there are no opfamilies and hence
10515 * no loose operators to worry about.
10517 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10518 "amopopr::pg_catalog.regoperator, "
10519 "NULL AS sortfamily, "
10520 "NULL AS sortfamilynsp "
10521 "FROM pg_catalog.pg_amop "
10522 "WHERE amopclaid = '%u'::pg_catalog.oid "
10523 "ORDER BY amopstrategy",
10524 opcinfo->dobj.catId.oid);
10527 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10529 ntups = PQntuples(res);
10531 i_amopstrategy = PQfnumber(res, "amopstrategy");
10532 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10533 i_amopopr = PQfnumber(res, "amopopr");
10534 i_sortfamily = PQfnumber(res, "sortfamily");
10535 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10537 for (i = 0; i < ntups; i++)
10539 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10540 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10541 amopopr = PQgetvalue(res, i, i_amopopr);
10542 sortfamily = PQgetvalue(res, i, i_sortfamily);
10543 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10546 appendPQExpBuffer(q, " ,\n ");
10548 appendPQExpBuffer(q, "OPERATOR %s %s",
10549 amopstrategy, amopopr);
10551 if (strlen(sortfamily) > 0)
10553 appendPQExpBuffer(q, " FOR ORDER BY ");
10554 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10555 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10556 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10559 if (strcmp(amopreqcheck, "t") == 0)
10560 appendPQExpBuffer(q, " RECHECK");
10568 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10570 * Print only those opfamily members that are tied to the opclass by
10571 * pg_depend entries.
10573 * We print the amproclefttype/amprocrighttype even though in most cases
10574 * the backend could deduce the right values, because of the corner case
10575 * of a btree sort support function for a cross-type comparison. That's
10576 * only allowed in 9.2 and later, but for simplicity print them in all
10577 * versions that have the columns.
10579 resetPQExpBuffer(query);
10581 if (fout->remoteVersion >= 80300)
10583 appendPQExpBuffer(query, "SELECT amprocnum, "
10584 "amproc::pg_catalog.regprocedure, "
10585 "amproclefttype::pg_catalog.regtype, "
10586 "amprocrighttype::pg_catalog.regtype "
10587 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10588 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10589 "AND refobjid = '%u'::pg_catalog.oid "
10590 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10591 "AND objid = ap.oid "
10592 "ORDER BY amprocnum",
10593 opcinfo->dobj.catId.oid);
10597 appendPQExpBuffer(query, "SELECT amprocnum, "
10598 "amproc::pg_catalog.regprocedure, "
10599 "'' AS amproclefttype, "
10600 "'' AS amprocrighttype "
10601 "FROM pg_catalog.pg_amproc "
10602 "WHERE amopclaid = '%u'::pg_catalog.oid "
10603 "ORDER BY amprocnum",
10604 opcinfo->dobj.catId.oid);
10607 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10609 ntups = PQntuples(res);
10611 i_amprocnum = PQfnumber(res, "amprocnum");
10612 i_amproc = PQfnumber(res, "amproc");
10613 i_amproclefttype = PQfnumber(res, "amproclefttype");
10614 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10616 for (i = 0; i < ntups; i++)
10618 amprocnum = PQgetvalue(res, i, i_amprocnum);
10619 amproc = PQgetvalue(res, i, i_amproc);
10620 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10621 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10624 appendPQExpBuffer(q, " ,\n ");
10626 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10628 if (*amproclefttype && *amprocrighttype)
10629 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10631 appendPQExpBuffer(q, " %s", amproc);
10638 appendPQExpBuffer(q, ";\n");
10640 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10641 fmtId(opcinfo->dobj.name));
10642 appendPQExpBuffer(labelq, " USING %s",
10645 if (binary_upgrade)
10646 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10648 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10649 opcinfo->dobj.name,
10650 opcinfo->dobj.namespace->dobj.name,
10653 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10654 q->data, delq->data, NULL,
10658 /* Dump Operator Class Comments */
10659 dumpComment(fout, labelq->data,
10660 NULL, opcinfo->rolname,
10661 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10664 destroyPQExpBuffer(query);
10665 destroyPQExpBuffer(q);
10666 destroyPQExpBuffer(delq);
10667 destroyPQExpBuffer(labelq);
10672 * write out a single operator family definition
10674 * Note: this also dumps any "loose" operator members that aren't bound to a
10675 * specific opclass within the opfamily.
10678 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10683 PQExpBuffer labelq;
10686 PGresult *res_procs;
10689 int i_amopstrategy;
10690 int i_amopreqcheck;
10693 int i_sortfamilynsp;
10696 int i_amproclefttype;
10697 int i_amprocrighttype;
10699 char *amopstrategy;
10700 char *amopreqcheck;
10703 char *sortfamilynsp;
10706 char *amproclefttype;
10707 char *amprocrighttype;
10711 /* Skip if not to be dumped */
10712 if (!opfinfo->dobj.dump || dataOnly)
10716 * We want to dump the opfamily only if (1) it contains "loose" operators
10717 * or functions, or (2) it contains an opclass with a different name or
10718 * owner. Otherwise it's sufficient to let it be created during creation
10719 * of the contained opclass, and not dumping it improves portability of
10720 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10724 query = createPQExpBuffer();
10725 q = createPQExpBuffer();
10726 delq = createPQExpBuffer();
10727 labelq = createPQExpBuffer();
10729 /* Make sure we are in proper schema so regoperator works correctly */
10730 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10733 * Fetch only those opfamily members that are tied directly to the
10734 * opfamily by pg_depend entries.
10736 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10737 * older server's opclass in which it is used. This is to avoid
10738 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10739 * older server and then reload into that old version. This can go away
10740 * once 8.3 is so old as to not be of interest to anyone.
10742 if (fout->remoteVersion >= 90100)
10744 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10745 "amopopr::pg_catalog.regoperator, "
10746 "opfname AS sortfamily, "
10747 "nspname AS sortfamilynsp "
10748 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10749 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10750 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10751 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10752 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10753 "AND refobjid = '%u'::pg_catalog.oid "
10754 "AND amopfamily = '%u'::pg_catalog.oid "
10755 "ORDER BY amopstrategy",
10756 opfinfo->dobj.catId.oid,
10757 opfinfo->dobj.catId.oid);
10759 else if (fout->remoteVersion >= 80400)
10761 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10762 "amopopr::pg_catalog.regoperator, "
10763 "NULL AS sortfamily, "
10764 "NULL AS sortfamilynsp "
10765 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10766 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10767 "AND refobjid = '%u'::pg_catalog.oid "
10768 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10769 "AND objid = ao.oid "
10770 "ORDER BY amopstrategy",
10771 opfinfo->dobj.catId.oid);
10775 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10776 "amopopr::pg_catalog.regoperator, "
10777 "NULL AS sortfamily, "
10778 "NULL AS sortfamilynsp "
10779 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10780 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10781 "AND refobjid = '%u'::pg_catalog.oid "
10782 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10783 "AND objid = ao.oid "
10784 "ORDER BY amopstrategy",
10785 opfinfo->dobj.catId.oid);
10788 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10790 resetPQExpBuffer(query);
10792 appendPQExpBuffer(query, "SELECT amprocnum, "
10793 "amproc::pg_catalog.regprocedure, "
10794 "amproclefttype::pg_catalog.regtype, "
10795 "amprocrighttype::pg_catalog.regtype "
10796 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10797 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10798 "AND refobjid = '%u'::pg_catalog.oid "
10799 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10800 "AND objid = ap.oid "
10801 "ORDER BY amprocnum",
10802 opfinfo->dobj.catId.oid);
10804 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10806 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10808 /* No loose members, so check contained opclasses */
10809 resetPQExpBuffer(query);
10811 appendPQExpBuffer(query, "SELECT 1 "
10812 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10813 "WHERE f.oid = '%u'::pg_catalog.oid "
10814 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10815 "AND refobjid = f.oid "
10816 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10817 "AND objid = c.oid "
10818 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10820 opfinfo->dobj.catId.oid);
10822 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10824 if (PQntuples(res) == 0)
10826 /* no need to dump it, so bail out */
10829 PQclear(res_procs);
10830 destroyPQExpBuffer(query);
10831 destroyPQExpBuffer(q);
10832 destroyPQExpBuffer(delq);
10833 destroyPQExpBuffer(labelq);
10840 /* Get additional fields from the pg_opfamily row */
10841 resetPQExpBuffer(query);
10843 appendPQExpBuffer(query, "SELECT "
10844 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10845 "FROM pg_catalog.pg_opfamily "
10846 "WHERE oid = '%u'::pg_catalog.oid",
10847 opfinfo->dobj.catId.oid);
10849 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10851 i_amname = PQfnumber(res, "amname");
10853 /* amname will still be needed after we PQclear res */
10854 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10857 * DROP must be fully qualified in case same name appears in pg_catalog
10859 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10860 fmtId(opfinfo->dobj.namespace->dobj.name));
10861 appendPQExpBuffer(delq, ".%s",
10862 fmtId(opfinfo->dobj.name));
10863 appendPQExpBuffer(delq, " USING %s;\n",
10866 /* Build the fixed portion of the CREATE command */
10867 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10868 fmtId(opfinfo->dobj.name));
10869 appendPQExpBuffer(q, " USING %s;\n",
10874 /* Do we need an ALTER to add loose members? */
10875 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10877 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10878 fmtId(opfinfo->dobj.name));
10879 appendPQExpBuffer(q, " USING %s ADD\n ",
10885 * Now fetch and print the OPERATOR entries (pg_amop rows).
10887 ntups = PQntuples(res_ops);
10889 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10890 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10891 i_amopopr = PQfnumber(res_ops, "amopopr");
10892 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10893 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10895 for (i = 0; i < ntups; i++)
10897 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10898 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10899 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10900 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10901 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10904 appendPQExpBuffer(q, " ,\n ");
10906 appendPQExpBuffer(q, "OPERATOR %s %s",
10907 amopstrategy, amopopr);
10909 if (strlen(sortfamily) > 0)
10911 appendPQExpBuffer(q, " FOR ORDER BY ");
10912 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10913 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10914 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10917 if (strcmp(amopreqcheck, "t") == 0)
10918 appendPQExpBuffer(q, " RECHECK");
10924 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10926 ntups = PQntuples(res_procs);
10928 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10929 i_amproc = PQfnumber(res_procs, "amproc");
10930 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10931 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10933 for (i = 0; i < ntups; i++)
10935 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10936 amproc = PQgetvalue(res_procs, i, i_amproc);
10937 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10938 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10941 appendPQExpBuffer(q, " ,\n ");
10943 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10944 amprocnum, amproclefttype, amprocrighttype,
10950 appendPQExpBuffer(q, ";\n");
10953 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10954 fmtId(opfinfo->dobj.name));
10955 appendPQExpBuffer(labelq, " USING %s",
10958 if (binary_upgrade)
10959 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10961 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10962 opfinfo->dobj.name,
10963 opfinfo->dobj.namespace->dobj.name,
10966 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10967 q->data, delq->data, NULL,
10971 /* Dump Operator Family Comments */
10972 dumpComment(fout, labelq->data,
10973 NULL, opfinfo->rolname,
10974 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10978 PQclear(res_procs);
10979 destroyPQExpBuffer(query);
10980 destroyPQExpBuffer(q);
10981 destroyPQExpBuffer(delq);
10982 destroyPQExpBuffer(labelq);
10987 * write out a single collation definition
10990 dumpCollation(Archive *fout, CollInfo *collinfo)
10995 PQExpBuffer labelq;
10999 const char *collcollate;
11000 const char *collctype;
11002 /* Skip if not to be dumped */
11003 if (!collinfo->dobj.dump || dataOnly)
11006 query = createPQExpBuffer();
11007 q = createPQExpBuffer();
11008 delq = createPQExpBuffer();
11009 labelq = createPQExpBuffer();
11011 /* Make sure we are in proper schema */
11012 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
11014 /* Get conversion-specific details */
11015 appendPQExpBuffer(query, "SELECT "
11018 "FROM pg_catalog.pg_collation c "
11019 "WHERE c.oid = '%u'::pg_catalog.oid",
11020 collinfo->dobj.catId.oid);
11022 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11024 i_collcollate = PQfnumber(res, "collcollate");
11025 i_collctype = PQfnumber(res, "collctype");
11027 collcollate = PQgetvalue(res, 0, i_collcollate);
11028 collctype = PQgetvalue(res, 0, i_collctype);
11031 * DROP must be fully qualified in case same name appears in pg_catalog
11033 appendPQExpBuffer(delq, "DROP COLLATION %s",
11034 fmtId(collinfo->dobj.namespace->dobj.name));
11035 appendPQExpBuffer(delq, ".%s;\n",
11036 fmtId(collinfo->dobj.name));
11038 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
11039 fmtId(collinfo->dobj.name));
11040 appendStringLiteralAH(q, collcollate, fout);
11041 appendPQExpBuffer(q, ", lc_ctype = ");
11042 appendStringLiteralAH(q, collctype, fout);
11043 appendPQExpBuffer(q, ");\n");
11045 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
11047 if (binary_upgrade)
11048 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
11050 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
11051 collinfo->dobj.name,
11052 collinfo->dobj.namespace->dobj.name,
11055 false, "COLLATION", SECTION_PRE_DATA,
11056 q->data, delq->data, NULL,
11060 /* Dump Collation Comments */
11061 dumpComment(fout, labelq->data,
11062 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
11063 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
11067 destroyPQExpBuffer(query);
11068 destroyPQExpBuffer(q);
11069 destroyPQExpBuffer(delq);
11070 destroyPQExpBuffer(labelq);
11075 * write out a single conversion definition
11078 dumpConversion(Archive *fout, ConvInfo *convinfo)
11083 PQExpBuffer labelq;
11085 int i_conforencoding;
11086 int i_contoencoding;
11089 const char *conforencoding;
11090 const char *contoencoding;
11091 const char *conproc;
11094 /* Skip if not to be dumped */
11095 if (!convinfo->dobj.dump || dataOnly)
11098 query = createPQExpBuffer();
11099 q = createPQExpBuffer();
11100 delq = createPQExpBuffer();
11101 labelq = createPQExpBuffer();
11103 /* Make sure we are in proper schema */
11104 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
11106 /* Get conversion-specific details */
11107 appendPQExpBuffer(query, "SELECT "
11108 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
11109 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
11110 "conproc, condefault "
11111 "FROM pg_catalog.pg_conversion c "
11112 "WHERE c.oid = '%u'::pg_catalog.oid",
11113 convinfo->dobj.catId.oid);
11115 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11117 i_conforencoding = PQfnumber(res, "conforencoding");
11118 i_contoencoding = PQfnumber(res, "contoencoding");
11119 i_conproc = PQfnumber(res, "conproc");
11120 i_condefault = PQfnumber(res, "condefault");
11122 conforencoding = PQgetvalue(res, 0, i_conforencoding);
11123 contoencoding = PQgetvalue(res, 0, i_contoencoding);
11124 conproc = PQgetvalue(res, 0, i_conproc);
11125 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
11128 * DROP must be fully qualified in case same name appears in pg_catalog
11130 appendPQExpBuffer(delq, "DROP CONVERSION %s",
11131 fmtId(convinfo->dobj.namespace->dobj.name));
11132 appendPQExpBuffer(delq, ".%s;\n",
11133 fmtId(convinfo->dobj.name));
11135 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
11136 (condefault) ? "DEFAULT " : "",
11137 fmtId(convinfo->dobj.name));
11138 appendStringLiteralAH(q, conforencoding, fout);
11139 appendPQExpBuffer(q, " TO ");
11140 appendStringLiteralAH(q, contoencoding, fout);
11141 /* regproc is automatically quoted in 7.3 and above */
11142 appendPQExpBuffer(q, " FROM %s;\n", conproc);
11144 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
11146 if (binary_upgrade)
11147 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
11149 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
11150 convinfo->dobj.name,
11151 convinfo->dobj.namespace->dobj.name,
11154 false, "CONVERSION", SECTION_PRE_DATA,
11155 q->data, delq->data, NULL,
11159 /* Dump Conversion Comments */
11160 dumpComment(fout, labelq->data,
11161 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
11162 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
11166 destroyPQExpBuffer(query);
11167 destroyPQExpBuffer(q);
11168 destroyPQExpBuffer(delq);
11169 destroyPQExpBuffer(labelq);
11173 * format_aggregate_signature: generate aggregate name and argument list
11175 * The argument type names are qualified if needed. The aggregate name
11176 * is never qualified.
11179 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11181 PQExpBufferData buf;
11184 initPQExpBuffer(&buf);
11186 appendPQExpBuffer(&buf, "%s",
11187 fmtId(agginfo->aggfn.dobj.name));
11189 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11191 if (agginfo->aggfn.nargs == 0)
11192 appendPQExpBuffer(&buf, "(*)");
11195 appendPQExpBuffer(&buf, "(");
11196 for (j = 0; j < agginfo->aggfn.nargs; j++)
11200 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11203 appendPQExpBuffer(&buf, "%s%s",
11204 (j > 0) ? ", " : "",
11208 appendPQExpBuffer(&buf, ")");
11215 * write out a single aggregate definition
11218 dumpAgg(Archive *fout, AggInfo *agginfo)
11223 PQExpBuffer labelq;
11224 PQExpBuffer details;
11231 int i_aggtranstype;
11234 const char *aggtransfn;
11235 const char *aggfinalfn;
11236 const char *aggsortop;
11237 const char *aggtranstype;
11238 const char *agginitval;
11241 /* Skip if not to be dumped */
11242 if (!agginfo->aggfn.dobj.dump || dataOnly)
11245 query = createPQExpBuffer();
11246 q = createPQExpBuffer();
11247 delq = createPQExpBuffer();
11248 labelq = createPQExpBuffer();
11249 details = createPQExpBuffer();
11251 /* Make sure we are in proper schema */
11252 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11254 /* Get aggregate-specific details */
11255 if (fout->remoteVersion >= 80100)
11257 appendPQExpBuffer(query, "SELECT aggtransfn, "
11258 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11259 "aggsortop::pg_catalog.regoperator, "
11261 "'t'::boolean AS convertok "
11262 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11263 "WHERE a.aggfnoid = p.oid "
11264 "AND p.oid = '%u'::pg_catalog.oid",
11265 agginfo->aggfn.dobj.catId.oid);
11267 else if (fout->remoteVersion >= 70300)
11269 appendPQExpBuffer(query, "SELECT aggtransfn, "
11270 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11273 "'t'::boolean AS convertok "
11274 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11275 "WHERE a.aggfnoid = p.oid "
11276 "AND p.oid = '%u'::pg_catalog.oid",
11277 agginfo->aggfn.dobj.catId.oid);
11279 else if (fout->remoteVersion >= 70100)
11281 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11282 "format_type(aggtranstype, NULL) AS aggtranstype, "
11285 "'t'::boolean AS convertok "
11286 "FROM pg_aggregate "
11287 "WHERE oid = '%u'::oid",
11288 agginfo->aggfn.dobj.catId.oid);
11292 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11294 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11296 "agginitval1 AS agginitval, "
11297 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11298 "FROM pg_aggregate "
11299 "WHERE oid = '%u'::oid",
11300 agginfo->aggfn.dobj.catId.oid);
11303 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11305 i_aggtransfn = PQfnumber(res, "aggtransfn");
11306 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11307 i_aggsortop = PQfnumber(res, "aggsortop");
11308 i_aggtranstype = PQfnumber(res, "aggtranstype");
11309 i_agginitval = PQfnumber(res, "agginitval");
11310 i_convertok = PQfnumber(res, "convertok");
11312 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11313 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11314 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11315 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11316 agginitval = PQgetvalue(res, 0, i_agginitval);
11317 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11319 aggsig = format_aggregate_signature(agginfo, fout, true);
11320 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11324 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11329 if (fout->remoteVersion >= 70300)
11331 /* If using 7.3's regproc or regtype, data is already quoted */
11332 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11336 else if (fout->remoteVersion >= 70100)
11338 /* format_type quotes, regproc does not */
11339 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11345 /* need quotes all around */
11346 appendPQExpBuffer(details, " SFUNC = %s,\n",
11347 fmtId(aggtransfn));
11348 appendPQExpBuffer(details, " STYPE = %s",
11349 fmtId(aggtranstype));
11352 if (!PQgetisnull(res, 0, i_agginitval))
11354 appendPQExpBuffer(details, ",\n INITCOND = ");
11355 appendStringLiteralAH(details, agginitval, fout);
11358 if (strcmp(aggfinalfn, "-") != 0)
11360 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11364 aggsortop = convertOperatorReference(fout, aggsortop);
11367 appendPQExpBuffer(details, ",\n SORTOP = %s",
11372 * DROP must be fully qualified in case same name appears in pg_catalog
11374 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11375 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11378 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11379 aggsig, details->data);
11381 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11383 if (binary_upgrade)
11384 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11386 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11388 agginfo->aggfn.dobj.namespace->dobj.name,
11390 agginfo->aggfn.rolname,
11391 false, "AGGREGATE", SECTION_PRE_DATA,
11392 q->data, delq->data, NULL,
11396 /* Dump Aggregate Comments */
11397 dumpComment(fout, labelq->data,
11398 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11399 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11400 dumpSecLabel(fout, labelq->data,
11401 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11402 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11405 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11406 * command look like a function's GRANT; in particular this affects the
11407 * syntax for zero-argument aggregates.
11412 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11413 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11415 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11417 aggsig, NULL, aggsig_tag,
11418 agginfo->aggfn.dobj.namespace->dobj.name,
11419 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11426 destroyPQExpBuffer(query);
11427 destroyPQExpBuffer(q);
11428 destroyPQExpBuffer(delq);
11429 destroyPQExpBuffer(labelq);
11430 destroyPQExpBuffer(details);
11435 * write out a single text search parser
11438 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11442 PQExpBuffer labelq;
11444 /* Skip if not to be dumped */
11445 if (!prsinfo->dobj.dump || dataOnly)
11448 q = createPQExpBuffer();
11449 delq = createPQExpBuffer();
11450 labelq = createPQExpBuffer();
11452 /* Make sure we are in proper schema */
11453 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11455 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11456 fmtId(prsinfo->dobj.name));
11458 appendPQExpBuffer(q, " START = %s,\n",
11459 convertTSFunction(fout, prsinfo->prsstart));
11460 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11461 convertTSFunction(fout, prsinfo->prstoken));
11462 appendPQExpBuffer(q, " END = %s,\n",
11463 convertTSFunction(fout, prsinfo->prsend));
11464 if (prsinfo->prsheadline != InvalidOid)
11465 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11466 convertTSFunction(fout, prsinfo->prsheadline));
11467 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11468 convertTSFunction(fout, prsinfo->prslextype));
11471 * DROP must be fully qualified in case same name appears in pg_catalog
11473 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11474 fmtId(prsinfo->dobj.namespace->dobj.name));
11475 appendPQExpBuffer(delq, ".%s;\n",
11476 fmtId(prsinfo->dobj.name));
11478 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11479 fmtId(prsinfo->dobj.name));
11481 if (binary_upgrade)
11482 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11484 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11485 prsinfo->dobj.name,
11486 prsinfo->dobj.namespace->dobj.name,
11489 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11490 q->data, delq->data, NULL,
11494 /* Dump Parser Comments */
11495 dumpComment(fout, labelq->data,
11497 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11499 destroyPQExpBuffer(q);
11500 destroyPQExpBuffer(delq);
11501 destroyPQExpBuffer(labelq);
11506 * write out a single text search dictionary
11509 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11513 PQExpBuffer labelq;
11519 /* Skip if not to be dumped */
11520 if (!dictinfo->dobj.dump || dataOnly)
11523 q = createPQExpBuffer();
11524 delq = createPQExpBuffer();
11525 labelq = createPQExpBuffer();
11526 query = createPQExpBuffer();
11528 /* Fetch name and namespace of the dictionary's template */
11529 selectSourceSchema(fout, "pg_catalog");
11530 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11531 "FROM pg_ts_template p, pg_namespace n "
11532 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11533 dictinfo->dicttemplate);
11534 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11535 nspname = PQgetvalue(res, 0, 0);
11536 tmplname = PQgetvalue(res, 0, 1);
11538 /* Make sure we are in proper schema */
11539 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11541 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11542 fmtId(dictinfo->dobj.name));
11544 appendPQExpBuffer(q, " TEMPLATE = ");
11545 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11546 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11547 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11551 /* the dictinitoption can be dumped straight into the command */
11552 if (dictinfo->dictinitoption)
11553 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11555 appendPQExpBuffer(q, " );\n");
11558 * DROP must be fully qualified in case same name appears in pg_catalog
11560 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11561 fmtId(dictinfo->dobj.namespace->dobj.name));
11562 appendPQExpBuffer(delq, ".%s;\n",
11563 fmtId(dictinfo->dobj.name));
11565 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11566 fmtId(dictinfo->dobj.name));
11568 if (binary_upgrade)
11569 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11571 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11572 dictinfo->dobj.name,
11573 dictinfo->dobj.namespace->dobj.name,
11576 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11577 q->data, delq->data, NULL,
11581 /* Dump Dictionary Comments */
11582 dumpComment(fout, labelq->data,
11583 NULL, dictinfo->rolname,
11584 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11586 destroyPQExpBuffer(q);
11587 destroyPQExpBuffer(delq);
11588 destroyPQExpBuffer(labelq);
11589 destroyPQExpBuffer(query);
11594 * write out a single text search template
11597 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11601 PQExpBuffer labelq;
11603 /* Skip if not to be dumped */
11604 if (!tmplinfo->dobj.dump || dataOnly)
11607 q = createPQExpBuffer();
11608 delq = createPQExpBuffer();
11609 labelq = createPQExpBuffer();
11611 /* Make sure we are in proper schema */
11612 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11614 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11615 fmtId(tmplinfo->dobj.name));
11617 if (tmplinfo->tmplinit != InvalidOid)
11618 appendPQExpBuffer(q, " INIT = %s,\n",
11619 convertTSFunction(fout, tmplinfo->tmplinit));
11620 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11621 convertTSFunction(fout, tmplinfo->tmpllexize));
11624 * DROP must be fully qualified in case same name appears in pg_catalog
11626 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11627 fmtId(tmplinfo->dobj.namespace->dobj.name));
11628 appendPQExpBuffer(delq, ".%s;\n",
11629 fmtId(tmplinfo->dobj.name));
11631 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11632 fmtId(tmplinfo->dobj.name));
11634 if (binary_upgrade)
11635 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11637 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11638 tmplinfo->dobj.name,
11639 tmplinfo->dobj.namespace->dobj.name,
11642 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11643 q->data, delq->data, NULL,
11647 /* Dump Template Comments */
11648 dumpComment(fout, labelq->data,
11650 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11652 destroyPQExpBuffer(q);
11653 destroyPQExpBuffer(delq);
11654 destroyPQExpBuffer(labelq);
11659 * write out a single text search configuration
11662 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11666 PQExpBuffer labelq;
11676 /* Skip if not to be dumped */
11677 if (!cfginfo->dobj.dump || dataOnly)
11680 q = createPQExpBuffer();
11681 delq = createPQExpBuffer();
11682 labelq = createPQExpBuffer();
11683 query = createPQExpBuffer();
11685 /* Fetch name and namespace of the config's parser */
11686 selectSourceSchema(fout, "pg_catalog");
11687 appendPQExpBuffer(query, "SELECT nspname, prsname "
11688 "FROM pg_ts_parser p, pg_namespace n "
11689 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11690 cfginfo->cfgparser);
11691 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11692 nspname = PQgetvalue(res, 0, 0);
11693 prsname = PQgetvalue(res, 0, 1);
11695 /* Make sure we are in proper schema */
11696 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11698 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11699 fmtId(cfginfo->dobj.name));
11701 appendPQExpBuffer(q, " PARSER = ");
11702 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11703 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11704 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11708 resetPQExpBuffer(query);
11709 appendPQExpBuffer(query,
11711 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11712 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11713 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11714 "FROM pg_catalog.pg_ts_config_map AS m \n"
11715 "WHERE m.mapcfg = '%u' \n"
11716 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11717 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11719 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11720 ntups = PQntuples(res);
11722 i_tokenname = PQfnumber(res, "tokenname");
11723 i_dictname = PQfnumber(res, "dictname");
11725 for (i = 0; i < ntups; i++)
11727 char *tokenname = PQgetvalue(res, i, i_tokenname);
11728 char *dictname = PQgetvalue(res, i, i_dictname);
11731 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11733 /* starting a new token type, so start a new command */
11735 appendPQExpBuffer(q, ";\n");
11736 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11737 fmtId(cfginfo->dobj.name));
11738 /* tokenname needs quoting, dictname does NOT */
11739 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11740 fmtId(tokenname), dictname);
11743 appendPQExpBuffer(q, ", %s", dictname);
11747 appendPQExpBuffer(q, ";\n");
11752 * DROP must be fully qualified in case same name appears in pg_catalog
11754 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11755 fmtId(cfginfo->dobj.namespace->dobj.name));
11756 appendPQExpBuffer(delq, ".%s;\n",
11757 fmtId(cfginfo->dobj.name));
11759 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11760 fmtId(cfginfo->dobj.name));
11762 if (binary_upgrade)
11763 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11765 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11766 cfginfo->dobj.name,
11767 cfginfo->dobj.namespace->dobj.name,
11770 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11771 q->data, delq->data, NULL,
11775 /* Dump Configuration Comments */
11776 dumpComment(fout, labelq->data,
11777 NULL, cfginfo->rolname,
11778 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11780 destroyPQExpBuffer(q);
11781 destroyPQExpBuffer(delq);
11782 destroyPQExpBuffer(labelq);
11783 destroyPQExpBuffer(query);
11787 * dumpForeignDataWrapper
11788 * write out a single foreign-data wrapper definition
11791 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11795 PQExpBuffer labelq;
11798 /* Skip if not to be dumped */
11799 if (!fdwinfo->dobj.dump || dataOnly)
11803 * FDWs that belong to an extension are dumped based on their "dump"
11804 * field. Otherwise omit them if we are only dumping some specific object.
11806 if (!fdwinfo->dobj.ext_member)
11807 if (!include_everything)
11810 q = createPQExpBuffer();
11811 delq = createPQExpBuffer();
11812 labelq = createPQExpBuffer();
11814 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11816 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11819 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11820 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11822 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11823 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11825 if (strlen(fdwinfo->fdwoptions) > 0)
11826 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11828 appendPQExpBuffer(q, ";\n");
11830 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11833 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11836 if (binary_upgrade)
11837 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11839 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11840 fdwinfo->dobj.name,
11844 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11845 q->data, delq->data, NULL,
11849 /* Handle the ACL */
11850 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11851 "FOREIGN DATA WRAPPER",
11852 qfdwname, NULL, fdwinfo->dobj.name,
11853 NULL, fdwinfo->rolname,
11856 /* Dump Foreign Data Wrapper Comments */
11857 dumpComment(fout, labelq->data,
11858 NULL, fdwinfo->rolname,
11859 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11863 destroyPQExpBuffer(q);
11864 destroyPQExpBuffer(delq);
11865 destroyPQExpBuffer(labelq);
11869 * dumpForeignServer
11870 * write out a foreign server definition
11873 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11877 PQExpBuffer labelq;
11883 /* Skip if not to be dumped */
11884 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11887 q = createPQExpBuffer();
11888 delq = createPQExpBuffer();
11889 labelq = createPQExpBuffer();
11890 query = createPQExpBuffer();
11892 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11894 /* look up the foreign-data wrapper */
11895 selectSourceSchema(fout, "pg_catalog");
11896 appendPQExpBuffer(query, "SELECT fdwname "
11897 "FROM pg_foreign_data_wrapper w "
11898 "WHERE w.oid = '%u'",
11900 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11901 fdwname = PQgetvalue(res, 0, 0);
11903 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11904 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11906 appendPQExpBuffer(q, " TYPE ");
11907 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11909 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11911 appendPQExpBuffer(q, " VERSION ");
11912 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11915 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11916 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11918 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11919 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11921 appendPQExpBuffer(q, ";\n");
11923 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11926 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11928 if (binary_upgrade)
11929 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11931 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11932 srvinfo->dobj.name,
11936 false, "SERVER", SECTION_PRE_DATA,
11937 q->data, delq->data, NULL,
11941 /* Handle the ACL */
11942 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11944 qsrvname, NULL, srvinfo->dobj.name,
11945 NULL, srvinfo->rolname,
11948 /* Dump user mappings */
11949 dumpUserMappings(fout,
11950 srvinfo->dobj.name, NULL,
11952 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11954 /* Dump Foreign Server Comments */
11955 dumpComment(fout, labelq->data,
11956 NULL, srvinfo->rolname,
11957 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11961 destroyPQExpBuffer(q);
11962 destroyPQExpBuffer(delq);
11963 destroyPQExpBuffer(labelq);
11969 * This routine is used to dump any user mappings associated with the
11970 * server handed to this routine. Should be called after ArchiveEntry()
11974 dumpUserMappings(Archive *fout,
11975 const char *servername, const char *namespace,
11977 CatalogId catalogId, DumpId dumpId)
11989 q = createPQExpBuffer();
11990 tag = createPQExpBuffer();
11991 delq = createPQExpBuffer();
11992 query = createPQExpBuffer();
11995 * We read from the publicly accessible view pg_user_mappings, so as not
11996 * to fail if run by a non-superuser. Note that the view will show
11997 * umoptions as null if the user hasn't got privileges for the associated
11998 * server; this means that pg_dump will dump such a mapping, but with no
11999 * OPTIONS clause. A possible alternative is to skip such mappings
12000 * altogether, but it's not clear that that's an improvement.
12002 selectSourceSchema(fout, "pg_catalog");
12004 appendPQExpBuffer(query,
12006 "array_to_string(ARRAY("
12007 "SELECT quote_ident(option_name) || ' ' || "
12008 "quote_literal(option_value) "
12009 "FROM pg_options_to_table(umoptions) "
12010 "ORDER BY option_name"
12011 "), E',\n ') AS umoptions "
12012 "FROM pg_user_mappings "
12013 "WHERE srvid = '%u' "
12014 "ORDER BY usename",
12017 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12019 ntups = PQntuples(res);
12020 i_usename = PQfnumber(res, "usename");
12021 i_umoptions = PQfnumber(res, "umoptions");
12023 for (i = 0; i < ntups; i++)
12028 usename = PQgetvalue(res, i, i_usename);
12029 umoptions = PQgetvalue(res, i, i_umoptions);
12031 resetPQExpBuffer(q);
12032 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
12033 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
12035 if (umoptions && strlen(umoptions) > 0)
12036 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
12038 appendPQExpBuffer(q, ";\n");
12040 resetPQExpBuffer(delq);
12041 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
12042 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
12044 resetPQExpBuffer(tag);
12045 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
12046 usename, servername);
12048 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12053 "USER MAPPING", SECTION_PRE_DATA,
12054 q->data, delq->data, NULL,
12061 destroyPQExpBuffer(query);
12062 destroyPQExpBuffer(delq);
12063 destroyPQExpBuffer(q);
12067 * Write out default privileges information
12070 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
12076 /* Skip if not to be dumped */
12077 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
12080 q = createPQExpBuffer();
12081 tag = createPQExpBuffer();
12083 switch (daclinfo->defaclobjtype)
12085 case DEFACLOBJ_RELATION:
12088 case DEFACLOBJ_SEQUENCE:
12089 type = "SEQUENCES";
12091 case DEFACLOBJ_FUNCTION:
12092 type = "FUNCTIONS";
12094 case DEFACLOBJ_TYPE:
12098 /* shouldn't get here */
12099 exit_horribly(NULL,
12100 "unrecognized object type in default privileges: %d\n",
12101 (int) daclinfo->defaclobjtype);
12102 type = ""; /* keep compiler quiet */
12105 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
12107 /* build the actual command(s) for this tuple */
12108 if (!buildDefaultACLCommands(type,
12109 daclinfo->dobj.namespace != NULL ?
12110 daclinfo->dobj.namespace->dobj.name : NULL,
12111 daclinfo->defaclacl,
12112 daclinfo->defaclrole,
12113 fout->remoteVersion,
12115 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
12116 daclinfo->defaclacl);
12118 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
12120 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
12122 daclinfo->defaclrole,
12123 false, "DEFAULT ACL", SECTION_POST_DATA,
12128 destroyPQExpBuffer(tag);
12129 destroyPQExpBuffer(q);
12133 * Write out grant/revoke information
12135 * 'objCatId' is the catalog ID of the underlying object.
12136 * 'objDumpId' is the dump ID of the underlying object.
12137 * 'type' must be one of
12138 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
12139 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
12140 * 'name' is the formatted name of the object. Must be quoted etc. already.
12141 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
12142 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12143 * 'nspname' is the namespace the object is in (NULL if none).
12144 * 'owner' is the owner, NULL if there is no owner (for languages).
12145 * 'acls' is the string read out of the fooacl system catalog field;
12146 * it will be parsed here.
12150 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12151 const char *type, const char *name, const char *subname,
12152 const char *tag, const char *nspname, const char *owner,
12157 /* Do nothing if ACL dump is not enabled */
12161 /* --data-only skips ACLs *except* BLOB ACLs */
12162 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12165 sql = createPQExpBuffer();
12167 if (!buildACLCommands(name, subname, type, acls, owner,
12168 "", fout->remoteVersion, sql))
12169 exit_horribly(NULL,
12170 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12174 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12177 owner ? owner : "",
12178 false, "ACL", SECTION_NONE,
12179 sql->data, "", NULL,
12183 destroyPQExpBuffer(sql);
12189 * This routine is used to dump any security labels associated with the
12190 * object handed to this routine. The routine takes a constant character
12191 * string for the target part of the security-label command, plus
12192 * the namespace and owner of the object (for labeling the ArchiveEntry),
12193 * plus catalog ID and subid which are the lookup key for pg_seclabel,
12194 * plus the dump ID for the object (for setting a dependency).
12195 * If a matching pg_seclabel entry is found, it is dumped.
12197 * Note: although this routine takes a dumpId for dependency purposes,
12198 * that purpose is just to mark the dependency in the emitted dump file
12199 * for possible future use by pg_restore. We do NOT use it for determining
12200 * ordering of the label in the dump file, because this routine is called
12201 * after dependency sorting occurs. This routine should be called just after
12202 * calling ArchiveEntry() for the specified object.
12205 dumpSecLabel(Archive *fout, const char *target,
12206 const char *namespace, const char *owner,
12207 CatalogId catalogId, int subid, DumpId dumpId)
12209 SecLabelItem *labels;
12214 /* do nothing, if --no-security-labels is supplied */
12215 if (no_security_labels)
12218 /* Comments are schema not data ... except blob comments are data */
12219 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12230 /* Search for security labels associated with catalogId, using table */
12231 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12233 query = createPQExpBuffer();
12235 for (i = 0; i < nlabels; i++)
12238 * Ignore label entries for which the subid doesn't match.
12240 if (labels[i].objsubid != subid)
12243 appendPQExpBuffer(query,
12244 "SECURITY LABEL FOR %s ON %s IS ",
12245 fmtId(labels[i].provider), target);
12246 appendStringLiteralAH(query, labels[i].label, fout);
12247 appendPQExpBuffer(query, ";\n");
12250 if (query->len > 0)
12252 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12253 target, namespace, NULL, owner,
12254 false, "SECURITY LABEL", SECTION_NONE,
12255 query->data, "", NULL,
12259 destroyPQExpBuffer(query);
12263 * dumpTableSecLabel
12265 * As above, but dump security label for both the specified table (or view)
12269 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12271 SecLabelItem *labels;
12275 PQExpBuffer target;
12277 /* do nothing, if --no-security-labels is supplied */
12278 if (no_security_labels)
12281 /* SecLabel are SCHEMA not data */
12285 /* Search for comments associated with relation, using table */
12286 nlabels = findSecLabels(fout,
12287 tbinfo->dobj.catId.tableoid,
12288 tbinfo->dobj.catId.oid,
12291 /* If security labels exist, build SECURITY LABEL statements */
12295 query = createPQExpBuffer();
12296 target = createPQExpBuffer();
12298 for (i = 0; i < nlabels; i++)
12300 const char *colname;
12301 const char *provider = labels[i].provider;
12302 const char *label = labels[i].label;
12303 int objsubid = labels[i].objsubid;
12305 resetPQExpBuffer(target);
12308 appendPQExpBuffer(target, "%s %s", reltypename,
12309 fmtId(tbinfo->dobj.name));
12313 colname = getAttrName(objsubid, tbinfo);
12314 /* first fmtId result must be consumed before calling it again */
12315 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12316 appendPQExpBuffer(target, ".%s", fmtId(colname));
12318 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12319 fmtId(provider), target->data);
12320 appendStringLiteralAH(query, label, fout);
12321 appendPQExpBuffer(query, ";\n");
12323 if (query->len > 0)
12325 resetPQExpBuffer(target);
12326 appendPQExpBuffer(target, "%s %s", reltypename,
12327 fmtId(tbinfo->dobj.name));
12328 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12330 tbinfo->dobj.namespace->dobj.name,
12331 NULL, tbinfo->rolname,
12332 false, "SECURITY LABEL", SECTION_NONE,
12333 query->data, "", NULL,
12334 &(tbinfo->dobj.dumpId), 1,
12337 destroyPQExpBuffer(query);
12338 destroyPQExpBuffer(target);
12344 * Find the security label(s), if any, associated with the given object.
12345 * All the objsubid values associated with the given classoid/objoid are
12346 * found with one search.
12349 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12351 /* static storage for table of security labels */
12352 static SecLabelItem *labels = NULL;
12353 static int nlabels = -1;
12355 SecLabelItem *middle = NULL;
12357 SecLabelItem *high;
12360 /* Get security labels if we didn't already */
12362 nlabels = collectSecLabels(fout, &labels);
12364 if (nlabels <= 0) /* no labels, so no match is possible */
12371 * Do binary search to find some item matching the object.
12374 high = &labels[nlabels - 1];
12375 while (low <= high)
12377 middle = low + (high - low) / 2;
12379 if (classoid < middle->classoid)
12381 else if (classoid > middle->classoid)
12383 else if (objoid < middle->objoid)
12385 else if (objoid > middle->objoid)
12388 break; /* found a match */
12391 if (low > high) /* no matches */
12398 * Now determine how many items match the object. The search loop
12399 * invariant still holds: only items between low and high inclusive could
12403 while (middle > low)
12405 if (classoid != middle[-1].classoid ||
12406 objoid != middle[-1].objoid)
12415 while (middle <= high)
12417 if (classoid != middle->classoid ||
12418 objoid != middle->objoid)
12430 * Construct a table of all security labels available for database objects.
12431 * It's much faster to pull them all at once.
12433 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12436 collectSecLabels(Archive *fout, SecLabelItem **items)
12447 SecLabelItem *labels;
12449 query = createPQExpBuffer();
12451 appendPQExpBuffer(query,
12452 "SELECT label, provider, classoid, objoid, objsubid "
12453 "FROM pg_catalog.pg_seclabel "
12454 "ORDER BY classoid, objoid, objsubid");
12456 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12458 /* Construct lookup table containing OIDs in numeric form */
12459 i_label = PQfnumber(res, "label");
12460 i_provider = PQfnumber(res, "provider");
12461 i_classoid = PQfnumber(res, "classoid");
12462 i_objoid = PQfnumber(res, "objoid");
12463 i_objsubid = PQfnumber(res, "objsubid");
12465 ntups = PQntuples(res);
12467 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12469 for (i = 0; i < ntups; i++)
12471 labels[i].label = PQgetvalue(res, i, i_label);
12472 labels[i].provider = PQgetvalue(res, i, i_provider);
12473 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12474 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12475 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12478 /* Do NOT free the PGresult since we are keeping pointers into it */
12479 destroyPQExpBuffer(query);
12487 * write out to fout the declarations (not data) of a user-defined table
12490 dumpTable(Archive *fout, TableInfo *tbinfo)
12492 if (tbinfo->dobj.dump && !dataOnly)
12496 if (tbinfo->relkind == RELKIND_SEQUENCE)
12497 dumpSequence(fout, tbinfo);
12499 dumpTableSchema(fout, tbinfo);
12501 /* Handle the ACL here */
12502 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12503 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12504 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12506 namecopy, NULL, tbinfo->dobj.name,
12507 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12511 * Handle column ACLs, if any. Note: we pull these with a separate
12512 * query rather than trying to fetch them during getTableAttrs, so
12513 * that we won't miss ACLs on system columns.
12515 if (fout->remoteVersion >= 80400)
12517 PQExpBuffer query = createPQExpBuffer();
12521 appendPQExpBuffer(query,
12522 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12523 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12525 tbinfo->dobj.catId.oid);
12526 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12528 for (i = 0; i < PQntuples(res); i++)
12530 char *attname = PQgetvalue(res, i, 0);
12531 char *attacl = PQgetvalue(res, i, 1);
12535 attnamecopy = pg_strdup(fmtId(attname));
12536 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12537 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12538 /* Column's GRANT type is always TABLE */
12539 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12540 namecopy, attnamecopy, acltag,
12541 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12547 destroyPQExpBuffer(query);
12555 * Create the AS clause for a view or materialized view. The semicolon is
12556 * stripped because a materialized view must add a WITH NO DATA clause.
12558 * This returns a new buffer which must be freed by the caller.
12561 createViewAsClause(Archive *fout, TableInfo *tbinfo)
12563 PQExpBuffer query = createPQExpBuffer();
12564 PQExpBuffer result = createPQExpBuffer();
12568 /* Fetch the view definition */
12569 if (fout->remoteVersion >= 70300)
12571 /* Beginning in 7.3, viewname is not unique; rely on OID */
12572 appendPQExpBuffer(query,
12573 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12574 tbinfo->dobj.catId.oid);
12578 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12579 "FROM pg_views WHERE viewname = ");
12580 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12581 appendPQExpBuffer(query, ";");
12584 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12586 if (PQntuples(res) != 1)
12588 if (PQntuples(res) < 1)
12589 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12590 tbinfo->dobj.name);
12592 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12593 tbinfo->dobj.name);
12596 len = PQgetlength(res, 0, 0);
12599 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12600 tbinfo->dobj.name);
12602 /* Strip off the trailing semicolon so that other things may follow. */
12603 Assert(PQgetvalue(res, 0, 0)[len-1] == ';');
12604 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
12607 destroyPQExpBuffer(query);
12614 * write the declaration (not data) of one user-defined table or view
12617 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12619 PQExpBuffer q = createPQExpBuffer();
12620 PQExpBuffer delq = createPQExpBuffer();
12621 PQExpBuffer labelq = createPQExpBuffer();
12623 TableInfo **parents;
12624 int actual_atts; /* number of attrs in this CREATE statement */
12625 const char *reltypename;
12632 /* Make sure we are in proper schema */
12633 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12635 if (binary_upgrade)
12636 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12637 tbinfo->dobj.catId.oid);
12639 /* Is it a table or a view? */
12640 if (tbinfo->relkind == RELKIND_VIEW)
12642 PQExpBuffer result;
12644 reltypename = "VIEW";
12647 * DROP must be fully qualified in case same name appears in
12650 appendPQExpBuffer(delq, "DROP VIEW %s.",
12651 fmtId(tbinfo->dobj.namespace->dobj.name));
12652 appendPQExpBuffer(delq, "%s;\n",
12653 fmtId(tbinfo->dobj.name));
12655 if (binary_upgrade)
12656 binary_upgrade_set_pg_class_oids(fout, q,
12657 tbinfo->dobj.catId.oid, false);
12659 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12660 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12661 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12662 result = createViewAsClause(fout, tbinfo);
12663 appendPQExpBuffer(q, " AS\n%s;\n", result->data);
12664 destroyPQExpBuffer(result);
12666 appendPQExpBuffer(labelq, "VIEW %s",
12667 fmtId(tbinfo->dobj.name));
12671 switch (tbinfo->relkind)
12673 case (RELKIND_FOREIGN_TABLE):
12675 PQExpBuffer query = createPQExpBuffer();
12680 reltypename = "FOREIGN TABLE";
12682 /* retrieve name of foreign server and generic options */
12683 appendPQExpBuffer(query,
12684 "SELECT fs.srvname, "
12685 "pg_catalog.array_to_string(ARRAY("
12686 "SELECT pg_catalog.quote_ident(option_name) || "
12687 "' ' || pg_catalog.quote_literal(option_value) "
12688 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12689 "ORDER BY option_name"
12690 "), E',\n ') AS ftoptions "
12691 "FROM pg_catalog.pg_foreign_table ft "
12692 "JOIN pg_catalog.pg_foreign_server fs "
12693 "ON (fs.oid = ft.ftserver) "
12694 "WHERE ft.ftrelid = '%u'",
12695 tbinfo->dobj.catId.oid);
12696 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12697 i_srvname = PQfnumber(res, "srvname");
12698 i_ftoptions = PQfnumber(res, "ftoptions");
12699 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12700 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12702 destroyPQExpBuffer(query);
12705 case (RELKIND_MATVIEW):
12706 reltypename = "MATERIALIZED VIEW";
12711 reltypename = "TABLE";
12716 numParents = tbinfo->numParents;
12717 parents = tbinfo->parents;
12720 * DROP must be fully qualified in case same name appears in
12723 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12724 fmtId(tbinfo->dobj.namespace->dobj.name));
12725 appendPQExpBuffer(delq, "%s;\n",
12726 fmtId(tbinfo->dobj.name));
12728 appendPQExpBuffer(labelq, "%s %s", reltypename,
12729 fmtId(tbinfo->dobj.name));
12731 if (binary_upgrade)
12732 binary_upgrade_set_pg_class_oids(fout, q,
12733 tbinfo->dobj.catId.oid, false);
12735 appendPQExpBuffer(q, "CREATE %s%s %s",
12736 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12739 fmtId(tbinfo->dobj.name));
12742 * Attach to type, if reloftype; except in case of a binary upgrade,
12743 * we dump the table normally and attach it to the type afterward.
12745 if (tbinfo->reloftype && !binary_upgrade)
12746 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12748 if (tbinfo->relkind != RELKIND_MATVIEW)
12750 /* Dump the attributes */
12752 for (j = 0; j < tbinfo->numatts; j++)
12755 * Normally, dump if it's locally defined in this table, and not
12756 * dropped. But for binary upgrade, we'll dump all the columns,
12757 * and then fix up the dropped and nonlocal cases below.
12759 if (shouldPrintColumn(tbinfo, j))
12762 * Default value --- suppress if to be printed separately.
12764 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12765 !tbinfo->attrdefs[j]->separate);
12768 * Not Null constraint --- suppress if inherited, except in
12769 * binary-upgrade case where that won't work.
12771 bool has_notnull = (tbinfo->notnull[j] &&
12772 (!tbinfo->inhNotNull[j] ||
12775 /* Skip column if fully defined by reloftype */
12776 if (tbinfo->reloftype &&
12777 !has_default && !has_notnull && !binary_upgrade)
12780 /* Format properly if not first attr */
12781 if (actual_atts == 0)
12782 appendPQExpBuffer(q, " (");
12784 appendPQExpBuffer(q, ",");
12785 appendPQExpBuffer(q, "\n ");
12788 /* Attribute name */
12789 appendPQExpBuffer(q, "%s",
12790 fmtId(tbinfo->attnames[j]));
12792 if (tbinfo->attisdropped[j])
12795 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12796 * so we will not have gotten a valid type name; insert
12797 * INTEGER as a stopgap. We'll clean things up later.
12799 appendPQExpBuffer(q, " INTEGER /* dummy */");
12800 /* Skip all the rest, too */
12804 /* Attribute type */
12805 if (tbinfo->reloftype && !binary_upgrade)
12807 appendPQExpBuffer(q, " WITH OPTIONS");
12809 else if (fout->remoteVersion >= 70100)
12811 appendPQExpBuffer(q, " %s",
12812 tbinfo->atttypnames[j]);
12816 /* If no format_type, fake it */
12817 appendPQExpBuffer(q, " %s",
12818 myFormatType(tbinfo->atttypnames[j],
12819 tbinfo->atttypmod[j]));
12822 /* Add collation if not default for the type */
12823 if (OidIsValid(tbinfo->attcollation[j]))
12827 coll = findCollationByOid(tbinfo->attcollation[j]);
12830 /* always schema-qualify, don't try to be smart */
12831 appendPQExpBuffer(q, " COLLATE %s.",
12832 fmtId(coll->dobj.namespace->dobj.name));
12833 appendPQExpBuffer(q, "%s",
12834 fmtId(coll->dobj.name));
12839 appendPQExpBuffer(q, " DEFAULT %s",
12840 tbinfo->attrdefs[j]->adef_expr);
12843 appendPQExpBuffer(q, " NOT NULL");
12848 * Add non-inherited CHECK constraints, if any.
12850 for (j = 0; j < tbinfo->ncheck; j++)
12852 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12854 if (constr->separate || !constr->conislocal)
12857 if (actual_atts == 0)
12858 appendPQExpBuffer(q, " (\n ");
12860 appendPQExpBuffer(q, ",\n ");
12862 appendPQExpBuffer(q, "CONSTRAINT %s ",
12863 fmtId(constr->dobj.name));
12864 appendPQExpBuffer(q, "%s", constr->condef);
12870 appendPQExpBuffer(q, "\n)");
12871 else if (!(tbinfo->reloftype && !binary_upgrade))
12874 * We must have a parenthesized attribute list, even though empty,
12875 * when not using the OF TYPE syntax.
12877 appendPQExpBuffer(q, " (\n)");
12880 if (numParents > 0 && !binary_upgrade)
12882 appendPQExpBuffer(q, "\nINHERITS (");
12883 for (k = 0; k < numParents; k++)
12885 TableInfo *parentRel = parents[k];
12888 appendPQExpBuffer(q, ", ");
12889 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12890 appendPQExpBuffer(q, "%s.",
12891 fmtId(parentRel->dobj.namespace->dobj.name));
12892 appendPQExpBuffer(q, "%s",
12893 fmtId(parentRel->dobj.name));
12895 appendPQExpBuffer(q, ")");
12898 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12899 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12902 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12903 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12905 bool addcomma = false;
12907 appendPQExpBuffer(q, "\nWITH (");
12908 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12911 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12913 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12915 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12916 tbinfo->toast_reloptions);
12918 appendPQExpBuffer(q, ")");
12921 /* Dump generic options if any */
12922 if (ftoptions && ftoptions[0])
12923 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12926 * For materialized views, create the AS clause just like a view.
12928 if (tbinfo->relkind == RELKIND_MATVIEW)
12930 PQExpBuffer result;
12932 result = createViewAsClause(fout, tbinfo);
12933 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
12935 destroyPQExpBuffer(result);
12938 appendPQExpBuffer(q, ";\n");
12941 * To create binary-compatible heap files, we have to ensure the same
12942 * physical column order, including dropped columns, as in the
12943 * original. Therefore, we create dropped columns above and drop them
12944 * here, also updating their attlen/attalign values so that the
12945 * dropped column can be skipped properly. (We do not bother with
12946 * restoring the original attbyval setting.) Also, inheritance
12947 * relationships are set up by doing ALTER INHERIT rather than using
12948 * an INHERITS clause --- the latter would possibly mess up the column
12949 * order. That also means we have to take care about setting
12950 * attislocal correctly, plus fix up any inherited CHECK constraints.
12951 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12953 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12955 for (j = 0; j < tbinfo->numatts; j++)
12957 if (tbinfo->attisdropped[j])
12959 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12960 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12961 "SET attlen = %d, "
12962 "attalign = '%c', attbyval = false\n"
12963 "WHERE attname = ",
12965 tbinfo->attalign[j]);
12966 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12967 appendPQExpBuffer(q, "\n AND attrelid = ");
12968 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12969 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12971 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12972 fmtId(tbinfo->dobj.name));
12973 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12974 fmtId(tbinfo->attnames[j]));
12976 else if (!tbinfo->attislocal[j])
12978 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12979 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12980 "SET attislocal = false\n"
12981 "WHERE attname = ");
12982 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12983 appendPQExpBuffer(q, "\n AND attrelid = ");
12984 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12985 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12989 for (k = 0; k < tbinfo->ncheck; k++)
12991 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12993 if (constr->separate || constr->conislocal)
12996 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12997 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12998 fmtId(tbinfo->dobj.name));
12999 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13000 fmtId(constr->dobj.name));
13001 appendPQExpBuffer(q, "%s;\n", constr->condef);
13002 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
13003 "SET conislocal = false\n"
13004 "WHERE contype = 'c' AND conname = ");
13005 appendStringLiteralAH(q, constr->dobj.name, fout);
13006 appendPQExpBuffer(q, "\n AND conrelid = ");
13007 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13008 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13011 if (numParents > 0)
13013 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
13014 for (k = 0; k < numParents; k++)
13016 TableInfo *parentRel = parents[k];
13018 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
13019 fmtId(tbinfo->dobj.name));
13020 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13021 appendPQExpBuffer(q, "%s.",
13022 fmtId(parentRel->dobj.namespace->dobj.name));
13023 appendPQExpBuffer(q, "%s;\n",
13024 fmtId(parentRel->dobj.name));
13028 if (tbinfo->reloftype)
13030 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
13031 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
13032 fmtId(tbinfo->dobj.name),
13033 tbinfo->reloftype);
13036 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
13037 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13038 "SET relfrozenxid = '%u'\n"
13040 tbinfo->frozenxid);
13041 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13042 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13044 if (tbinfo->toast_oid)
13046 /* We preserve the toast oids, so we can use it during restore */
13047 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
13048 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13049 "SET relfrozenxid = '%u'\n"
13050 "WHERE oid = '%u';\n",
13051 tbinfo->toast_frozenxid, tbinfo->toast_oid);
13056 * Dump additional per-column properties that we can't handle in the
13057 * main CREATE TABLE command.
13059 for (j = 0; j < tbinfo->numatts; j++)
13061 /* None of this applies to dropped columns */
13062 if (tbinfo->attisdropped[j])
13066 * If we didn't dump the column definition explicitly above, and
13067 * it is NOT NULL and did not inherit that property from a parent,
13068 * we have to mark it separately.
13070 if (!shouldPrintColumn(tbinfo, j) &&
13071 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
13073 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13074 fmtId(tbinfo->dobj.name));
13075 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
13076 fmtId(tbinfo->attnames[j]));
13080 * Dump per-column statistics information. We only issue an ALTER
13081 * TABLE statement if the attstattarget entry for this column is
13082 * non-negative (i.e. it's not the default value)
13084 if (tbinfo->attstattarget[j] >= 0)
13086 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13087 fmtId(tbinfo->dobj.name));
13088 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13089 fmtId(tbinfo->attnames[j]));
13090 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
13091 tbinfo->attstattarget[j]);
13095 * Dump per-column storage information. The statement is only
13096 * dumped if the storage has been changed from the type's default.
13098 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
13100 switch (tbinfo->attstorage[j])
13106 storage = "EXTERNAL";
13112 storage = "EXTENDED";
13119 * Only dump the statement if it's a storage type we recognize
13121 if (storage != NULL)
13123 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13124 fmtId(tbinfo->dobj.name));
13125 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13126 fmtId(tbinfo->attnames[j]));
13127 appendPQExpBuffer(q, "SET STORAGE %s;\n",
13133 * Dump per-column attributes.
13135 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
13137 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13138 fmtId(tbinfo->dobj.name));
13139 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13140 fmtId(tbinfo->attnames[j]));
13141 appendPQExpBuffer(q, "SET (%s);\n",
13142 tbinfo->attoptions[j]);
13146 * Dump per-column fdw options.
13148 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
13149 tbinfo->attfdwoptions[j] &&
13150 tbinfo->attfdwoptions[j][0] != '\0')
13152 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13153 fmtId(tbinfo->dobj.name));
13154 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13155 fmtId(tbinfo->attnames[j]));
13156 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
13157 tbinfo->attfdwoptions[j]);
13162 if (binary_upgrade)
13163 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
13165 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13167 tbinfo->dobj.namespace->dobj.name,
13168 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
13170 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
13171 reltypename, SECTION_PRE_DATA,
13172 q->data, delq->data, NULL,
13177 /* Dump Table Comments */
13178 dumpTableComment(fout, tbinfo, reltypename);
13180 /* Dump Table Security Labels */
13181 dumpTableSecLabel(fout, tbinfo, reltypename);
13183 /* Dump comments on inlined table constraints */
13184 for (j = 0; j < tbinfo->ncheck; j++)
13186 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13188 if (constr->separate || !constr->conislocal)
13191 dumpTableConstraintComment(fout, constr);
13194 destroyPQExpBuffer(q);
13195 destroyPQExpBuffer(delq);
13196 destroyPQExpBuffer(labelq);
13200 * dumpAttrDef --- dump an attribute's default-value declaration
13203 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13205 TableInfo *tbinfo = adinfo->adtable;
13206 int adnum = adinfo->adnum;
13210 /* Skip if table definition not to be dumped */
13211 if (!tbinfo->dobj.dump || dataOnly)
13214 /* Skip if not "separate"; it was dumped in the table's definition */
13215 if (!adinfo->separate)
13218 q = createPQExpBuffer();
13219 delq = createPQExpBuffer();
13221 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13222 fmtId(tbinfo->dobj.name));
13223 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13224 fmtId(tbinfo->attnames[adnum - 1]),
13225 adinfo->adef_expr);
13228 * DROP must be fully qualified in case same name appears in pg_catalog
13230 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13231 fmtId(tbinfo->dobj.namespace->dobj.name));
13232 appendPQExpBuffer(delq, "%s ",
13233 fmtId(tbinfo->dobj.name));
13234 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13235 fmtId(tbinfo->attnames[adnum - 1]));
13237 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13238 tbinfo->attnames[adnum - 1],
13239 tbinfo->dobj.namespace->dobj.name,
13242 false, "DEFAULT", SECTION_PRE_DATA,
13243 q->data, delq->data, NULL,
13247 destroyPQExpBuffer(q);
13248 destroyPQExpBuffer(delq);
13252 * getAttrName: extract the correct name for an attribute
13254 * The array tblInfo->attnames[] only provides names of user attributes;
13255 * if a system attribute number is supplied, we have to fake it.
13256 * We also do a little bit of bounds checking for safety's sake.
13258 static const char *
13259 getAttrName(int attrnum, TableInfo *tblInfo)
13261 if (attrnum > 0 && attrnum <= tblInfo->numatts)
13262 return tblInfo->attnames[attrnum - 1];
13265 case SelfItemPointerAttributeNumber:
13267 case ObjectIdAttributeNumber:
13269 case MinTransactionIdAttributeNumber:
13271 case MinCommandIdAttributeNumber:
13273 case MaxTransactionIdAttributeNumber:
13275 case MaxCommandIdAttributeNumber:
13277 case TableOidAttributeNumber:
13280 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13281 attrnum, tblInfo->dobj.name);
13282 return NULL; /* keep compiler quiet */
13287 * write out to fout a user-defined index
13290 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13292 TableInfo *tbinfo = indxinfo->indextable;
13295 PQExpBuffer labelq;
13300 q = createPQExpBuffer();
13301 delq = createPQExpBuffer();
13302 labelq = createPQExpBuffer();
13304 appendPQExpBuffer(labelq, "INDEX %s",
13305 fmtId(indxinfo->dobj.name));
13308 * If there's an associated constraint, don't dump the index per se, but
13309 * do dump any comment for it. (This is safe because dependency ordering
13310 * will have ensured the constraint is emitted first.)
13312 if (indxinfo->indexconstraint == 0)
13314 if (binary_upgrade)
13315 binary_upgrade_set_pg_class_oids(fout, q,
13316 indxinfo->dobj.catId.oid, true);
13318 /* Plain secondary index */
13319 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13321 /* If the index is clustered, we need to record that. */
13322 if (indxinfo->indisclustered)
13324 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13325 fmtId(tbinfo->dobj.name));
13326 appendPQExpBuffer(q, " ON %s;\n",
13327 fmtId(indxinfo->dobj.name));
13331 * DROP must be fully qualified in case same name appears in
13334 appendPQExpBuffer(delq, "DROP INDEX %s.",
13335 fmtId(tbinfo->dobj.namespace->dobj.name));
13336 appendPQExpBuffer(delq, "%s;\n",
13337 fmtId(indxinfo->dobj.name));
13339 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13340 indxinfo->dobj.name,
13341 tbinfo->dobj.namespace->dobj.name,
13342 indxinfo->tablespace,
13343 tbinfo->rolname, false,
13344 "INDEX", SECTION_POST_DATA,
13345 q->data, delq->data, NULL,
13350 /* Dump Index Comments */
13351 dumpComment(fout, labelq->data,
13352 tbinfo->dobj.namespace->dobj.name,
13354 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13356 destroyPQExpBuffer(q);
13357 destroyPQExpBuffer(delq);
13358 destroyPQExpBuffer(labelq);
13363 * write out to fout a user-defined constraint
13366 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13368 TableInfo *tbinfo = coninfo->contable;
13372 /* Skip if not to be dumped */
13373 if (!coninfo->dobj.dump || dataOnly)
13376 q = createPQExpBuffer();
13377 delq = createPQExpBuffer();
13379 if (coninfo->contype == 'p' ||
13380 coninfo->contype == 'u' ||
13381 coninfo->contype == 'x')
13383 /* Index-related constraint */
13384 IndxInfo *indxinfo;
13387 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13389 if (indxinfo == NULL)
13390 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13391 coninfo->dobj.name);
13393 if (binary_upgrade)
13394 binary_upgrade_set_pg_class_oids(fout, q,
13395 indxinfo->dobj.catId.oid, true);
13397 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13398 fmtId(tbinfo->dobj.name));
13399 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13400 fmtId(coninfo->dobj.name));
13402 if (coninfo->condef)
13404 /* pg_get_constraintdef should have provided everything */
13405 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13409 appendPQExpBuffer(q, "%s (",
13410 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13411 for (k = 0; k < indxinfo->indnkeys; k++)
13413 int indkey = (int) indxinfo->indkeys[k];
13414 const char *attname;
13416 if (indkey == InvalidAttrNumber)
13418 attname = getAttrName(indkey, tbinfo);
13420 appendPQExpBuffer(q, "%s%s",
13421 (k == 0) ? "" : ", ",
13425 appendPQExpBuffer(q, ")");
13427 if (indxinfo->options && strlen(indxinfo->options) > 0)
13428 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13430 if (coninfo->condeferrable)
13432 appendPQExpBuffer(q, " DEFERRABLE");
13433 if (coninfo->condeferred)
13434 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13437 appendPQExpBuffer(q, ";\n");
13440 /* If the index is clustered, we need to record that. */
13441 if (indxinfo->indisclustered)
13443 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13444 fmtId(tbinfo->dobj.name));
13445 appendPQExpBuffer(q, " ON %s;\n",
13446 fmtId(indxinfo->dobj.name));
13450 * DROP must be fully qualified in case same name appears in
13453 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13454 fmtId(tbinfo->dobj.namespace->dobj.name));
13455 appendPQExpBuffer(delq, "%s ",
13456 fmtId(tbinfo->dobj.name));
13457 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13458 fmtId(coninfo->dobj.name));
13460 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13461 coninfo->dobj.name,
13462 tbinfo->dobj.namespace->dobj.name,
13463 indxinfo->tablespace,
13464 tbinfo->rolname, false,
13465 "CONSTRAINT", SECTION_POST_DATA,
13466 q->data, delq->data, NULL,
13470 else if (coninfo->contype == 'f')
13473 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13474 * current table data is not processed
13476 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13477 fmtId(tbinfo->dobj.name));
13478 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13479 fmtId(coninfo->dobj.name),
13483 * DROP must be fully qualified in case same name appears in
13486 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13487 fmtId(tbinfo->dobj.namespace->dobj.name));
13488 appendPQExpBuffer(delq, "%s ",
13489 fmtId(tbinfo->dobj.name));
13490 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13491 fmtId(coninfo->dobj.name));
13493 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13494 coninfo->dobj.name,
13495 tbinfo->dobj.namespace->dobj.name,
13497 tbinfo->rolname, false,
13498 "FK CONSTRAINT", SECTION_POST_DATA,
13499 q->data, delq->data, NULL,
13503 else if (coninfo->contype == 'c' && tbinfo)
13505 /* CHECK constraint on a table */
13507 /* Ignore if not to be dumped separately */
13508 if (coninfo->separate)
13510 /* not ONLY since we want it to propagate to children */
13511 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13512 fmtId(tbinfo->dobj.name));
13513 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13514 fmtId(coninfo->dobj.name),
13518 * DROP must be fully qualified in case same name appears in
13521 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13522 fmtId(tbinfo->dobj.namespace->dobj.name));
13523 appendPQExpBuffer(delq, "%s ",
13524 fmtId(tbinfo->dobj.name));
13525 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13526 fmtId(coninfo->dobj.name));
13528 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13529 coninfo->dobj.name,
13530 tbinfo->dobj.namespace->dobj.name,
13532 tbinfo->rolname, false,
13533 "CHECK CONSTRAINT", SECTION_POST_DATA,
13534 q->data, delq->data, NULL,
13539 else if (coninfo->contype == 'c' && tbinfo == NULL)
13541 /* CHECK constraint on a domain */
13542 TypeInfo *tyinfo = coninfo->condomain;
13544 /* Ignore if not to be dumped separately */
13545 if (coninfo->separate)
13547 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13548 fmtId(tyinfo->dobj.name));
13549 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13550 fmtId(coninfo->dobj.name),
13554 * DROP must be fully qualified in case same name appears in
13557 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13558 fmtId(tyinfo->dobj.namespace->dobj.name));
13559 appendPQExpBuffer(delq, "%s ",
13560 fmtId(tyinfo->dobj.name));
13561 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13562 fmtId(coninfo->dobj.name));
13564 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13565 coninfo->dobj.name,
13566 tyinfo->dobj.namespace->dobj.name,
13568 tyinfo->rolname, false,
13569 "CHECK CONSTRAINT", SECTION_POST_DATA,
13570 q->data, delq->data, NULL,
13577 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13581 /* Dump Constraint Comments --- only works for table constraints */
13582 if (tbinfo && coninfo->separate)
13583 dumpTableConstraintComment(fout, coninfo);
13585 destroyPQExpBuffer(q);
13586 destroyPQExpBuffer(delq);
13590 * dumpTableConstraintComment --- dump a constraint's comment if any
13592 * This is split out because we need the function in two different places
13593 * depending on whether the constraint is dumped as part of CREATE TABLE
13594 * or as a separate ALTER command.
13597 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13599 TableInfo *tbinfo = coninfo->contable;
13600 PQExpBuffer labelq = createPQExpBuffer();
13602 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13603 fmtId(coninfo->dobj.name));
13604 appendPQExpBuffer(labelq, "ON %s",
13605 fmtId(tbinfo->dobj.name));
13606 dumpComment(fout, labelq->data,
13607 tbinfo->dobj.namespace->dobj.name,
13609 coninfo->dobj.catId, 0,
13610 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13612 destroyPQExpBuffer(labelq);
13616 * findLastBuiltInOid -
13617 * find the last built in oid
13619 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13620 * pg_database entry for the current database
13623 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13627 PQExpBuffer query = createPQExpBuffer();
13629 resetPQExpBuffer(query);
13630 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13631 appendStringLiteralAH(query, dbname, fout);
13633 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13634 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13636 destroyPQExpBuffer(query);
13641 * findLastBuiltInOid -
13642 * find the last built in oid
13644 * For 7.0, we do this by assuming that the last thing that initdb does is to
13645 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13646 * initdb won't be changing anymore, it'll do.
13649 findLastBuiltinOid_V70(Archive *fout)
13654 res = ExecuteSqlQueryForSingleRow(fout,
13655 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13656 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13663 * write the declaration (not data) of one user-defined sequence
13666 dumpSequence(Archive *fout, TableInfo *tbinfo)
13677 PQExpBuffer query = createPQExpBuffer();
13678 PQExpBuffer delqry = createPQExpBuffer();
13679 PQExpBuffer labelq = createPQExpBuffer();
13681 /* Make sure we are in proper schema */
13682 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13684 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13685 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13687 if (fout->remoteVersion >= 80400)
13689 appendPQExpBuffer(query,
13690 "SELECT sequence_name, "
13691 "start_value, increment_by, "
13692 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13693 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13695 "END AS max_value, "
13696 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13697 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13699 "END AS min_value, "
13700 "cache_value, is_cycled FROM %s",
13702 fmtId(tbinfo->dobj.name));
13706 appendPQExpBuffer(query,
13707 "SELECT sequence_name, "
13708 "0 AS start_value, increment_by, "
13709 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13710 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13712 "END AS max_value, "
13713 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13714 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13716 "END AS min_value, "
13717 "cache_value, is_cycled FROM %s",
13719 fmtId(tbinfo->dobj.name));
13722 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13724 if (PQntuples(res) != 1)
13726 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13727 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13729 tbinfo->dobj.name, PQntuples(res));
13733 /* Disable this check: it fails if sequence has been renamed */
13735 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13737 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13738 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13743 startv = PQgetvalue(res, 0, 1);
13744 incby = PQgetvalue(res, 0, 2);
13745 if (!PQgetisnull(res, 0, 3))
13746 maxv = PQgetvalue(res, 0, 3);
13747 if (!PQgetisnull(res, 0, 4))
13748 minv = PQgetvalue(res, 0, 4);
13749 cache = PQgetvalue(res, 0, 5);
13750 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13753 * DROP must be fully qualified in case same name appears in pg_catalog
13755 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13756 fmtId(tbinfo->dobj.namespace->dobj.name));
13757 appendPQExpBuffer(delqry, "%s;\n",
13758 fmtId(tbinfo->dobj.name));
13760 resetPQExpBuffer(query);
13762 if (binary_upgrade)
13764 binary_upgrade_set_pg_class_oids(fout, query,
13765 tbinfo->dobj.catId.oid, false);
13766 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13767 tbinfo->dobj.catId.oid);
13770 appendPQExpBuffer(query,
13771 "CREATE SEQUENCE %s\n",
13772 fmtId(tbinfo->dobj.name));
13774 if (fout->remoteVersion >= 80400)
13775 appendPQExpBuffer(query, " START WITH %s\n", startv);
13777 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13780 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13782 appendPQExpBuffer(query, " NO MINVALUE\n");
13785 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13787 appendPQExpBuffer(query, " NO MAXVALUE\n");
13789 appendPQExpBuffer(query,
13791 cache, (cycled ? "\n CYCLE" : ""));
13793 appendPQExpBuffer(query, ";\n");
13795 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13797 /* binary_upgrade: no need to clear TOAST table oid */
13799 if (binary_upgrade)
13800 binary_upgrade_extension_member(query, &tbinfo->dobj,
13803 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13805 tbinfo->dobj.namespace->dobj.name,
13808 false, "SEQUENCE", SECTION_PRE_DATA,
13809 query->data, delqry->data, NULL,
13814 * If the sequence is owned by a table column, emit the ALTER for it as a
13815 * separate TOC entry immediately following the sequence's own entry.
13816 * It's OK to do this rather than using full sorting logic, because the
13817 * dependency that tells us it's owned will have forced the table to be
13818 * created first. We can't just include the ALTER in the TOC entry
13819 * because it will fail if we haven't reassigned the sequence owner to
13820 * match the table's owner.
13822 * We need not schema-qualify the table reference because both sequence
13823 * and table must be in the same schema.
13825 if (OidIsValid(tbinfo->owning_tab))
13827 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13829 if (owning_tab && owning_tab->dobj.dump)
13831 resetPQExpBuffer(query);
13832 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13833 fmtId(tbinfo->dobj.name));
13834 appendPQExpBuffer(query, " OWNED BY %s",
13835 fmtId(owning_tab->dobj.name));
13836 appendPQExpBuffer(query, ".%s;\n",
13837 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13839 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13841 tbinfo->dobj.namespace->dobj.name,
13844 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13845 query->data, "", NULL,
13846 &(tbinfo->dobj.dumpId), 1,
13851 /* Dump Sequence Comments and Security Labels */
13852 dumpComment(fout, labelq->data,
13853 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13854 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13855 dumpSecLabel(fout, labelq->data,
13856 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13857 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13861 destroyPQExpBuffer(query);
13862 destroyPQExpBuffer(delqry);
13863 destroyPQExpBuffer(labelq);
13868 * write the data of one user-defined sequence
13871 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
13873 TableInfo *tbinfo = tdinfo->tdtable;
13877 PQExpBuffer query = createPQExpBuffer();
13879 /* Make sure we are in proper schema */
13880 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13882 appendPQExpBuffer(query,
13883 "SELECT last_value, is_called FROM %s",
13884 fmtId(tbinfo->dobj.name));
13886 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13888 if (PQntuples(res) != 1)
13890 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13891 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13893 tbinfo->dobj.name, PQntuples(res));
13897 last = PQgetvalue(res, 0, 0);
13898 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
13900 resetPQExpBuffer(query);
13901 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13902 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13903 appendPQExpBuffer(query, ", %s, %s);\n",
13904 last, (called ? "true" : "false"));
13906 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13908 tbinfo->dobj.namespace->dobj.name,
13911 false, "SEQUENCE SET", SECTION_DATA,
13912 query->data, "", NULL,
13913 &(tbinfo->dobj.dumpId), 1,
13918 destroyPQExpBuffer(query);
13922 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13924 TableInfo *tbinfo = tginfo->tgtable;
13926 PQExpBuffer delqry;
13927 PQExpBuffer labelq;
13936 query = createPQExpBuffer();
13937 delqry = createPQExpBuffer();
13938 labelq = createPQExpBuffer();
13941 * DROP must be fully qualified in case same name appears in pg_catalog
13943 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13944 fmtId(tginfo->dobj.name));
13945 appendPQExpBuffer(delqry, "ON %s.",
13946 fmtId(tbinfo->dobj.namespace->dobj.name));
13947 appendPQExpBuffer(delqry, "%s;\n",
13948 fmtId(tbinfo->dobj.name));
13952 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13956 if (tginfo->tgisconstraint)
13958 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13959 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13963 appendPQExpBuffer(query, "CREATE TRIGGER ");
13964 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13966 appendPQExpBuffer(query, "\n ");
13969 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13970 appendPQExpBuffer(query, "BEFORE");
13971 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13972 appendPQExpBuffer(query, "AFTER");
13973 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13974 appendPQExpBuffer(query, "INSTEAD OF");
13977 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13982 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13984 appendPQExpBuffer(query, " INSERT");
13987 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13990 appendPQExpBuffer(query, " OR DELETE");
13992 appendPQExpBuffer(query, " DELETE");
13995 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13998 appendPQExpBuffer(query, " OR UPDATE");
14000 appendPQExpBuffer(query, " UPDATE");
14003 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
14006 appendPQExpBuffer(query, " OR TRUNCATE");
14008 appendPQExpBuffer(query, " TRUNCATE");
14011 appendPQExpBuffer(query, " ON %s\n",
14012 fmtId(tbinfo->dobj.name));
14014 if (tginfo->tgisconstraint)
14016 if (OidIsValid(tginfo->tgconstrrelid))
14018 /* If we are using regclass, name is already quoted */
14019 if (fout->remoteVersion >= 70300)
14020 appendPQExpBuffer(query, " FROM %s\n ",
14021 tginfo->tgconstrrelname);
14023 appendPQExpBuffer(query, " FROM %s\n ",
14024 fmtId(tginfo->tgconstrrelname));
14026 if (!tginfo->tgdeferrable)
14027 appendPQExpBuffer(query, "NOT ");
14028 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
14029 if (tginfo->tginitdeferred)
14030 appendPQExpBuffer(query, "DEFERRED\n");
14032 appendPQExpBuffer(query, "IMMEDIATE\n");
14035 if (TRIGGER_FOR_ROW(tginfo->tgtype))
14036 appendPQExpBuffer(query, " FOR EACH ROW\n ");
14038 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
14040 /* In 7.3, result of regproc is already quoted */
14041 if (fout->remoteVersion >= 70300)
14042 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14045 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14046 fmtId(tginfo->tgfname));
14048 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
14051 for (findx = 0; findx < tginfo->tgnargs; findx++)
14053 /* find the embedded null that terminates this trigger argument */
14054 size_t tlen = strlen(p);
14056 if (p + tlen >= tgargs + lentgargs)
14058 /* hm, not found before end of bytea value... */
14059 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
14062 tbinfo->dobj.name);
14067 appendPQExpBuffer(query, ", ");
14068 appendStringLiteralAH(query, p, fout);
14072 appendPQExpBuffer(query, ");\n");
14075 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
14077 appendPQExpBuffer(query, "\nALTER TABLE %s ",
14078 fmtId(tbinfo->dobj.name));
14079 switch (tginfo->tgenabled)
14083 appendPQExpBuffer(query, "DISABLE");
14086 appendPQExpBuffer(query, "ENABLE ALWAYS");
14089 appendPQExpBuffer(query, "ENABLE REPLICA");
14092 appendPQExpBuffer(query, "ENABLE");
14095 appendPQExpBuffer(query, " TRIGGER %s;\n",
14096 fmtId(tginfo->dobj.name));
14099 appendPQExpBuffer(labelq, "TRIGGER %s ",
14100 fmtId(tginfo->dobj.name));
14101 appendPQExpBuffer(labelq, "ON %s",
14102 fmtId(tbinfo->dobj.name));
14104 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
14106 tbinfo->dobj.namespace->dobj.name,
14108 tbinfo->rolname, false,
14109 "TRIGGER", SECTION_POST_DATA,
14110 query->data, delqry->data, NULL,
14114 dumpComment(fout, labelq->data,
14115 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14116 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
14118 destroyPQExpBuffer(query);
14119 destroyPQExpBuffer(delqry);
14120 destroyPQExpBuffer(labelq);
14124 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
14127 PQExpBuffer labelq;
14129 query = createPQExpBuffer();
14130 labelq = createPQExpBuffer();
14132 appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
14133 appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
14134 appendPQExpBuffer(query, " ON ");
14135 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
14136 appendPQExpBufferStr(query, " ");
14138 if (strcmp("", evtinfo->evttags) != 0)
14140 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
14141 appendPQExpBufferStr(query, evtinfo->evttags);
14142 appendPQExpBufferStr(query, ") ");
14145 appendPQExpBuffer(query, "\n EXECUTE PROCEDURE ");
14146 appendPQExpBufferStr(query, evtinfo->evtfname);
14147 appendPQExpBuffer(query, "();\n");
14149 if (evtinfo->evtenabled != 'O')
14151 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
14152 fmtId(evtinfo->dobj.name));
14153 switch (evtinfo->evtenabled)
14156 appendPQExpBuffer(query, "DISABLE");
14159 appendPQExpBuffer(query, "ENABLE ALWAYS");
14162 appendPQExpBuffer(query, "ENABLE REPLICA");
14165 appendPQExpBuffer(query, "ENABLE");
14168 appendPQExpBuffer(query, ";\n");
14170 appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
14171 fmtId(evtinfo->dobj.name));
14173 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
14174 evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
14175 "EVENT TRIGGER", SECTION_POST_DATA,
14176 query->data, "", NULL, NULL, 0, NULL, NULL);
14178 dumpComment(fout, labelq->data,
14180 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
14182 destroyPQExpBuffer(query);
14183 destroyPQExpBuffer(labelq);
14191 dumpRule(Archive *fout, RuleInfo *rinfo)
14193 TableInfo *tbinfo = rinfo->ruletable;
14196 PQExpBuffer delcmd;
14197 PQExpBuffer labelq;
14200 /* Skip if not to be dumped */
14201 if (!rinfo->dobj.dump || dataOnly)
14205 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
14206 * we do not want to dump it as a separate object.
14208 if (!rinfo->separate)
14212 * Make sure we are in proper schema.
14214 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14216 query = createPQExpBuffer();
14217 cmd = createPQExpBuffer();
14218 delcmd = createPQExpBuffer();
14219 labelq = createPQExpBuffer();
14221 if (fout->remoteVersion >= 70300)
14223 appendPQExpBuffer(query,
14224 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14225 rinfo->dobj.catId.oid);
14229 /* Rule name was unique before 7.3 ... */
14230 appendPQExpBuffer(query,
14231 "SELECT pg_get_ruledef('%s') AS definition",
14235 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14237 if (PQntuples(res) != 1)
14239 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14240 rinfo->dobj.name, tbinfo->dobj.name);
14244 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14247 * Add the command to alter the rules replication firing semantics if it
14248 * differs from the default.
14250 if (rinfo->ev_enabled != 'O')
14252 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14253 switch (rinfo->ev_enabled)
14256 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14257 fmtId(rinfo->dobj.name));
14260 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14261 fmtId(rinfo->dobj.name));
14264 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14265 fmtId(rinfo->dobj.name));
14271 * Apply view's reloptions when its ON SELECT rule is separate.
14273 if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14275 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14276 fmtId(tbinfo->dobj.name),
14277 rinfo->reloptions);
14281 * DROP must be fully qualified in case same name appears in pg_catalog
14283 appendPQExpBuffer(delcmd, "DROP RULE %s ",
14284 fmtId(rinfo->dobj.name));
14285 appendPQExpBuffer(delcmd, "ON %s.",
14286 fmtId(tbinfo->dobj.namespace->dobj.name));
14287 appendPQExpBuffer(delcmd, "%s;\n",
14288 fmtId(tbinfo->dobj.name));
14290 appendPQExpBuffer(labelq, "RULE %s",
14291 fmtId(rinfo->dobj.name));
14292 appendPQExpBuffer(labelq, " ON %s",
14293 fmtId(tbinfo->dobj.name));
14295 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14297 tbinfo->dobj.namespace->dobj.name,
14299 tbinfo->rolname, false,
14300 "RULE", SECTION_POST_DATA,
14301 cmd->data, delcmd->data, NULL,
14305 /* Dump rule comments */
14306 dumpComment(fout, labelq->data,
14307 tbinfo->dobj.namespace->dobj.name,
14309 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14313 destroyPQExpBuffer(query);
14314 destroyPQExpBuffer(cmd);
14315 destroyPQExpBuffer(delcmd);
14316 destroyPQExpBuffer(labelq);
14320 * getExtensionMembership --- obtain extension membership data
14323 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14334 DumpableObject *dobj,
14337 /* Nothing to do if no extensions */
14338 if (numExtensions == 0)
14341 /* Make sure we are in proper schema */
14342 selectSourceSchema(fout, "pg_catalog");
14344 query = createPQExpBuffer();
14346 /* refclassid constraint is redundant but may speed the search */
14347 appendPQExpBuffer(query, "SELECT "
14348 "classid, objid, refclassid, refobjid "
14350 "WHERE refclassid = 'pg_extension'::regclass "
14351 "AND deptype = 'e' "
14354 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14356 ntups = PQntuples(res);
14358 i_classid = PQfnumber(res, "classid");
14359 i_objid = PQfnumber(res, "objid");
14360 i_refclassid = PQfnumber(res, "refclassid");
14361 i_refobjid = PQfnumber(res, "refobjid");
14364 * Since we ordered the SELECT by referenced ID, we can expect that
14365 * multiple entries for the same extension will appear together; this
14366 * saves on searches.
14370 for (i = 0; i < ntups; i++)
14373 CatalogId refobjId;
14375 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14376 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14377 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14378 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14380 if (refdobj == NULL ||
14381 refdobj->catId.tableoid != refobjId.tableoid ||
14382 refdobj->catId.oid != refobjId.oid)
14383 refdobj = findObjectByCatalogId(refobjId);
14386 * Failure to find objects mentioned in pg_depend is not unexpected,
14387 * since for example we don't collect info about TOAST tables.
14389 if (refdobj == NULL)
14392 fprintf(stderr, "no referenced object %u %u\n",
14393 refobjId.tableoid, refobjId.oid);
14398 dobj = findObjectByCatalogId(objId);
14403 fprintf(stderr, "no referencing object %u %u\n",
14404 objId.tableoid, objId.oid);
14409 /* Record dependency so that getDependencies needn't repeat this */
14410 addObjectDependency(dobj, refdobj->dumpId);
14412 dobj->ext_member = true;
14415 * Normally, mark the member object as not to be dumped. But in
14416 * binary upgrades, we still dump the members individually, since the
14417 * idea is to exactly reproduce the database contents rather than
14418 * replace the extension contents with something different.
14420 if (!binary_upgrade)
14421 dobj->dump = false;
14423 dobj->dump = refdobj->dump;
14429 * Now identify extension configuration tables and create TableDataInfo
14430 * objects for them, ensuring their data will be dumped even though the
14431 * tables themselves won't be.
14433 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14434 * user data in a configuration table is treated like schema data. This
14435 * seems appropriate since system data in a config table would get
14436 * reloaded by CREATE EXTENSION.
14438 for (i = 0; i < numExtensions; i++)
14440 ExtensionInfo *curext = &(extinfo[i]);
14441 char *extconfig = curext->extconfig;
14442 char *extcondition = curext->extcondition;
14443 char **extconfigarray = NULL;
14444 char **extconditionarray = NULL;
14446 int nconditionitems;
14448 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14449 if (!curext->dobj.dump)
14452 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14453 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14454 nconfigitems == nconditionitems)
14458 for (j = 0; j < nconfigitems; j++)
14460 TableInfo *configtbl;
14462 configtbl = findTableByOid(atooid(extconfigarray[j]));
14463 if (configtbl == NULL)
14467 * Note: config tables are dumped without OIDs regardless of
14468 * the --oids setting. This is because row filtering
14469 * conditions aren't compatible with dumping OIDs.
14471 makeTableDataInfo(configtbl, false);
14472 if (configtbl->dataObj != NULL)
14474 if (strlen(extconditionarray[j]) > 0)
14475 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14479 if (extconfigarray)
14480 free(extconfigarray);
14481 if (extconditionarray)
14482 free(extconditionarray);
14485 destroyPQExpBuffer(query);
14489 * getDependencies --- obtain available dependency data
14492 getDependencies(Archive *fout)
14503 DumpableObject *dobj,
14506 /* No dependency info available before 7.3 */
14507 if (fout->remoteVersion < 70300)
14511 write_msg(NULL, "reading dependency data\n");
14513 /* Make sure we are in proper schema */
14514 selectSourceSchema(fout, "pg_catalog");
14516 query = createPQExpBuffer();
14519 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14520 * already processed by getExtensionMembership.
14522 appendPQExpBuffer(query, "SELECT "
14523 "classid, objid, refclassid, refobjid, deptype "
14525 "WHERE deptype != 'p' AND deptype != 'e' "
14528 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14530 ntups = PQntuples(res);
14532 i_classid = PQfnumber(res, "classid");
14533 i_objid = PQfnumber(res, "objid");
14534 i_refclassid = PQfnumber(res, "refclassid");
14535 i_refobjid = PQfnumber(res, "refobjid");
14536 i_deptype = PQfnumber(res, "deptype");
14539 * Since we ordered the SELECT by referencing ID, we can expect that
14540 * multiple entries for the same object will appear together; this saves
14545 for (i = 0; i < ntups; i++)
14548 CatalogId refobjId;
14551 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14552 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14553 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14554 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14555 deptype = *(PQgetvalue(res, i, i_deptype));
14557 if (dobj == NULL ||
14558 dobj->catId.tableoid != objId.tableoid ||
14559 dobj->catId.oid != objId.oid)
14560 dobj = findObjectByCatalogId(objId);
14563 * Failure to find objects mentioned in pg_depend is not unexpected,
14564 * since for example we don't collect info about TOAST tables.
14569 fprintf(stderr, "no referencing object %u %u\n",
14570 objId.tableoid, objId.oid);
14575 refdobj = findObjectByCatalogId(refobjId);
14577 if (refdobj == NULL)
14580 fprintf(stderr, "no referenced object %u %u\n",
14581 refobjId.tableoid, refobjId.oid);
14587 * Ordinarily, table rowtypes have implicit dependencies on their
14588 * tables. However, for a composite type the implicit dependency goes
14589 * the other way in pg_depend; which is the right thing for DROP but
14590 * it doesn't produce the dependency ordering we need. So in that one
14591 * case, we reverse the direction of the dependency.
14593 if (deptype == 'i' &&
14594 dobj->objType == DO_TABLE &&
14595 refdobj->objType == DO_TYPE)
14596 addObjectDependency(refdobj, dobj->dumpId);
14599 addObjectDependency(dobj, refdobj->dumpId);
14604 destroyPQExpBuffer(query);
14609 * createBoundaryObjects - create dummy DumpableObjects to represent
14610 * dump section boundaries.
14612 static DumpableObject *
14613 createBoundaryObjects(void)
14615 DumpableObject *dobjs;
14617 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14619 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14620 dobjs[0].catId = nilCatalogId;
14621 AssignDumpId(dobjs + 0);
14622 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14624 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14625 dobjs[1].catId = nilCatalogId;
14626 AssignDumpId(dobjs + 1);
14627 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14633 * addBoundaryDependencies - add dependencies as needed to enforce the dump
14634 * section boundaries.
14637 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14638 DumpableObject *boundaryObjs)
14640 DumpableObject *preDataBound = boundaryObjs + 0;
14641 DumpableObject *postDataBound = boundaryObjs + 1;
14644 for (i = 0; i < numObjs; i++)
14646 DumpableObject *dobj = dobjs[i];
14649 * The classification of object types here must match the SECTION_xxx
14650 * values assigned during subsequent ArchiveEntry calls!
14652 switch (dobj->objType)
14657 case DO_SHELL_TYPE:
14664 case DO_CONVERSION:
14669 case DO_DUMMY_TYPE:
14672 case DO_TSTEMPLATE:
14675 case DO_FOREIGN_SERVER:
14677 /* Pre-data objects: must come before the pre-data boundary */
14678 addObjectDependency(preDataBound, dobj->dumpId);
14680 case DO_TABLE_DATA:
14682 /* Data objects: must come between the boundaries */
14683 addObjectDependency(dobj, preDataBound->dumpId);
14684 addObjectDependency(postDataBound, dobj->dumpId);
14687 case DO_REFRESH_MATVIEW:
14689 case DO_EVENT_TRIGGER:
14690 case DO_DEFAULT_ACL:
14691 /* Post-data objects: must come after the post-data boundary */
14692 addObjectDependency(dobj, postDataBound->dumpId);
14695 /* Rules are post-data, but only if dumped separately */
14696 if (((RuleInfo *) dobj)->separate)
14697 addObjectDependency(dobj, postDataBound->dumpId);
14699 case DO_CONSTRAINT:
14700 case DO_FK_CONSTRAINT:
14701 /* Constraints are post-data, but only if dumped separately */
14702 if (((ConstraintInfo *) dobj)->separate)
14703 addObjectDependency(dobj, postDataBound->dumpId);
14705 case DO_PRE_DATA_BOUNDARY:
14706 /* nothing to do */
14708 case DO_POST_DATA_BOUNDARY:
14709 /* must come after the pre-data boundary */
14710 addObjectDependency(dobj, preDataBound->dumpId);
14718 * BuildArchiveDependencies - create dependency data for archive TOC entries
14720 * The raw dependency data obtained by getDependencies() is not terribly
14721 * useful in an archive dump, because in many cases there are dependency
14722 * chains linking through objects that don't appear explicitly in the dump.
14723 * For example, a view will depend on its _RETURN rule while the _RETURN rule
14724 * will depend on other objects --- but the rule will not appear as a separate
14725 * object in the dump. We need to adjust the view's dependencies to include
14726 * whatever the rule depends on that is included in the dump.
14728 * Just to make things more complicated, there are also "special" dependencies
14729 * such as the dependency of a TABLE DATA item on its TABLE, which we must
14730 * not rearrange because pg_restore knows that TABLE DATA only depends on
14731 * its table. In these cases we must leave the dependencies strictly as-is
14732 * even if they refer to not-to-be-dumped objects.
14734 * To handle this, the convention is that "special" dependencies are created
14735 * during ArchiveEntry calls, and an archive TOC item that has any such
14736 * entries will not be touched here. Otherwise, we recursively search the
14737 * DumpableObject data structures to build the correct dependencies for each
14738 * archive TOC item.
14741 BuildArchiveDependencies(Archive *fout)
14743 ArchiveHandle *AH = (ArchiveHandle *) fout;
14746 /* Scan all TOC entries in the archive */
14747 for (te = AH->toc->next; te != AH->toc; te = te->next)
14749 DumpableObject *dobj;
14750 DumpId *dependencies;
14754 /* No need to process entries that will not be dumped */
14757 /* Ignore entries that already have "special" dependencies */
14760 /* Otherwise, look up the item's original DumpableObject, if any */
14761 dobj = findObjectByDumpId(te->dumpId);
14764 /* No work if it has no dependencies */
14765 if (dobj->nDeps <= 0)
14767 /* Set up work array */
14769 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14771 /* Recursively find all dumpable dependencies */
14772 findDumpableDependencies(AH, dobj,
14773 &dependencies, &nDeps, &allocDeps);
14774 /* And save 'em ... */
14777 dependencies = (DumpId *) pg_realloc(dependencies,
14778 nDeps * sizeof(DumpId));
14779 te->dependencies = dependencies;
14783 free(dependencies);
14787 /* Recursive search subroutine for BuildArchiveDependencies */
14789 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14790 DumpId **dependencies, int *nDeps, int *allocDeps)
14795 * Ignore section boundary objects: if we search through them, we'll
14796 * report lots of bogus dependencies.
14798 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
14799 dobj->objType == DO_POST_DATA_BOUNDARY)
14802 for (i = 0; i < dobj->nDeps; i++)
14804 DumpId depid = dobj->dependencies[i];
14806 if (TocIDRequired(AH, depid) != 0)
14808 /* Object will be dumped, so just reference it as a dependency */
14809 if (*nDeps >= *allocDeps)
14812 *dependencies = (DumpId *) pg_realloc(*dependencies,
14813 *allocDeps * sizeof(DumpId));
14815 (*dependencies)[*nDeps] = depid;
14821 * Object will not be dumped, so recursively consider its deps.
14822 * We rely on the assumption that sortDumpableObjects already
14823 * broke any dependency loops, else we might recurse infinitely.
14825 DumpableObject *otherdobj = findObjectByDumpId(depid);
14828 findDumpableDependencies(AH, otherdobj,
14829 dependencies, nDeps, allocDeps);
14836 * selectSourceSchema - make the specified schema the active search path
14837 * in the source database.
14839 * NB: pg_catalog is explicitly searched after the specified schema;
14840 * so user names are only qualified if they are cross-schema references,
14841 * and system names are only qualified if they conflict with a user name
14842 * in the current schema.
14844 * Whenever the selected schema is not pg_catalog, be careful to qualify
14845 * references to system catalogs and types in our emitted commands!
14848 selectSourceSchema(Archive *fout, const char *schemaName)
14850 static char *curSchemaName = NULL;
14853 /* Not relevant if fetching from pre-7.3 DB */
14854 if (fout->remoteVersion < 70300)
14856 /* Ignore null schema names */
14857 if (schemaName == NULL || *schemaName == '\0')
14859 /* Optimize away repeated selection of same schema */
14860 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14863 query = createPQExpBuffer();
14864 appendPQExpBuffer(query, "SET search_path = %s",
14865 fmtId(schemaName));
14866 if (strcmp(schemaName, "pg_catalog") != 0)
14867 appendPQExpBuffer(query, ", pg_catalog");
14869 ExecuteSqlStatement(fout, query->data);
14871 destroyPQExpBuffer(query);
14873 free(curSchemaName);
14874 curSchemaName = pg_strdup(schemaName);
14878 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14881 * NB: in 7.3 and up the result may depend on the currently-selected
14882 * schema; this is why we don't try to cache the names.
14885 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14893 if ((opts & zeroAsOpaque) != 0)
14894 return pg_strdup(g_opaque_type);
14895 else if ((opts & zeroAsAny) != 0)
14896 return pg_strdup("'any'");
14897 else if ((opts & zeroAsStar) != 0)
14898 return pg_strdup("*");
14899 else if ((opts & zeroAsNone) != 0)
14900 return pg_strdup("NONE");
14903 query = createPQExpBuffer();
14904 if (fout->remoteVersion >= 70300)
14906 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14909 else if (fout->remoteVersion >= 70100)
14911 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14916 appendPQExpBuffer(query, "SELECT typname "
14918 "WHERE oid = '%u'::oid",
14922 res = ExecuteSqlQueryForSingleRow(fout, query->data);
14924 if (fout->remoteVersion >= 70100)
14926 /* already quoted */
14927 result = pg_strdup(PQgetvalue(res, 0, 0));
14931 /* may need to quote it */
14932 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14936 destroyPQExpBuffer(query);
14942 * myFormatType --- local implementation of format_type for use with 7.0.
14945 myFormatType(const char *typname, int32 typmod)
14948 bool isarray = false;
14949 PQExpBuffer buf = createPQExpBuffer();
14951 /* Handle array types */
14952 if (typname[0] == '_')
14958 /* Show lengths on bpchar and varchar */
14959 if (strcmp(typname, "bpchar") == 0)
14961 int len = (typmod - VARHDRSZ);
14963 appendPQExpBuffer(buf, "character");
14965 appendPQExpBuffer(buf, "(%d)",
14966 typmod - VARHDRSZ);
14968 else if (strcmp(typname, "varchar") == 0)
14970 appendPQExpBuffer(buf, "character varying");
14972 appendPQExpBuffer(buf, "(%d)",
14973 typmod - VARHDRSZ);
14975 else if (strcmp(typname, "numeric") == 0)
14977 appendPQExpBuffer(buf, "numeric");
14984 tmp_typmod = typmod - VARHDRSZ;
14985 precision = (tmp_typmod >> 16) & 0xffff;
14986 scale = tmp_typmod & 0xffff;
14987 appendPQExpBuffer(buf, "(%d,%d)",
14993 * char is an internal single-byte data type; Let's make sure we force it
14994 * through with quotes. - thomas 1998-12-13
14996 else if (strcmp(typname, "char") == 0)
14997 appendPQExpBuffer(buf, "\"char\"");
14999 appendPQExpBuffer(buf, "%s", fmtId(typname));
15001 /* Append array qualifier for array types */
15003 appendPQExpBuffer(buf, "[]");
15005 result = pg_strdup(buf->data);
15006 destroyPQExpBuffer(buf);
15012 * fmtQualifiedId - convert a qualified name to the proper format for
15013 * the source database.
15015 * Like fmtId, use the result before calling again.
15017 static const char *
15018 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
15020 static PQExpBuffer id_return = NULL;
15022 if (id_return) /* first time through? */
15023 resetPQExpBuffer(id_return);
15025 id_return = createPQExpBuffer();
15027 /* Suppress schema name if fetching from pre-7.3 DB */
15028 if (fout->remoteVersion >= 70300 && schema && *schema)
15030 appendPQExpBuffer(id_return, "%s.",
15033 appendPQExpBuffer(id_return, "%s",
15036 return id_return->data;
15040 * Return a column list clause for the given relation.
15042 * Special case: if there are no undropped columns in the relation, return
15043 * "", not an invalid "()" column list.
15045 static const char *
15046 fmtCopyColumnList(const TableInfo *ti)
15048 static PQExpBuffer q = NULL;
15049 int numatts = ti->numatts;
15050 char **attnames = ti->attnames;
15051 bool *attisdropped = ti->attisdropped;
15055 if (q) /* first time through? */
15056 resetPQExpBuffer(q);
15058 q = createPQExpBuffer();
15060 appendPQExpBuffer(q, "(");
15062 for (i = 0; i < numatts; i++)
15064 if (attisdropped[i])
15067 appendPQExpBuffer(q, ", ");
15068 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
15073 return ""; /* no undropped columns */
15075 appendPQExpBuffer(q, ")");
15080 * Execute an SQL query and verify that we got exactly one row back.
15083 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
15088 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
15090 /* Expecting a single result only */
15091 ntups = PQntuples(res);
15093 exit_horribly(NULL,
15094 ngettext("query returned %d row instead of one: %s\n",
15095 "query returned %d rows instead of one: %s\n",