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 look at
18 * the currently committed state. So it is possible to get 'cache
19 * lookup failed' error if someone performs DDL changes while a dump is
20 * happening. The window for this sort of thing is from the acquisition
21 * of the transaction snapshot to getSchemaData() (when pg_dump acquires
22 * AccessShareLock on every table it intends to dump). It isn't very large,
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 "pg_backup_utils.h"
63 #include "dumputils.h"
73 const char *descr; /* comment for an object */
74 Oid classoid; /* object class (catalog OID) */
75 Oid objoid; /* object OID */
76 int objsubid; /* subobject (table column #) */
81 const char *provider; /* label provider of this security label */
82 const char *label; /* security label for an object */
83 Oid classoid; /* object class (catalog OID) */
84 Oid objoid; /* object OID */
85 int objsubid; /* subobject (table column #) */
89 bool g_verbose; /* User wants verbose narration of our
92 /* various user-settable parameters */
95 int dumpSections; /* bitmask of chosen sections */
97 const char *lockWaitTimeout;
99 /* subquery used to convert user ID (eg, datdba) to user name */
100 static const char *username_subquery;
102 /* obsolete as of 7.3: */
103 static Oid g_last_builtin_oid; /* value of the last builtin oid */
106 * Object inclusion/exclusion lists
108 * The string lists record the patterns given by command-line switches,
109 * which we then convert to lists of OIDs of matching objects.
111 static SimpleStringList schema_include_patterns = {NULL, NULL};
112 static SimpleOidList schema_include_oids = {NULL, NULL};
113 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
114 static SimpleOidList schema_exclude_oids = {NULL, NULL};
116 static SimpleStringList table_include_patterns = {NULL, NULL};
117 static SimpleOidList table_include_oids = {NULL, NULL};
118 static SimpleStringList table_exclude_patterns = {NULL, NULL};
119 static SimpleOidList table_exclude_oids = {NULL, NULL};
120 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
121 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
123 /* default, if no "inclusion" switches appear, is to dump everything */
124 static bool include_everything = true;
126 char g_opaque_type[10]; /* name for the opaque type */
128 /* placeholders for the delimiters for comments */
129 char g_comment_start[10];
130 char g_comment_end[10];
132 static const CatalogId nilCatalogId = {0, 0};
134 /* flags for various command-line long options */
135 static int binary_upgrade = 0;
136 static int disable_dollar_quoting = 0;
137 static int dump_inserts = 0;
138 static int column_inserts = 0;
139 static int no_security_labels = 0;
140 static int no_synchronized_snapshots = 0;
141 static int no_unlogged_table_data = 0;
142 static int serializable_deferrable = 0;
145 static void help(const char *progname);
146 static void setup_connection(Archive *AH, const char *dumpencoding,
148 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
149 static void expand_schema_name_patterns(Archive *fout,
150 SimpleStringList *patterns,
151 SimpleOidList *oids);
152 static void expand_table_name_patterns(Archive *fout,
153 SimpleStringList *patterns,
154 SimpleOidList *oids);
155 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
156 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
157 static void refreshMatViewData(Archive *fout, TableDataInfo *tdinfo);
158 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
159 static void dumpComment(Archive *fout, const char *target,
160 const char *namespace, const char *owner,
161 CatalogId catalogId, int subid, DumpId dumpId);
162 static int findComments(Archive *fout, Oid classoid, Oid objoid,
163 CommentItem **items);
164 static int collectComments(Archive *fout, CommentItem **items);
165 static void dumpSecLabel(Archive *fout, const char *target,
166 const char *namespace, const char *owner,
167 CatalogId catalogId, int subid, DumpId dumpId);
168 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
169 SecLabelItem **items);
170 static int collectSecLabels(Archive *fout, SecLabelItem **items);
171 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
172 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
173 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
174 static void dumpType(Archive *fout, TypeInfo *tyinfo);
175 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
179 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
181 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
182 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
183 static void dumpFunc(Archive *fout, FuncInfo *finfo);
184 static void dumpCast(Archive *fout, CastInfo *cast);
185 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
186 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
187 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
188 static void dumpCollation(Archive *fout, CollInfo *convinfo);
189 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
190 static void dumpRule(Archive *fout, RuleInfo *rinfo);
191 static void dumpAgg(Archive *fout, AggInfo *agginfo);
192 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
193 static void dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo);
194 static void dumpTable(Archive *fout, TableInfo *tbinfo);
195 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
196 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
197 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
198 static void dumpSequenceData(Archive *fout, TableDataInfo *tdinfo);
199 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
200 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
201 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
202 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
203 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
204 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
205 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
206 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
207 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
208 static void dumpUserMappings(Archive *fout,
209 const char *servername, const char *namespace,
210 const char *owner, CatalogId catalogId, DumpId dumpId);
211 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
213 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
214 const char *type, const char *name, const char *subname,
215 const char *tag, const char *nspname, const char *owner,
218 static void getDependencies(Archive *fout);
219 static void BuildArchiveDependencies(Archive *fout);
220 static void findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
221 DumpId **dependencies, int *nDeps, int *allocDeps);
223 static DumpableObject *createBoundaryObjects(void);
224 static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
225 DumpableObject *boundaryObjs);
227 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
228 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
229 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
230 static void buildMatViewRefreshDependencies(Archive *fout);
231 static void getTableDataFKConstraints(void);
232 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
233 static char *format_function_arguments_old(Archive *fout,
234 FuncInfo *finfo, int nallargs,
238 static char *format_function_signature(Archive *fout,
239 FuncInfo *finfo, bool honor_quotes);
240 static const char *convertRegProcReference(Archive *fout,
242 static const char *convertOperatorReference(Archive *fout, const char *opr);
243 static const char *convertTSFunction(Archive *fout, Oid funcOid);
244 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
245 static Oid findLastBuiltinOid_V70(Archive *fout);
246 static void selectSourceSchema(Archive *fout, const char *schemaName);
247 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
248 static char *myFormatType(const char *typname, int32 typmod);
249 static void getBlobs(Archive *fout);
250 static void dumpBlob(Archive *fout, BlobInfo *binfo);
251 static int dumpBlobs(Archive *fout, void *arg);
252 static void dumpDatabase(Archive *AH);
253 static void dumpEncoding(Archive *AH);
254 static void dumpStdStrings(Archive *AH);
255 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
256 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
257 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
258 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
259 static void binary_upgrade_set_pg_class_oids(Archive *fout,
260 PQExpBuffer upgrade_buffer,
261 Oid pg_class_oid, bool is_index);
262 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
263 DumpableObject *dobj,
264 const char *objlabel);
265 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
266 static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
267 static char *get_synchronized_snapshot(Archive *fout);
268 static PGresult *ExecuteSqlQueryForSingleRow(Archive *fout, char *query);
269 static void setupDumpWorker(Archive *AHX, RestoreOptions *ropt);
273 main(int argc, char **argv)
276 const char *filename = NULL;
277 const char *format = "p";
278 const char *dbname = NULL;
279 const char *pghost = NULL;
280 const char *pgport = NULL;
281 const char *username = NULL;
282 const char *dumpencoding = NULL;
286 DumpableObject **dobjs;
288 DumpableObject *boundaryObjs;
291 enum trivalue prompt_password = TRI_DEFAULT;
292 int compressLevel = -1;
295 int outputCreateDB = 0;
296 bool outputBlobs = false;
297 int outputNoOwner = 0;
298 char *outputSuperuser = NULL;
299 char *use_role = NULL;
301 RestoreOptions *ropt;
302 ArchiveFormat archiveFormat = archUnknown;
303 ArchiveMode archiveMode;
304 Archive *fout; /* the script file */
306 static int disable_triggers = 0;
307 static int outputNoTablespaces = 0;
308 static int use_setsessauth = 0;
310 static struct option long_options[] = {
311 {"data-only", no_argument, NULL, 'a'},
312 {"blobs", no_argument, NULL, 'b'},
313 {"clean", no_argument, NULL, 'c'},
314 {"create", no_argument, NULL, 'C'},
315 {"dbname", required_argument, NULL, 'd'},
316 {"file", required_argument, NULL, 'f'},
317 {"format", required_argument, NULL, 'F'},
318 {"host", required_argument, NULL, 'h'},
319 {"ignore-version", no_argument, NULL, 'i'},
320 {"jobs", 1, NULL, 'j'},
321 {"no-reconnect", no_argument, NULL, 'R'},
322 {"oids", no_argument, NULL, 'o'},
323 {"no-owner", no_argument, NULL, 'O'},
324 {"port", required_argument, NULL, 'p'},
325 {"schema", required_argument, NULL, 'n'},
326 {"exclude-schema", required_argument, NULL, 'N'},
327 {"schema-only", no_argument, NULL, 's'},
328 {"superuser", required_argument, NULL, 'S'},
329 {"table", required_argument, NULL, 't'},
330 {"exclude-table", required_argument, NULL, 'T'},
331 {"no-password", no_argument, NULL, 'w'},
332 {"password", no_argument, NULL, 'W'},
333 {"username", required_argument, NULL, 'U'},
334 {"verbose", no_argument, NULL, 'v'},
335 {"no-privileges", no_argument, NULL, 'x'},
336 {"no-acl", no_argument, NULL, 'x'},
337 {"compress", required_argument, NULL, 'Z'},
338 {"encoding", required_argument, NULL, 'E'},
339 {"help", no_argument, NULL, '?'},
340 {"version", no_argument, NULL, 'V'},
343 * the following options don't have an equivalent short option letter
345 {"attribute-inserts", no_argument, &column_inserts, 1},
346 {"binary-upgrade", no_argument, &binary_upgrade, 1},
347 {"column-inserts", no_argument, &column_inserts, 1},
348 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
349 {"disable-triggers", no_argument, &disable_triggers, 1},
350 {"exclude-table-data", required_argument, NULL, 4},
351 {"inserts", no_argument, &dump_inserts, 1},
352 {"lock-wait-timeout", required_argument, NULL, 2},
353 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
354 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
355 {"role", required_argument, NULL, 3},
356 {"section", required_argument, NULL, 5},
357 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
358 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
359 {"no-security-labels", no_argument, &no_security_labels, 1},
360 {"no-synchronized-snapshots", no_argument, &no_synchronized_snapshots, 1},
361 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
366 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
369 * Initialize what we need for parallel execution, especially for thread
370 * support on Windows.
372 init_parallel_dump_utils();
376 strcpy(g_comment_start, "-- ");
377 g_comment_end[0] = '\0';
378 strcpy(g_opaque_type, "opaque");
380 dataOnly = schemaOnly = false;
381 dumpSections = DUMP_UNSECTIONED;
382 lockWaitTimeout = NULL;
384 progname = get_progname(argv[0]);
386 /* Set default options based on progname */
387 if (strcmp(progname, "pg_backup") == 0)
392 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
397 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
399 puts("pg_dump (PostgreSQL) " PG_VERSION);
404 while ((c = getopt_long(argc, argv, "abcCd:E:f:F:h:ij:K:n:N:oOp:RsS:t:T:U:vwWxZ:",
405 long_options, &optindex)) != -1)
409 case 'a': /* Dump data only */
413 case 'b': /* Dump blobs */
417 case 'c': /* clean (i.e., drop) schema prior to create */
421 case 'C': /* Create DB */
425 case 'd': /* database name */
426 dbname = pg_strdup(optarg);
429 case 'E': /* Dump encoding */
430 dumpencoding = pg_strdup(optarg);
434 filename = pg_strdup(optarg);
438 format = pg_strdup(optarg);
441 case 'h': /* server host */
442 pghost = pg_strdup(optarg);
446 /* ignored, deprecated option */
449 case 'j': /* number of dump jobs */
450 numWorkers = atoi(optarg);
453 case 'n': /* include schema(s) */
454 simple_string_list_append(&schema_include_patterns, optarg);
455 include_everything = false;
458 case 'N': /* exclude schema(s) */
459 simple_string_list_append(&schema_exclude_patterns, optarg);
462 case 'o': /* Dump oids */
466 case 'O': /* Don't reconnect to match owner */
470 case 'p': /* server port */
471 pgport = pg_strdup(optarg);
475 /* no-op, still accepted for backwards compatibility */
478 case 's': /* dump schema only */
482 case 'S': /* Username for superuser in plain text output */
483 outputSuperuser = pg_strdup(optarg);
486 case 't': /* include table(s) */
487 simple_string_list_append(&table_include_patterns, optarg);
488 include_everything = false;
491 case 'T': /* exclude table(s) */
492 simple_string_list_append(&table_exclude_patterns, optarg);
496 username = pg_strdup(optarg);
499 case 'v': /* verbose */
504 prompt_password = TRI_NO;
508 prompt_password = TRI_YES;
511 case 'x': /* skip ACL dump */
515 case 'Z': /* Compression Level */
516 compressLevel = atoi(optarg);
520 /* This covers the long options. */
523 case 2: /* lock-wait-timeout */
524 lockWaitTimeout = pg_strdup(optarg);
527 case 3: /* SET ROLE */
528 use_role = pg_strdup(optarg);
531 case 4: /* exclude table(s) data */
532 simple_string_list_append(&tabledata_exclude_patterns, optarg);
535 case 5: /* section */
536 set_dump_section(optarg, &dumpSections);
540 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
546 * Non-option argument specifies database name as long as it wasn't
547 * already specified with -d / --dbname
549 if (optind < argc && dbname == NULL)
550 dbname = argv[optind++];
552 /* Complain if any arguments remain */
555 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
556 progname, argv[optind]);
557 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
562 /* --column-inserts implies --inserts */
566 if (dataOnly && schemaOnly)
567 exit_horribly(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
569 if (dataOnly && outputClean)
570 exit_horribly(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
572 if (dump_inserts && oids)
574 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
575 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
579 /* Identify archive format to emit */
580 archiveFormat = parseArchiveFormat(format, &archiveMode);
582 /* archiveFormat specific setup */
583 if (archiveFormat == archNull)
586 /* Custom and directory formats are compressed by default, others not */
587 if (compressLevel == -1)
589 if (archiveFormat == archCustom || archiveFormat == archDirectory)
590 compressLevel = Z_DEFAULT_COMPRESSION;
596 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
597 * parallel jobs because that's the maximum limit for the
598 * WaitForMultipleObjects() call.
602 || numWorkers > MAXIMUM_WAIT_OBJECTS
605 exit_horribly(NULL, "%s: invalid number of parallel jobs\n", progname);
607 /* Parallel backup only in the directory archive format so far */
608 if (archiveFormat != archDirectory && numWorkers > 1)
609 exit_horribly(NULL, "parallel backup only supported by the directory format\n");
611 /* Open the output file */
612 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode,
615 /* Register the cleanup hook */
616 on_exit_close_archive(fout);
619 exit_horribly(NULL, "could not open output file \"%s\" for writing\n", filename);
621 /* Let the archiver know how noisy to be */
622 fout->verbose = g_verbose;
625 * We allow the server to be back to 7.0, and up to any minor release of
626 * our own major version. (See also version check in pg_dumpall.c.)
628 fout->minRemoteVersion = 70000;
629 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
631 fout->numWorkers = numWorkers;
634 * Open the database using the Archiver, so it knows about it. Errors mean
637 ConnectDatabase(fout, dbname, pghost, pgport, username, prompt_password);
638 setup_connection(fout, dumpencoding, use_role);
641 * Disable security label support if server version < v9.1.x (prevents
642 * access to nonexistent pg_seclabel catalog)
644 if (fout->remoteVersion < 90100)
645 no_security_labels = 1;
648 * When running against 9.0 or later, check if we are in recovery mode,
649 * which means we are on a hot standby.
651 if (fout->remoteVersion >= 90000)
653 PGresult *res = ExecuteSqlQueryForSingleRow(fout, "SELECT pg_catalog.pg_is_in_recovery()");
655 if (strcmp(PQgetvalue(res, 0, 0), "t") == 0)
658 * On hot standby slaves, never try to dump unlogged table data,
659 * since it will just throw an error.
661 no_unlogged_table_data = true;
666 /* Select the appropriate subquery to convert user IDs to names */
667 if (fout->remoteVersion >= 80100)
668 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
669 else if (fout->remoteVersion >= 70300)
670 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
672 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
674 /* check the version for the synchronized snapshots feature */
675 if (numWorkers > 1 && fout->remoteVersion < 90200
676 && !no_synchronized_snapshots)
678 "Synchronized snapshots are not supported by this server version.\n"
679 "Run with --no-synchronized-snapshots instead if you do not need\n"
680 "synchronized snapshots.\n");
682 /* Find the last built-in OID, if needed */
683 if (fout->remoteVersion < 70300)
685 if (fout->remoteVersion >= 70100)
686 g_last_builtin_oid = findLastBuiltinOid_V71(fout,
687 PQdb(GetConnection(fout)));
689 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
691 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
694 /* Expand schema selection patterns into OID lists */
695 if (schema_include_patterns.head != NULL)
697 expand_schema_name_patterns(fout, &schema_include_patterns,
698 &schema_include_oids);
699 if (schema_include_oids.head == NULL)
700 exit_horribly(NULL, "No matching schemas were found\n");
702 expand_schema_name_patterns(fout, &schema_exclude_patterns,
703 &schema_exclude_oids);
704 /* non-matching exclusion patterns aren't an error */
706 /* Expand table selection patterns into OID lists */
707 if (table_include_patterns.head != NULL)
709 expand_table_name_patterns(fout, &table_include_patterns,
710 &table_include_oids);
711 if (table_include_oids.head == NULL)
712 exit_horribly(NULL, "No matching tables were found\n");
714 expand_table_name_patterns(fout, &table_exclude_patterns,
715 &table_exclude_oids);
717 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
718 &tabledata_exclude_oids);
720 /* non-matching exclusion patterns aren't an error */
723 * Dumping blobs is now default unless we saw an inclusion switch or -s
724 * ... but even if we did see one of these, -b turns it back on.
726 if (include_everything && !schemaOnly)
730 * Now scan the database and create DumpableObject structs for all the
731 * objects we intend to dump.
733 tblinfo = getSchemaData(fout, &numTables);
735 if (fout->remoteVersion < 80400)
736 guessConstraintInheritance(tblinfo, numTables);
740 getTableData(tblinfo, numTables, oids);
741 buildMatViewRefreshDependencies(fout);
743 getTableDataFKConstraints();
750 * Collect dependency data to assist in ordering the objects.
752 getDependencies(fout);
754 /* Lastly, create dummy objects to represent the section boundaries */
755 boundaryObjs = createBoundaryObjects();
757 /* Get pointers to all the known DumpableObjects */
758 getDumpableObjects(&dobjs, &numObjs);
761 * Add dummy dependencies to enforce the dump section ordering.
763 addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
766 * Sort the objects into a safe dump order (no forward references).
768 * In 7.3 or later, we can rely on dependency information to help us
769 * determine a safe order, so the initial sort is mostly for cosmetic
770 * purposes: we sort by name to ensure that logically identical schemas
771 * will dump identically. Before 7.3 we don't have dependencies and we
772 * use OID ordering as an (unreliable) guide to creation order.
774 if (fout->remoteVersion >= 70300)
775 sortDumpableObjectsByTypeName(dobjs, numObjs);
777 sortDumpableObjectsByTypeOid(dobjs, numObjs);
779 /* If we do a parallel dump, we want the largest tables to go first */
780 if (archiveFormat == archDirectory && numWorkers > 1)
781 sortDataAndIndexObjectsBySize(dobjs, numObjs);
783 sortDumpableObjects(dobjs, numObjs,
784 boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
787 * Create archive TOC entries for all the objects to be dumped, in a safe
791 /* First the special ENCODING and STDSTRINGS entries. */
793 dumpStdStrings(fout);
795 /* The database item is always next, unless we don't want it at all */
796 if (include_everything && !dataOnly)
799 /* Now the rearrangeable objects. */
800 for (i = 0; i < numObjs; i++)
801 dumpDumpableObject(fout, dobjs[i]);
804 * Set up options info to ensure we dump what we want.
806 ropt = NewRestoreOptions();
807 ropt->filename = filename;
808 ropt->dropSchema = outputClean;
809 ropt->dataOnly = dataOnly;
810 ropt->schemaOnly = schemaOnly;
811 ropt->dumpSections = dumpSections;
812 ropt->aclsSkip = aclsSkip;
813 ropt->superuser = outputSuperuser;
814 ropt->createDB = outputCreateDB;
815 ropt->noOwner = outputNoOwner;
816 ropt->noTablespace = outputNoTablespaces;
817 ropt->disable_triggers = disable_triggers;
818 ropt->use_setsessauth = use_setsessauth;
820 if (compressLevel == -1)
821 ropt->compression = 0;
823 ropt->compression = compressLevel;
825 ropt->suppressDumpWarnings = true; /* We've already shown them */
827 SetArchiveRestoreOptions(fout, ropt);
830 * The archive's TOC entries are now marked as to which ones will actually
831 * be output, so we can set up their dependency lists properly. This isn't
832 * necessary for plain-text output, though.
835 BuildArchiveDependencies(fout);
838 * And finally we can do the actual output.
840 * Note: for non-plain-text output formats, the output file is written
841 * inside CloseArchive(). This is, um, bizarre; but not worth changing
845 RestoreArchive(fout);
854 help(const char *progname)
856 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
857 printf(_("Usage:\n"));
858 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
860 printf(_("\nGeneral options:\n"));
861 printf(_(" -f, --file=FILENAME output file or directory name\n"));
862 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
863 " plain text (default))\n"));
864 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
865 printf(_(" -v, --verbose verbose mode\n"));
866 printf(_(" -V, --version output version information, then exit\n"));
867 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
868 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
869 printf(_(" -?, --help show this help, then exit\n"));
871 printf(_("\nOptions controlling the output content:\n"));
872 printf(_(" -a, --data-only dump only the data, not the schema\n"));
873 printf(_(" -b, --blobs include large objects in dump\n"));
874 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
875 printf(_(" -C, --create include commands to create database in dump\n"));
876 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
877 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
878 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
879 printf(_(" -o, --oids include OIDs in dump\n"));
880 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
881 " plain-text format\n"));
882 printf(_(" -s, --schema-only dump only the schema, no data\n"));
883 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
884 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
885 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
886 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
887 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
888 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
889 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
890 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
891 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
892 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
893 printf(_(" --no-security-labels do not dump security label assignments\n"));
894 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
895 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
896 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
897 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
898 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
899 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
900 printf(_(" --use-set-session-authorization\n"
901 " use SET SESSION AUTHORIZATION commands instead of\n"
902 " ALTER OWNER commands to set ownership\n"));
904 printf(_("\nConnection options:\n"));
905 printf(_(" -d, --dbname=DBNAME database to dump\n"));
906 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
907 printf(_(" -p, --port=PORT database server port number\n"));
908 printf(_(" -U, --username=NAME connect as specified database user\n"));
909 printf(_(" -w, --no-password never prompt for password\n"));
910 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
911 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
913 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
914 "variable value is used.\n\n"));
915 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
919 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
921 PGconn *conn = GetConnection(AH);
922 const char *std_strings;
925 * Set the client encoding if requested. If dumpencoding == NULL then
926 * either it hasn't been requested or we're a cloned connection and then
927 * this has already been set in CloneArchive according to the original
928 * connection encoding.
932 if (PQsetClientEncoding(conn, dumpencoding) < 0)
933 exit_horribly(NULL, "invalid client encoding \"%s\" specified\n",
938 * Get the active encoding and the standard_conforming_strings setting, so
939 * we know how to escape strings.
941 AH->encoding = PQclientEncoding(conn);
943 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
944 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
946 /* Set the role if requested */
947 if (!use_role && AH->use_role)
948 use_role = AH->use_role;
950 /* Set the role if requested */
951 if (use_role && AH->remoteVersion >= 80100)
953 PQExpBuffer query = createPQExpBuffer();
955 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
956 ExecuteSqlStatement(AH, query->data);
957 destroyPQExpBuffer(query);
959 /* save this for later use on parallel connections */
961 AH->use_role = strdup(use_role);
964 /* Set the datestyle to ISO to ensure the dump's portability */
965 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
967 /* Likewise, avoid using sql_standard intervalstyle */
968 if (AH->remoteVersion >= 80400)
969 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
972 * If supported, set extra_float_digits so that we can dump float data
973 * exactly (given correctly implemented float I/O code, anyway)
975 if (AH->remoteVersion >= 90000)
976 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
977 else if (AH->remoteVersion >= 70400)
978 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
981 * If synchronized scanning is supported, disable it, to prevent
982 * unpredictable changes in row ordering across a dump and reload.
984 if (AH->remoteVersion >= 80300)
985 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
988 * Disable timeouts if supported.
990 if (AH->remoteVersion >= 70300)
991 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
992 if (AH->remoteVersion >= 90300)
993 ExecuteSqlStatement(AH, "SET lock_timeout = 0");
996 * Quote all identifiers, if requested.
998 if (quote_all_identifiers && AH->remoteVersion >= 90100)
999 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1002 * Start transaction-snapshot mode transaction to dump consistent data.
1004 ExecuteSqlStatement(AH, "BEGIN");
1005 if (AH->remoteVersion >= 90100)
1007 if (serializable_deferrable)
1008 ExecuteSqlStatement(AH,
1009 "SET TRANSACTION ISOLATION LEVEL "
1010 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1012 ExecuteSqlStatement(AH,
1013 "SET TRANSACTION ISOLATION LEVEL "
1014 "REPEATABLE READ, READ ONLY");
1016 else if (AH->remoteVersion >= 70400)
1018 /* note: comma was not accepted in SET TRANSACTION before 8.0 */
1019 ExecuteSqlStatement(AH,
1020 "SET TRANSACTION ISOLATION LEVEL "
1021 "SERIALIZABLE READ ONLY");
1024 ExecuteSqlStatement(AH,
1025 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
1029 if (AH->numWorkers > 1 && AH->remoteVersion >= 90200 && !no_synchronized_snapshots)
1031 if (AH->sync_snapshot_id)
1033 PQExpBuffer query = createPQExpBuffer();
1035 appendPQExpBuffer(query, "SET TRANSACTION SNAPSHOT ");
1036 appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1037 ExecuteSqlStatement(AH, query->data);
1038 destroyPQExpBuffer(query);
1041 AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1046 setupDumpWorker(Archive *AHX, RestoreOptions *ropt)
1048 setup_connection(AHX, NULL, NULL);
1052 get_synchronized_snapshot(Archive *fout)
1054 char *query = "SELECT pg_export_snapshot()";
1058 res = ExecuteSqlQueryForSingleRow(fout, query);
1059 result = strdup(PQgetvalue(res, 0, 0));
1065 static ArchiveFormat
1066 parseArchiveFormat(const char *format, ArchiveMode *mode)
1068 ArchiveFormat archiveFormat;
1070 *mode = archModeWrite;
1072 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1074 /* This is used by pg_dumpall, and is not documented */
1075 archiveFormat = archNull;
1076 *mode = archModeAppend;
1078 else if (pg_strcasecmp(format, "c") == 0)
1079 archiveFormat = archCustom;
1080 else if (pg_strcasecmp(format, "custom") == 0)
1081 archiveFormat = archCustom;
1082 else if (pg_strcasecmp(format, "d") == 0)
1083 archiveFormat = archDirectory;
1084 else if (pg_strcasecmp(format, "directory") == 0)
1085 archiveFormat = archDirectory;
1086 else if (pg_strcasecmp(format, "p") == 0)
1087 archiveFormat = archNull;
1088 else if (pg_strcasecmp(format, "plain") == 0)
1089 archiveFormat = archNull;
1090 else if (pg_strcasecmp(format, "t") == 0)
1091 archiveFormat = archTar;
1092 else if (pg_strcasecmp(format, "tar") == 0)
1093 archiveFormat = archTar;
1095 exit_horribly(NULL, "invalid output format \"%s\" specified\n", format);
1096 return archiveFormat;
1100 * Find the OIDs of all schemas matching the given list of patterns,
1101 * and append them to the given OID list.
1104 expand_schema_name_patterns(Archive *fout,
1105 SimpleStringList *patterns,
1106 SimpleOidList *oids)
1110 SimpleStringListCell *cell;
1113 if (patterns->head == NULL)
1114 return; /* nothing to do */
1116 if (fout->remoteVersion < 70300)
1117 exit_horribly(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1119 query = createPQExpBuffer();
1122 * We use UNION ALL rather than UNION; this might sometimes result in
1123 * duplicate entries in the OID list, but we don't care.
1126 for (cell = patterns->head; cell; cell = cell->next)
1128 if (cell != patterns->head)
1129 appendPQExpBuffer(query, "UNION ALL\n");
1130 appendPQExpBuffer(query,
1131 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1132 processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1133 false, NULL, "n.nspname", NULL, NULL);
1136 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1138 for (i = 0; i < PQntuples(res); i++)
1140 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1144 destroyPQExpBuffer(query);
1148 * Find the OIDs of all tables matching the given list of patterns,
1149 * and append them to the given OID list.
1152 expand_table_name_patterns(Archive *fout,
1153 SimpleStringList *patterns, SimpleOidList *oids)
1157 SimpleStringListCell *cell;
1160 if (patterns->head == NULL)
1161 return; /* nothing to do */
1163 query = createPQExpBuffer();
1166 * We use UNION ALL rather than UNION; this might sometimes result in
1167 * duplicate entries in the OID list, but we don't care.
1170 for (cell = patterns->head; cell; cell = cell->next)
1172 if (cell != patterns->head)
1173 appendPQExpBuffer(query, "UNION ALL\n");
1174 appendPQExpBuffer(query,
1176 "\nFROM pg_catalog.pg_class c"
1177 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1178 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c', '%c')\n",
1179 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1180 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
1181 processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1182 false, "n.nspname", "c.relname", NULL,
1183 "pg_catalog.pg_table_is_visible(c.oid)");
1186 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1188 for (i = 0; i < PQntuples(res); i++)
1190 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1194 destroyPQExpBuffer(query);
1198 * selectDumpableNamespace: policy-setting subroutine
1199 * Mark a namespace as to be dumped or not
1202 selectDumpableNamespace(NamespaceInfo *nsinfo)
1205 * If specific tables are being dumped, do not dump any complete
1206 * namespaces. If specific namespaces are being dumped, dump just those
1207 * namespaces. Otherwise, dump all non-system namespaces.
1209 if (table_include_oids.head != NULL)
1210 nsinfo->dobj.dump = false;
1211 else if (schema_include_oids.head != NULL)
1212 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1213 nsinfo->dobj.catId.oid);
1214 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1215 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1216 nsinfo->dobj.dump = false;
1218 nsinfo->dobj.dump = true;
1221 * In any case, a namespace can be excluded by an exclusion switch
1223 if (nsinfo->dobj.dump &&
1224 simple_oid_list_member(&schema_exclude_oids,
1225 nsinfo->dobj.catId.oid))
1226 nsinfo->dobj.dump = false;
1230 * selectDumpableTable: policy-setting subroutine
1231 * Mark a table as to be dumped or not
1234 selectDumpableTable(TableInfo *tbinfo)
1237 * If specific tables are being dumped, dump just those tables; else, dump
1238 * according to the parent namespace's dump flag.
1240 if (table_include_oids.head != NULL)
1241 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1242 tbinfo->dobj.catId.oid);
1244 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1247 * In any case, a table can be excluded by an exclusion switch
1249 if (tbinfo->dobj.dump &&
1250 simple_oid_list_member(&table_exclude_oids,
1251 tbinfo->dobj.catId.oid))
1252 tbinfo->dobj.dump = false;
1256 * selectDumpableType: policy-setting subroutine
1257 * Mark a type as to be dumped or not
1259 * If it's a table's rowtype or an autogenerated array type, we also apply a
1260 * special type code to facilitate sorting into the desired order. (We don't
1261 * want to consider those to be ordinary types because that would bring tables
1262 * up into the datatype part of the dump order.) We still set the object's
1263 * dump flag; that's not going to cause the dummy type to be dumped, but we
1264 * need it so that casts involving such types will be dumped correctly -- see
1265 * dumpCast. This means the flag should be set the same as for the underlying
1266 * object (the table or base type).
1269 selectDumpableType(TypeInfo *tyinfo)
1271 /* skip complex types, except for standalone composite types */
1272 if (OidIsValid(tyinfo->typrelid) &&
1273 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1275 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1277 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1278 if (tytable != NULL)
1279 tyinfo->dobj.dump = tytable->dobj.dump;
1281 tyinfo->dobj.dump = false;
1285 /* skip auto-generated array types */
1286 if (tyinfo->isArray)
1288 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1291 * Fall through to set the dump flag; we assume that the subsequent
1292 * rules will do the same thing as they would for the array's base
1293 * type. (We cannot reliably look up the base type here, since
1294 * getTypes may not have processed it yet.)
1298 /* dump only types in dumpable namespaces */
1299 if (!tyinfo->dobj.namespace->dobj.dump)
1300 tyinfo->dobj.dump = false;
1302 /* skip undefined placeholder types */
1303 else if (!tyinfo->isDefined)
1304 tyinfo->dobj.dump = false;
1307 tyinfo->dobj.dump = true;
1311 * selectDumpableDefaultACL: policy-setting subroutine
1312 * Mark a default ACL as to be dumped or not
1314 * For per-schema default ACLs, dump if the schema is to be dumped.
1315 * Otherwise dump if we are dumping "everything". Note that dataOnly
1316 * and aclsSkip are checked separately.
1319 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1321 if (dinfo->dobj.namespace)
1322 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1324 dinfo->dobj.dump = include_everything;
1328 * selectDumpableExtension: policy-setting subroutine
1329 * Mark an extension as to be dumped or not
1331 * Normally, we dump all extensions, or none of them if include_everything
1332 * is false (i.e., a --schema or --table switch was given). However, in
1333 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1334 * assume those will already be installed in the target database. We identify
1335 * such extensions by their having OIDs in the range reserved for initdb.
1338 selectDumpableExtension(ExtensionInfo *extinfo)
1340 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1341 extinfo->dobj.dump = false;
1343 extinfo->dobj.dump = include_everything;
1347 * selectDumpableObject: policy-setting subroutine
1348 * Mark a generic dumpable object as to be dumped or not
1350 * Use this only for object types without a special-case routine above.
1353 selectDumpableObject(DumpableObject *dobj)
1356 * Default policy is to dump if parent namespace is dumpable, or always
1357 * for non-namespace-associated items.
1359 if (dobj->namespace)
1360 dobj->dump = dobj->namespace->dobj.dump;
1366 * Dump a table's contents for loading using the COPY command
1367 * - this routine is called by the Archiver when it wants the table
1372 dumpTableData_copy(Archive *fout, void *dcontext)
1374 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1375 TableInfo *tbinfo = tdinfo->tdtable;
1376 const char *classname = tbinfo->dobj.name;
1377 const bool hasoids = tbinfo->hasoids;
1378 const bool oids = tdinfo->oids;
1379 PQExpBuffer q = createPQExpBuffer();
1382 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1383 * which uses it already.
1385 PQExpBuffer clistBuf = createPQExpBuffer();
1386 PGconn *conn = GetConnection(fout);
1390 const char *column_list;
1393 write_msg(NULL, "dumping contents of table %s\n", classname);
1396 * Make sure we are in proper schema. We will qualify the table name
1397 * below anyway (in case its name conflicts with a pg_catalog table); but
1398 * this ensures reproducible results in case the table contains regproc,
1399 * regclass, etc columns.
1401 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1404 * If possible, specify the column list explicitly so that we have no
1405 * possibility of retrieving data in the wrong column order. (The default
1406 * column ordering of COPY will not be what we want in certain corner
1407 * cases involving ADD COLUMN and inheritance.)
1409 if (fout->remoteVersion >= 70300)
1410 column_list = fmtCopyColumnList(tbinfo, clistBuf);
1412 column_list = ""; /* can't select columns in COPY */
1414 if (oids && hasoids)
1416 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1417 fmtQualifiedId(fout->remoteVersion,
1418 tbinfo->dobj.namespace->dobj.name,
1422 else if (tdinfo->filtercond)
1424 /* Note: this syntax is only supported in 8.2 and up */
1425 appendPQExpBufferStr(q, "COPY (SELECT ");
1426 /* klugery to get rid of parens in column list */
1427 if (strlen(column_list) > 2)
1429 appendPQExpBufferStr(q, column_list + 1);
1430 q->data[q->len - 1] = ' ';
1433 appendPQExpBufferStr(q, "* ");
1434 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1435 fmtQualifiedId(fout->remoteVersion,
1436 tbinfo->dobj.namespace->dobj.name,
1438 tdinfo->filtercond);
1442 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1443 fmtQualifiedId(fout->remoteVersion,
1444 tbinfo->dobj.namespace->dobj.name,
1448 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1450 destroyPQExpBuffer(clistBuf);
1454 ret = PQgetCopyData(conn, ©buf, 0);
1457 break; /* done or error */
1461 WriteData(fout, copybuf, ret);
1468 * There was considerable discussion in late July, 2000 regarding
1469 * slowing down pg_dump when backing up large tables. Users with both
1470 * slow & fast (multi-processor) machines experienced performance
1471 * degradation when doing a backup.
1473 * Initial attempts based on sleeping for a number of ms for each ms
1474 * of work were deemed too complex, then a simple 'sleep in each loop'
1475 * implementation was suggested. The latter failed because the loop
1476 * was too tight. Finally, the following was implemented:
1478 * If throttle is non-zero, then
1479 * See how long since the last sleep.
1480 * Work out how long to sleep (based on ratio).
1481 * If sleep is more than 100ms, then
1487 * where the throttle value was the number of ms to sleep per ms of
1488 * work. The calculation was done in each loop.
1490 * Most of the hard work is done in the backend, and this solution
1491 * still did not work particularly well: on slow machines, the ratio
1492 * was 50:1, and on medium paced machines, 1:1, and on fast
1493 * multi-processor machines, it had little or no effect, for reasons
1494 * that were unclear.
1496 * Further discussion ensued, and the proposal was dropped.
1498 * For those people who want this feature, it can be implemented using
1499 * gettimeofday in each loop, calculating the time since last sleep,
1500 * multiplying that by the sleep ratio, then if the result is more
1501 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1502 * function to sleep for a subsecond period ie.
1504 * select(0, NULL, NULL, NULL, &tvi);
1506 * This will return after the interval specified in the structure tvi.
1507 * Finally, call gettimeofday again to save the 'last sleep time'.
1511 archprintf(fout, "\\.\n\n\n");
1515 /* copy data transfer failed */
1516 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1517 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1518 write_msg(NULL, "The command was: %s\n", q->data);
1522 /* Check command status and return to normal libpq state */
1523 res = PQgetResult(conn);
1524 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1526 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1527 write_msg(NULL, "Error message from server: %s", PQerrorMessage(conn));
1528 write_msg(NULL, "The command was: %s\n", q->data);
1533 destroyPQExpBuffer(q);
1538 * Dump table data using INSERT commands.
1540 * Caution: when we restore from an archive file direct to database, the
1541 * INSERT commands emitted by this function have to be parsed by
1542 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1543 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1546 dumpTableData_insert(Archive *fout, void *dcontext)
1548 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1549 TableInfo *tbinfo = tdinfo->tdtable;
1550 const char *classname = tbinfo->dobj.name;
1551 PQExpBuffer q = createPQExpBuffer();
1558 * Make sure we are in proper schema. We will qualify the table name
1559 * below anyway (in case its name conflicts with a pg_catalog table); but
1560 * this ensures reproducible results in case the table contains regproc,
1561 * regclass, etc columns.
1563 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1565 if (fout->remoteVersion >= 70100)
1567 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1568 "SELECT * FROM ONLY %s",
1569 fmtQualifiedId(fout->remoteVersion,
1570 tbinfo->dobj.namespace->dobj.name,
1575 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1577 fmtQualifiedId(fout->remoteVersion,
1578 tbinfo->dobj.namespace->dobj.name,
1581 if (tdinfo->filtercond)
1582 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1584 ExecuteSqlStatement(fout, q->data);
1588 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1590 nfields = PQnfields(res);
1591 for (tuple = 0; tuple < PQntuples(res); tuple++)
1593 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1596 /* corner case for zero-column table */
1597 archprintf(fout, "DEFAULT VALUES;\n");
1602 resetPQExpBuffer(q);
1603 appendPQExpBuffer(q, "(");
1604 for (field = 0; field < nfields; field++)
1607 appendPQExpBuffer(q, ", ");
1608 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1610 appendPQExpBuffer(q, ") ");
1611 archputs(q->data, fout);
1613 archprintf(fout, "VALUES (");
1614 for (field = 0; field < nfields; field++)
1617 archprintf(fout, ", ");
1618 if (PQgetisnull(res, tuple, field))
1620 archprintf(fout, "NULL");
1624 /* XXX This code is partially duplicated in ruleutils.c */
1625 switch (PQftype(res, field))
1636 * These types are printed without quotes unless
1637 * they contain values that aren't accepted by the
1638 * scanner unquoted (e.g., 'NaN'). Note that
1639 * strtod() and friends might accept NaN, so we
1640 * can't use that to test.
1642 * In reality we only need to defend against
1643 * infinity and NaN, so we need not get too crazy
1644 * about pattern matching here.
1646 const char *s = PQgetvalue(res, tuple, field);
1648 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1649 archprintf(fout, "%s", s);
1651 archprintf(fout, "'%s'", s);
1657 archprintf(fout, "B'%s'",
1658 PQgetvalue(res, tuple, field));
1662 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1663 archprintf(fout, "true");
1665 archprintf(fout, "false");
1669 /* All other types are printed as string literals. */
1670 resetPQExpBuffer(q);
1671 appendStringLiteralAH(q,
1672 PQgetvalue(res, tuple, field),
1674 archputs(q->data, fout);
1678 archprintf(fout, ");\n");
1681 if (PQntuples(res) <= 0)
1689 archprintf(fout, "\n\n");
1691 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1693 destroyPQExpBuffer(q);
1700 * dump the contents of a single table
1702 * Actually, this just makes an ArchiveEntry for the table contents.
1705 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1707 TableInfo *tbinfo = tdinfo->tdtable;
1708 PQExpBuffer copyBuf = createPQExpBuffer();
1709 PQExpBuffer clistBuf = createPQExpBuffer();
1710 DataDumperPtr dumpFn;
1715 /* Dump/restore using COPY */
1716 dumpFn = dumpTableData_copy;
1717 /* must use 2 steps here 'cause fmtId is nonreentrant */
1718 appendPQExpBuffer(copyBuf, "COPY %s ",
1719 fmtId(tbinfo->dobj.name));
1720 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1721 fmtCopyColumnList(tbinfo, clistBuf),
1722 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1723 copyStmt = copyBuf->data;
1727 /* Restore using INSERT */
1728 dumpFn = dumpTableData_insert;
1733 * Note: although the TableDataInfo is a full DumpableObject, we treat its
1734 * dependency on its table as "special" and pass it to ArchiveEntry now.
1735 * See comments for BuildArchiveDependencies.
1737 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1738 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1739 NULL, tbinfo->rolname,
1740 false, "TABLE DATA", SECTION_DATA,
1742 &(tbinfo->dobj.dumpId), 1,
1745 destroyPQExpBuffer(copyBuf);
1746 destroyPQExpBuffer(clistBuf);
1750 * refreshMatViewData -
1751 * load or refresh the contents of a single materialized view
1753 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
1757 refreshMatViewData(Archive *fout, TableDataInfo *tdinfo)
1759 TableInfo *tbinfo = tdinfo->tdtable;
1762 /* If the materialized view is not flagged as populated, skip this. */
1763 if (!tbinfo->relispopulated)
1766 q = createPQExpBuffer();
1768 appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
1769 fmtId(tbinfo->dobj.name));
1772 tdinfo->dobj.catId, /* catalog ID */
1773 tdinfo->dobj.dumpId, /* dump ID */
1774 tbinfo->dobj.name, /* Name */
1775 tbinfo->dobj.namespace->dobj.name, /* Namespace */
1776 NULL, /* Tablespace */
1777 tbinfo->rolname, /* Owner */
1778 false, /* with oids */
1779 "MATERIALIZED VIEW DATA", /* Desc */
1780 SECTION_POST_DATA, /* Section */
1781 q->data, /* Create */
1784 tdinfo->dobj.dependencies, /* Deps */
1785 tdinfo->dobj.nDeps, /* # Deps */
1787 NULL); /* Dumper Arg */
1789 destroyPQExpBuffer(q);
1794 * set up dumpable objects representing the contents of tables
1797 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1801 for (i = 0; i < numTables; i++)
1803 if (tblinfo[i].dobj.dump)
1804 makeTableDataInfo(&(tblinfo[i]), oids);
1809 * Make a dumpable object for the data of this specific table
1811 * Note: we make a TableDataInfo if and only if we are going to dump the
1812 * table data; the "dump" flag in such objects isn't used.
1815 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1817 TableDataInfo *tdinfo;
1820 * Nothing to do if we already decided to dump the table. This will
1821 * happen for "config" tables.
1823 if (tbinfo->dataObj != NULL)
1826 /* Skip VIEWs (no data to dump) */
1827 if (tbinfo->relkind == RELKIND_VIEW)
1829 /* Skip FOREIGN TABLEs (no data to dump) */
1830 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1833 /* Don't dump data in unlogged tables, if so requested */
1834 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1835 no_unlogged_table_data)
1838 /* Check that the data is not explicitly excluded */
1839 if (simple_oid_list_member(&tabledata_exclude_oids,
1840 tbinfo->dobj.catId.oid))
1843 /* OK, let's dump it */
1844 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1846 if (tbinfo->relkind == RELKIND_MATVIEW)
1847 tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
1849 tdinfo->dobj.objType = DO_TABLE_DATA;
1852 * Note: use tableoid 0 so that this object won't be mistaken for
1853 * something that pg_depend entries apply to.
1855 tdinfo->dobj.catId.tableoid = 0;
1856 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1857 AssignDumpId(&tdinfo->dobj);
1858 tdinfo->dobj.name = tbinfo->dobj.name;
1859 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1860 tdinfo->tdtable = tbinfo;
1861 tdinfo->oids = oids;
1862 tdinfo->filtercond = NULL; /* might get set later */
1863 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1865 tbinfo->dataObj = tdinfo;
1869 * The refresh for a materialized view must be dependent on the refresh for
1870 * any materialized view that this one is dependent on.
1872 * This must be called after all the objects are created, but before they are
1876 buildMatViewRefreshDependencies(Archive *fout)
1886 /* No Mat Views before 9.3. */
1887 if (fout->remoteVersion < 90300)
1890 /* Make sure we are in proper schema */
1891 selectSourceSchema(fout, "pg_catalog");
1893 query = createPQExpBuffer();
1895 appendPQExpBuffer(query, "with recursive w as "
1897 "select d1.objid, d2.refobjid, c2.relkind as refrelkind "
1898 "from pg_depend d1 "
1899 "join pg_class c1 on c1.oid = d1.objid "
1900 "and c1.relkind = 'm' "
1901 "join pg_rewrite r1 on r1.ev_class = d1.objid "
1902 "join pg_depend d2 on d2.classid = 'pg_rewrite'::regclass "
1903 "and d2.objid = r1.oid "
1904 "and d2.refobjid <> d1.objid "
1905 "join pg_class c2 on c2.oid = d2.refobjid "
1906 "and c2.relkind in ('m','v') "
1907 "where d1.classid = 'pg_class'::regclass "
1909 "select w.objid, d3.refobjid, c3.relkind "
1911 "join pg_rewrite r3 on r3.ev_class = w.refobjid "
1912 "join pg_depend d3 on d3.classid = 'pg_rewrite'::regclass "
1913 "and d3.objid = r3.oid "
1914 "and d3.refobjid <> w.refobjid "
1915 "join pg_class c3 on c3.oid = d3.refobjid "
1916 "and c3.relkind in ('m','v') "
1918 "select 'pg_class'::regclass::oid as classid, objid, refobjid "
1920 "where refrelkind = 'm'");
1922 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1924 ntups = PQntuples(res);
1926 i_classid = PQfnumber(res, "classid");
1927 i_objid = PQfnumber(res, "objid");
1928 i_refobjid = PQfnumber(res, "refobjid");
1930 for (i = 0; i < ntups; i++)
1934 DumpableObject *dobj;
1935 DumpableObject *refdobj;
1937 TableInfo *reftbinfo;
1939 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
1940 objId.oid = atooid(PQgetvalue(res, i, i_objid));
1941 refobjId.tableoid = objId.tableoid;
1942 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
1944 dobj = findObjectByCatalogId(objId);
1948 Assert(dobj->objType == DO_TABLE);
1949 tbinfo = (TableInfo *) dobj;
1950 Assert(tbinfo->relkind == RELKIND_MATVIEW);
1951 dobj = (DumpableObject *) tbinfo->dataObj;
1954 Assert(dobj->objType == DO_REFRESH_MATVIEW);
1956 refdobj = findObjectByCatalogId(refobjId);
1957 if (refdobj == NULL)
1960 Assert(refdobj->objType == DO_TABLE);
1961 reftbinfo = (TableInfo *) refdobj;
1962 Assert(reftbinfo->relkind == RELKIND_MATVIEW);
1963 refdobj = (DumpableObject *) reftbinfo->dataObj;
1964 if (refdobj == NULL)
1966 Assert(refdobj->objType == DO_REFRESH_MATVIEW);
1968 addObjectDependency(dobj, refdobj->dumpId);
1970 if (!reftbinfo->relispopulated)
1971 tbinfo->relispopulated = false;
1976 destroyPQExpBuffer(query);
1980 * getTableDataFKConstraints -
1981 * add dump-order dependencies reflecting foreign key constraints
1983 * This code is executed only in a data-only dump --- in schema+data dumps
1984 * we handle foreign key issues by not creating the FK constraints until
1985 * after the data is loaded. In a data-only dump, however, we want to
1986 * order the table data objects in such a way that a table's referenced
1987 * tables are restored first. (In the presence of circular references or
1988 * self-references this may be impossible; we'll detect and complain about
1989 * that during the dependency sorting step.)
1992 getTableDataFKConstraints(void)
1994 DumpableObject **dobjs;
1998 /* Search through all the dumpable objects for FK constraints */
1999 getDumpableObjects(&dobjs, &numObjs);
2000 for (i = 0; i < numObjs; i++)
2002 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
2004 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
2007 /* Not interesting unless both tables are to be dumped */
2008 if (cinfo->contable == NULL ||
2009 cinfo->contable->dataObj == NULL)
2011 ftable = findTableByOid(cinfo->confrelid);
2012 if (ftable == NULL ||
2013 ftable->dataObj == NULL)
2017 * Okay, make referencing table's TABLE_DATA object depend on the
2018 * referenced table's TABLE_DATA object.
2020 addObjectDependency(&cinfo->contable->dataObj->dobj,
2021 ftable->dataObj->dobj.dumpId);
2029 * guessConstraintInheritance:
2030 * In pre-8.4 databases, we can't tell for certain which constraints
2031 * are inherited. We assume a CHECK constraint is inherited if its name
2032 * matches the name of any constraint in the parent. Originally this code
2033 * tried to compare the expression texts, but that can fail for various
2034 * reasons --- for example, if the parent and child tables are in different
2035 * schemas, reverse-listing of function calls may produce different text
2036 * (schema-qualified or not) depending on search path.
2038 * In 8.4 and up we can rely on the conislocal field to decide which
2039 * constraints must be dumped; much safer.
2041 * This function assumes all conislocal flags were initialized to TRUE.
2042 * It clears the flag on anything that seems to be inherited.
2045 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
2051 for (i = 0; i < numTables; i++)
2053 TableInfo *tbinfo = &(tblinfo[i]);
2055 TableInfo **parents;
2058 /* Sequences and views never have parents */
2059 if (tbinfo->relkind == RELKIND_SEQUENCE ||
2060 tbinfo->relkind == RELKIND_VIEW)
2063 /* Don't bother computing anything for non-target tables, either */
2064 if (!tbinfo->dobj.dump)
2067 numParents = tbinfo->numParents;
2068 parents = tbinfo->parents;
2070 if (numParents == 0)
2071 continue; /* nothing to see here, move along */
2073 /* scan for inherited CHECK constraints */
2074 for (j = 0; j < tbinfo->ncheck; j++)
2076 ConstraintInfo *constr;
2078 constr = &(tbinfo->checkexprs[j]);
2080 for (k = 0; k < numParents; k++)
2084 parent = parents[k];
2085 for (l = 0; l < parent->ncheck; l++)
2087 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
2089 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
2091 constr->conislocal = false;
2095 if (!constr->conislocal)
2105 * dump the database definition
2108 dumpDatabase(Archive *fout)
2110 PQExpBuffer dbQry = createPQExpBuffer();
2111 PQExpBuffer delQry = createPQExpBuffer();
2112 PQExpBuffer creaQry = createPQExpBuffer();
2113 PGconn *conn = GetConnection(fout);
2125 const char *datname,
2133 datname = PQdb(conn);
2136 write_msg(NULL, "saving database definition\n");
2138 /* Make sure we are in proper schema */
2139 selectSourceSchema(fout, "pg_catalog");
2141 /* Get the database owner and parameters from pg_database */
2142 if (fout->remoteVersion >= 80400)
2144 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2145 "(%s datdba) AS dba, "
2146 "pg_encoding_to_char(encoding) AS encoding, "
2147 "datcollate, datctype, datfrozenxid, "
2148 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2149 "shobj_description(oid, 'pg_database') AS description "
2154 appendStringLiteralAH(dbQry, datname, fout);
2156 else if (fout->remoteVersion >= 80200)
2158 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2159 "(%s datdba) AS dba, "
2160 "pg_encoding_to_char(encoding) AS encoding, "
2161 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2162 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2163 "shobj_description(oid, 'pg_database') AS description "
2168 appendStringLiteralAH(dbQry, datname, fout);
2170 else if (fout->remoteVersion >= 80000)
2172 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2173 "(%s datdba) AS dba, "
2174 "pg_encoding_to_char(encoding) AS encoding, "
2175 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
2176 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2180 appendStringLiteralAH(dbQry, datname, fout);
2182 else if (fout->remoteVersion >= 70100)
2184 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
2185 "(%s datdba) AS dba, "
2186 "pg_encoding_to_char(encoding) AS encoding, "
2187 "NULL AS datcollate, NULL AS datctype, "
2188 "0 AS datfrozenxid, "
2189 "NULL AS tablespace "
2193 appendStringLiteralAH(dbQry, datname, fout);
2197 appendPQExpBuffer(dbQry, "SELECT "
2198 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
2200 "(%s datdba) AS dba, "
2201 "pg_encoding_to_char(encoding) AS encoding, "
2202 "NULL AS datcollate, NULL AS datctype, "
2203 "0 AS datfrozenxid, "
2204 "NULL AS tablespace "
2208 appendStringLiteralAH(dbQry, datname, fout);
2211 res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
2213 i_tableoid = PQfnumber(res, "tableoid");
2214 i_oid = PQfnumber(res, "oid");
2215 i_dba = PQfnumber(res, "dba");
2216 i_encoding = PQfnumber(res, "encoding");
2217 i_collate = PQfnumber(res, "datcollate");
2218 i_ctype = PQfnumber(res, "datctype");
2219 i_frozenxid = PQfnumber(res, "datfrozenxid");
2220 i_tablespace = PQfnumber(res, "tablespace");
2222 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
2223 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
2224 dba = PQgetvalue(res, 0, i_dba);
2225 encoding = PQgetvalue(res, 0, i_encoding);
2226 collate = PQgetvalue(res, 0, i_collate);
2227 ctype = PQgetvalue(res, 0, i_ctype);
2228 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
2229 tablespace = PQgetvalue(res, 0, i_tablespace);
2231 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
2233 if (strlen(encoding) > 0)
2235 appendPQExpBuffer(creaQry, " ENCODING = ");
2236 appendStringLiteralAH(creaQry, encoding, fout);
2238 if (strlen(collate) > 0)
2240 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
2241 appendStringLiteralAH(creaQry, collate, fout);
2243 if (strlen(ctype) > 0)
2245 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
2246 appendStringLiteralAH(creaQry, ctype, fout);
2248 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
2249 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
2251 appendPQExpBuffer(creaQry, ";\n");
2255 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
2256 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
2257 "SET datfrozenxid = '%u'\n"
2260 appendStringLiteralAH(creaQry, datname, fout);
2261 appendPQExpBuffer(creaQry, ";\n");
2265 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2268 dbDumpId = createDumpId();
2271 dbCatId, /* catalog ID */
2272 dbDumpId, /* dump ID */
2274 NULL, /* Namespace */
2275 NULL, /* Tablespace */
2277 false, /* with oids */
2278 "DATABASE", /* Desc */
2279 SECTION_PRE_DATA, /* Section */
2280 creaQry->data, /* Create */
2281 delQry->data, /* Del */
2286 NULL); /* Dumper Arg */
2289 * pg_largeobject and pg_largeobject_metadata come from the old system
2290 * intact, so set their relfrozenxids.
2295 PQExpBuffer loFrozenQry = createPQExpBuffer();
2296 PQExpBuffer loOutQry = createPQExpBuffer();
2302 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2303 "FROM pg_catalog.pg_class\n"
2304 "WHERE oid = %u;\n",
2305 LargeObjectRelationId);
2307 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2309 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2311 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2312 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2313 "SET relfrozenxid = '%u'\n"
2314 "WHERE oid = %u;\n",
2315 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2316 LargeObjectRelationId);
2317 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2318 "pg_largeobject", NULL, NULL, "",
2319 false, "pg_largeobject", SECTION_PRE_DATA,
2320 loOutQry->data, "", NULL,
2327 * pg_largeobject_metadata
2329 if (fout->remoteVersion >= 90000)
2331 resetPQExpBuffer(loFrozenQry);
2332 resetPQExpBuffer(loOutQry);
2334 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2335 "FROM pg_catalog.pg_class\n"
2336 "WHERE oid = %u;\n",
2337 LargeObjectMetadataRelationId);
2339 lo_res = ExecuteSqlQueryForSingleRow(fout, loFrozenQry->data);
2341 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2343 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2344 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2345 "SET relfrozenxid = '%u'\n"
2346 "WHERE oid = %u;\n",
2347 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2348 LargeObjectMetadataRelationId);
2349 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2350 "pg_largeobject_metadata", NULL, NULL, "",
2351 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2352 loOutQry->data, "", NULL,
2359 destroyPQExpBuffer(loFrozenQry);
2360 destroyPQExpBuffer(loOutQry);
2363 /* Dump DB comment if any */
2364 if (fout->remoteVersion >= 80200)
2367 * 8.2 keeps comments on shared objects in a shared table, so we
2368 * cannot use the dumpComment used for other database objects.
2370 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2372 if (comment && strlen(comment))
2374 resetPQExpBuffer(dbQry);
2377 * Generates warning when loaded into a differently-named
2380 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2381 appendStringLiteralAH(dbQry, comment, fout);
2382 appendPQExpBuffer(dbQry, ";\n");
2384 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2385 dba, false, "COMMENT", SECTION_NONE,
2386 dbQry->data, "", NULL,
2387 &dbDumpId, 1, NULL, NULL);
2392 resetPQExpBuffer(dbQry);
2393 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2394 dumpComment(fout, dbQry->data, NULL, "",
2395 dbCatId, 0, dbDumpId);
2400 /* Dump shared security label. */
2401 if (!no_security_labels && fout->remoteVersion >= 90200)
2403 PQExpBuffer seclabelQry = createPQExpBuffer();
2405 buildShSecLabelQuery(conn, "pg_database", dbCatId.oid, seclabelQry);
2406 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2407 resetPQExpBuffer(seclabelQry);
2408 emitShSecLabels(conn, res, seclabelQry, "DATABASE", datname);
2409 if (strlen(seclabelQry->data))
2410 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2411 dba, false, "SECURITY LABEL", SECTION_NONE,
2412 seclabelQry->data, "", NULL,
2413 &dbDumpId, 1, NULL, NULL);
2414 destroyPQExpBuffer(seclabelQry);
2417 destroyPQExpBuffer(dbQry);
2418 destroyPQExpBuffer(delQry);
2419 destroyPQExpBuffer(creaQry);
2424 * dumpEncoding: put the correct encoding into the archive
2427 dumpEncoding(Archive *AH)
2429 const char *encname = pg_encoding_to_char(AH->encoding);
2430 PQExpBuffer qry = createPQExpBuffer();
2433 write_msg(NULL, "saving encoding = %s\n", encname);
2435 appendPQExpBuffer(qry, "SET client_encoding = ");
2436 appendStringLiteralAH(qry, encname, AH);
2437 appendPQExpBuffer(qry, ";\n");
2439 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2440 "ENCODING", NULL, NULL, "",
2441 false, "ENCODING", SECTION_PRE_DATA,
2442 qry->data, "", NULL,
2446 destroyPQExpBuffer(qry);
2451 * dumpStdStrings: put the correct escape string behavior into the archive
2454 dumpStdStrings(Archive *AH)
2456 const char *stdstrings = AH->std_strings ? "on" : "off";
2457 PQExpBuffer qry = createPQExpBuffer();
2460 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2463 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2466 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2467 "STDSTRINGS", NULL, NULL, "",
2468 false, "STDSTRINGS", SECTION_PRE_DATA,
2469 qry->data, "", NULL,
2473 destroyPQExpBuffer(qry);
2479 * Collect schema-level data about large objects
2482 getBlobs(Archive *fout)
2484 PQExpBuffer blobQry = createPQExpBuffer();
2486 DumpableObject *bdata;
2491 /* Verbose message */
2493 write_msg(NULL, "reading large objects\n");
2495 /* Make sure we are in proper schema */
2496 selectSourceSchema(fout, "pg_catalog");
2498 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2499 if (fout->remoteVersion >= 90000)
2500 appendPQExpBuffer(blobQry,
2501 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2502 " FROM pg_largeobject_metadata",
2504 else if (fout->remoteVersion >= 70100)
2505 appendPQExpBuffer(blobQry,
2506 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2507 " FROM pg_largeobject");
2509 appendPQExpBuffer(blobQry,
2510 "SELECT oid, NULL::oid, NULL::oid"
2511 " FROM pg_class WHERE relkind = 'l'");
2513 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2515 ntups = PQntuples(res);
2519 * Each large object has its own BLOB archive entry.
2521 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2523 for (i = 0; i < ntups; i++)
2525 binfo[i].dobj.objType = DO_BLOB;
2526 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2527 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2528 AssignDumpId(&binfo[i].dobj);
2530 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2531 if (!PQgetisnull(res, i, 1))
2532 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2534 binfo[i].rolname = "";
2535 if (!PQgetisnull(res, i, 2))
2536 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2538 binfo[i].blobacl = NULL;
2542 * If we have any large objects, a "BLOBS" archive entry is needed.
2543 * This is just a placeholder for sorting; it carries no data now.
2545 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2546 bdata->objType = DO_BLOB_DATA;
2547 bdata->catId = nilCatalogId;
2548 AssignDumpId(bdata);
2549 bdata->name = pg_strdup("BLOBS");
2553 destroyPQExpBuffer(blobQry);
2559 * dump the definition (metadata) of the given large object
2562 dumpBlob(Archive *fout, BlobInfo *binfo)
2564 PQExpBuffer cquery = createPQExpBuffer();
2565 PQExpBuffer dquery = createPQExpBuffer();
2567 appendPQExpBuffer(cquery,
2568 "SELECT pg_catalog.lo_create('%s');\n",
2571 appendPQExpBuffer(dquery,
2572 "SELECT pg_catalog.lo_unlink('%s');\n",
2575 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2578 binfo->rolname, false,
2579 "BLOB", SECTION_PRE_DATA,
2580 cquery->data, dquery->data, NULL,
2584 /* set up tag for comment and/or ACL */
2585 resetPQExpBuffer(cquery);
2586 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2588 /* Dump comment if any */
2589 dumpComment(fout, cquery->data,
2590 NULL, binfo->rolname,
2591 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2593 /* Dump security label if any */
2594 dumpSecLabel(fout, cquery->data,
2595 NULL, binfo->rolname,
2596 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2598 /* Dump ACL if any */
2600 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2601 binfo->dobj.name, NULL, cquery->data,
2602 NULL, binfo->rolname, binfo->blobacl);
2604 destroyPQExpBuffer(cquery);
2605 destroyPQExpBuffer(dquery);
2610 * dump the data contents of all large objects
2613 dumpBlobs(Archive *fout, void *arg)
2615 const char *blobQry;
2616 const char *blobFetchQry;
2617 PGconn *conn = GetConnection(fout);
2619 char buf[LOBBUFSIZE];
2625 write_msg(NULL, "saving large objects\n");
2627 /* Make sure we are in proper schema */
2628 selectSourceSchema(fout, "pg_catalog");
2631 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2632 * the already-in-memory dumpable objects instead...
2634 if (fout->remoteVersion >= 90000)
2635 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2636 else if (fout->remoteVersion >= 70100)
2637 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2639 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2641 ExecuteSqlStatement(fout, blobQry);
2643 /* Command to fetch from cursor */
2644 blobFetchQry = "FETCH 1000 IN bloboid";
2649 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2651 /* Process the tuples, if any */
2652 ntups = PQntuples(res);
2653 for (i = 0; i < ntups; i++)
2658 blobOid = atooid(PQgetvalue(res, i, 0));
2660 loFd = lo_open(conn, blobOid, INV_READ);
2662 exit_horribly(NULL, "could not open large object %u: %s",
2663 blobOid, PQerrorMessage(conn));
2665 StartBlob(fout, blobOid);
2667 /* Now read it in chunks, sending data to archive */
2670 cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
2672 exit_horribly(NULL, "error reading large object %u: %s",
2673 blobOid, PQerrorMessage(conn));
2675 WriteData(fout, buf, cnt);
2678 lo_close(conn, loFd);
2680 EndBlob(fout, blobOid);
2684 } while (ntups > 0);
2690 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2691 PQExpBuffer upgrade_buffer,
2694 PQExpBuffer upgrade_query = createPQExpBuffer();
2695 PGresult *upgrade_res;
2696 Oid pg_type_array_oid;
2698 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2699 appendPQExpBuffer(upgrade_buffer,
2700 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2703 /* we only support old >= 8.3 for binary upgrades */
2704 appendPQExpBuffer(upgrade_query,
2706 "FROM pg_catalog.pg_type "
2707 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2710 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2712 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2714 if (OidIsValid(pg_type_array_oid))
2716 appendPQExpBuffer(upgrade_buffer,
2717 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2718 appendPQExpBuffer(upgrade_buffer,
2719 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2723 PQclear(upgrade_res);
2724 destroyPQExpBuffer(upgrade_query);
2728 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2729 PQExpBuffer upgrade_buffer,
2732 PQExpBuffer upgrade_query = createPQExpBuffer();
2733 PGresult *upgrade_res;
2735 bool toast_set = false;
2737 /* we only support old >= 8.3 for binary upgrades */
2738 appendPQExpBuffer(upgrade_query,
2739 "SELECT c.reltype AS crel, t.reltype AS trel "
2740 "FROM pg_catalog.pg_class c "
2741 "LEFT JOIN pg_catalog.pg_class t ON "
2742 " (c.reltoastrelid = t.oid) "
2743 "WHERE c.oid = '%u'::pg_catalog.oid;",
2746 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2748 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2750 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2753 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2755 /* Toast tables do not have pg_type array rows */
2756 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2757 PQfnumber(upgrade_res, "trel")));
2759 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2760 appendPQExpBuffer(upgrade_buffer,
2761 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2767 PQclear(upgrade_res);
2768 destroyPQExpBuffer(upgrade_query);
2774 binary_upgrade_set_pg_class_oids(Archive *fout,
2775 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2778 PQExpBuffer upgrade_query = createPQExpBuffer();
2779 PGresult *upgrade_res;
2780 Oid pg_class_reltoastrelid;
2781 Oid pg_index_indexrelid;
2783 appendPQExpBuffer(upgrade_query,
2784 "SELECT c.reltoastrelid, i.indexrelid "
2785 "FROM pg_catalog.pg_class c LEFT JOIN "
2786 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
2787 "WHERE c.oid = '%u'::pg_catalog.oid;",
2790 upgrade_res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
2792 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2793 pg_index_indexrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "indexrelid")));
2795 appendPQExpBuffer(upgrade_buffer,
2796 "\n-- For binary upgrade, must preserve pg_class oids\n");
2800 appendPQExpBuffer(upgrade_buffer,
2801 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2803 /* only tables have toast tables, not indexes */
2804 if (OidIsValid(pg_class_reltoastrelid))
2807 * One complexity is that the table definition might not require
2808 * the creation of a TOAST table, and the TOAST table might have
2809 * been created long after table creation, when the table was
2810 * loaded with wide data. By setting the TOAST oid we force
2811 * creation of the TOAST heap and TOAST index by the backend so we
2812 * can cleanly copy the files during binary upgrade.
2815 appendPQExpBuffer(upgrade_buffer,
2816 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2817 pg_class_reltoastrelid);
2819 /* every toast table has an index */
2820 appendPQExpBuffer(upgrade_buffer,
2821 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2822 pg_index_indexrelid);
2826 appendPQExpBuffer(upgrade_buffer,
2827 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2830 appendPQExpBuffer(upgrade_buffer, "\n");
2832 PQclear(upgrade_res);
2833 destroyPQExpBuffer(upgrade_query);
2837 * If the DumpableObject is a member of an extension, add a suitable
2838 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2841 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2842 DumpableObject *dobj,
2843 const char *objlabel)
2845 DumpableObject *extobj = NULL;
2848 if (!dobj->ext_member)
2852 * Find the parent extension. We could avoid this search if we wanted to
2853 * add a link field to DumpableObject, but the space costs of that would
2854 * be considerable. We assume that member objects could only have a
2855 * direct dependency on their own extension, not any others.
2857 for (i = 0; i < dobj->nDeps; i++)
2859 extobj = findObjectByDumpId(dobj->dependencies[i]);
2860 if (extobj && extobj->objType == DO_EXTENSION)
2865 exit_horribly(NULL, "could not find parent extension for %s\n", objlabel);
2867 appendPQExpBuffer(upgrade_buffer,
2868 "\n-- For binary upgrade, handle extension membership the hard way\n");
2869 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2870 fmtId(extobj->name),
2876 * read all namespaces in the system catalogs and return them in the
2877 * NamespaceInfo* structure
2879 * numNamespaces is set to the number of namespaces read in
2882 getNamespaces(Archive *fout, int *numNamespaces)
2888 NamespaceInfo *nsinfo;
2896 * Before 7.3, there are no real namespaces; create two dummy entries, one
2897 * for user stuff and one for system stuff.
2899 if (fout->remoteVersion < 70300)
2901 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2903 nsinfo[0].dobj.objType = DO_NAMESPACE;
2904 nsinfo[0].dobj.catId.tableoid = 0;
2905 nsinfo[0].dobj.catId.oid = 0;
2906 AssignDumpId(&nsinfo[0].dobj);
2907 nsinfo[0].dobj.name = pg_strdup("public");
2908 nsinfo[0].rolname = pg_strdup("");
2909 nsinfo[0].nspacl = pg_strdup("");
2911 selectDumpableNamespace(&nsinfo[0]);
2913 nsinfo[1].dobj.objType = DO_NAMESPACE;
2914 nsinfo[1].dobj.catId.tableoid = 0;
2915 nsinfo[1].dobj.catId.oid = 1;
2916 AssignDumpId(&nsinfo[1].dobj);
2917 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2918 nsinfo[1].rolname = pg_strdup("");
2919 nsinfo[1].nspacl = pg_strdup("");
2921 selectDumpableNamespace(&nsinfo[1]);
2928 query = createPQExpBuffer();
2930 /* Make sure we are in proper schema */
2931 selectSourceSchema(fout, "pg_catalog");
2934 * we fetch all namespaces including system ones, so that every object we
2935 * read in can be linked to a containing namespace.
2937 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2938 "(%s nspowner) AS rolname, "
2939 "nspacl FROM pg_namespace",
2942 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2944 ntups = PQntuples(res);
2946 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2948 i_tableoid = PQfnumber(res, "tableoid");
2949 i_oid = PQfnumber(res, "oid");
2950 i_nspname = PQfnumber(res, "nspname");
2951 i_rolname = PQfnumber(res, "rolname");
2952 i_nspacl = PQfnumber(res, "nspacl");
2954 for (i = 0; i < ntups; i++)
2956 nsinfo[i].dobj.objType = DO_NAMESPACE;
2957 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2958 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2959 AssignDumpId(&nsinfo[i].dobj);
2960 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2961 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2962 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2964 /* Decide whether to dump this namespace */
2965 selectDumpableNamespace(&nsinfo[i]);
2967 if (strlen(nsinfo[i].rolname) == 0)
2968 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2969 nsinfo[i].dobj.name);
2973 destroyPQExpBuffer(query);
2975 *numNamespaces = ntups;
2982 * given a namespace OID and an object OID, look up the info read by
2985 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2986 * a system object or not. In 7.3 and later there is no guessing, and we
2987 * don't use objoid at all.
2989 static NamespaceInfo *
2990 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2992 NamespaceInfo *nsinfo;
2994 if (fout->remoteVersion >= 70300)
2996 nsinfo = findNamespaceByOid(nsoid);
3000 /* This code depends on the dummy objects set up by getNamespaces. */
3003 if (objoid > g_last_builtin_oid)
3004 i = 0; /* user object */
3006 i = 1; /* system object */
3007 nsinfo = findNamespaceByOid(i);
3011 exit_horribly(NULL, "schema with OID %u does not exist\n", nsoid);
3018 * read all extensions in the system catalogs and return them in the
3019 * ExtensionInfo* structure
3021 * numExtensions is set to the number of extensions read in
3024 getExtensions(Archive *fout, int *numExtensions)
3030 ExtensionInfo *extinfo;
3035 int i_extrelocatable;
3041 * Before 9.1, there are no extensions.
3043 if (fout->remoteVersion < 90100)
3049 query = createPQExpBuffer();
3051 /* Make sure we are in proper schema */
3052 selectSourceSchema(fout, "pg_catalog");
3054 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
3055 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
3056 "FROM pg_extension x "
3057 "JOIN pg_namespace n ON n.oid = x.extnamespace");
3059 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3061 ntups = PQntuples(res);
3063 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
3065 i_tableoid = PQfnumber(res, "tableoid");
3066 i_oid = PQfnumber(res, "oid");
3067 i_extname = PQfnumber(res, "extname");
3068 i_nspname = PQfnumber(res, "nspname");
3069 i_extrelocatable = PQfnumber(res, "extrelocatable");
3070 i_extversion = PQfnumber(res, "extversion");
3071 i_extconfig = PQfnumber(res, "extconfig");
3072 i_extcondition = PQfnumber(res, "extcondition");
3074 for (i = 0; i < ntups; i++)
3076 extinfo[i].dobj.objType = DO_EXTENSION;
3077 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3078 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3079 AssignDumpId(&extinfo[i].dobj);
3080 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
3081 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
3082 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
3083 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
3084 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
3085 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
3087 /* Decide whether we want to dump it */
3088 selectDumpableExtension(&(extinfo[i]));
3092 destroyPQExpBuffer(query);
3094 *numExtensions = ntups;
3101 * read all types in the system catalogs and return them in the
3102 * TypeInfo* structure
3104 * numTypes is set to the number of types read in
3106 * NB: this must run after getFuncs() because we assume we can do
3110 getTypes(Archive *fout, int *numTypes)
3115 PQExpBuffer query = createPQExpBuffer();
3117 ShellTypeInfo *stinfo;
3134 * we include even the built-in types because those may be used as array
3135 * elements by user-defined types
3137 * we filter out the built-in types when we dump out the types
3139 * same approach for undefined (shell) types and array types
3141 * Note: as of 8.3 we can reliably detect whether a type is an
3142 * auto-generated array type by checking the element type's typarray.
3143 * (Before that the test is capable of generating false positives.) We
3144 * still check for name beginning with '_', though, so as to avoid the
3145 * cost of the subselect probe for all standard types. This would have to
3146 * be revisited if the backend ever allows renaming of array types.
3149 /* Make sure we are in proper schema */
3150 selectSourceSchema(fout, "pg_catalog");
3152 if (fout->remoteVersion >= 90200)
3154 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3155 "typnamespace, typacl, "
3156 "(%s typowner) AS rolname, "
3157 "typinput::oid AS typinput, "
3158 "typoutput::oid AS typoutput, typelem, typrelid, "
3159 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3160 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3161 "typtype, typisdefined, "
3162 "typname[0] = '_' AND typelem != 0 AND "
3163 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3167 else if (fout->remoteVersion >= 80300)
3169 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3170 "typnamespace, '{=U}' AS typacl, "
3171 "(%s typowner) AS rolname, "
3172 "typinput::oid AS typinput, "
3173 "typoutput::oid AS typoutput, typelem, typrelid, "
3174 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3175 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3176 "typtype, typisdefined, "
3177 "typname[0] = '_' AND typelem != 0 AND "
3178 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
3182 else if (fout->remoteVersion >= 70300)
3184 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3185 "typnamespace, '{=U}' AS typacl, "
3186 "(%s typowner) AS rolname, "
3187 "typinput::oid AS typinput, "
3188 "typoutput::oid AS typoutput, typelem, typrelid, "
3189 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3190 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3191 "typtype, typisdefined, "
3192 "typname[0] = '_' AND typelem != 0 AS isarray "
3196 else if (fout->remoteVersion >= 70100)
3198 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
3199 "0::oid AS typnamespace, '{=U}' AS typacl, "
3200 "(%s typowner) AS rolname, "
3201 "typinput::oid AS typinput, "
3202 "typoutput::oid AS typoutput, typelem, typrelid, "
3203 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3204 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3205 "typtype, typisdefined, "
3206 "typname[0] = '_' AND typelem != 0 AS isarray "
3212 appendPQExpBuffer(query, "SELECT "
3213 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
3215 "0::oid AS typnamespace, '{=U}' AS typacl, "
3216 "(%s typowner) AS rolname, "
3217 "typinput::oid AS typinput, "
3218 "typoutput::oid AS typoutput, typelem, typrelid, "
3219 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3220 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3221 "typtype, typisdefined, "
3222 "typname[0] = '_' AND typelem != 0 AS isarray "
3227 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3229 ntups = PQntuples(res);
3231 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3233 i_tableoid = PQfnumber(res, "tableoid");
3234 i_oid = PQfnumber(res, "oid");
3235 i_typname = PQfnumber(res, "typname");
3236 i_typnamespace = PQfnumber(res, "typnamespace");
3237 i_typacl = PQfnumber(res, "typacl");
3238 i_rolname = PQfnumber(res, "rolname");
3239 i_typinput = PQfnumber(res, "typinput");
3240 i_typoutput = PQfnumber(res, "typoutput");
3241 i_typelem = PQfnumber(res, "typelem");
3242 i_typrelid = PQfnumber(res, "typrelid");
3243 i_typrelkind = PQfnumber(res, "typrelkind");
3244 i_typtype = PQfnumber(res, "typtype");
3245 i_typisdefined = PQfnumber(res, "typisdefined");
3246 i_isarray = PQfnumber(res, "isarray");
3248 for (i = 0; i < ntups; i++)
3250 tyinfo[i].dobj.objType = DO_TYPE;
3251 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3252 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3253 AssignDumpId(&tyinfo[i].dobj);
3254 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3255 tyinfo[i].dobj.namespace =
3257 atooid(PQgetvalue(res, i, i_typnamespace)),
3258 tyinfo[i].dobj.catId.oid);
3259 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3260 tyinfo[i].typacl = pg_strdup(PQgetvalue(res, i, i_typacl));
3261 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3262 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3263 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3264 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3265 tyinfo[i].shellType = NULL;
3267 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3268 tyinfo[i].isDefined = true;
3270 tyinfo[i].isDefined = false;
3272 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3273 tyinfo[i].isArray = true;
3275 tyinfo[i].isArray = false;
3277 /* Decide whether we want to dump it */
3278 selectDumpableType(&tyinfo[i]);
3281 * If it's a domain, fetch info about its constraints, if any
3283 tyinfo[i].nDomChecks = 0;
3284 tyinfo[i].domChecks = NULL;
3285 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3286 getDomainConstraints(fout, &(tyinfo[i]));
3289 * If it's a base type, make a DumpableObject representing a shell
3290 * definition of the type. We will need to dump that ahead of the I/O
3291 * functions for the type. Similarly, range types need a shell
3292 * definition in case they have a canonicalize function.
3294 * Note: the shell type doesn't have a catId. You might think it
3295 * should copy the base type's catId, but then it might capture the
3296 * pg_depend entries for the type, which we don't want.
3298 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3299 tyinfo[i].typtype == TYPTYPE_RANGE))
3301 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3302 stinfo->dobj.objType = DO_SHELL_TYPE;
3303 stinfo->dobj.catId = nilCatalogId;
3304 AssignDumpId(&stinfo->dobj);
3305 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3306 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3307 stinfo->baseType = &(tyinfo[i]);
3308 tyinfo[i].shellType = stinfo;
3311 * Initially mark the shell type as not to be dumped. We'll only
3312 * dump it if the I/O or canonicalize functions need to be dumped;
3313 * this is taken care of while sorting dependencies.
3315 stinfo->dobj.dump = false;
3318 * However, if dumping from pre-7.3, there will be no dependency
3319 * info so we have to fake it here. We only need to worry about
3320 * typinput and typoutput since the other functions only exist
3323 if (fout->remoteVersion < 70300)
3329 typinput = atooid(PQgetvalue(res, i, i_typinput));
3330 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3332 funcInfo = findFuncByOid(typinput);
3333 if (funcInfo && funcInfo->dobj.dump)
3335 /* base type depends on function */
3336 addObjectDependency(&tyinfo[i].dobj,
3337 funcInfo->dobj.dumpId);
3338 /* function depends on shell type */
3339 addObjectDependency(&funcInfo->dobj,
3340 stinfo->dobj.dumpId);
3341 /* mark shell type as to be dumped */
3342 stinfo->dobj.dump = true;
3345 funcInfo = findFuncByOid(typoutput);
3346 if (funcInfo && funcInfo->dobj.dump)
3348 /* base type depends on function */
3349 addObjectDependency(&tyinfo[i].dobj,
3350 funcInfo->dobj.dumpId);
3351 /* function depends on shell type */
3352 addObjectDependency(&funcInfo->dobj,
3353 stinfo->dobj.dumpId);
3354 /* mark shell type as to be dumped */
3355 stinfo->dobj.dump = true;
3360 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3361 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3362 tyinfo[i].dobj.name);
3369 destroyPQExpBuffer(query);
3376 * read all operators in the system catalogs and return them in the
3377 * OprInfo* structure
3379 * numOprs is set to the number of operators read in
3382 getOperators(Archive *fout, int *numOprs)
3387 PQExpBuffer query = createPQExpBuffer();
3398 * find all operators, including builtin operators; we filter out
3399 * system-defined operators at dump-out time.
3402 /* Make sure we are in proper schema */
3403 selectSourceSchema(fout, "pg_catalog");
3405 if (fout->remoteVersion >= 70300)
3407 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3409 "(%s oprowner) AS rolname, "
3411 "oprcode::oid AS oprcode "
3415 else if (fout->remoteVersion >= 70100)
3417 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3418 "0::oid AS oprnamespace, "
3419 "(%s oprowner) AS rolname, "
3421 "oprcode::oid AS oprcode "
3427 appendPQExpBuffer(query, "SELECT "
3428 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3430 "0::oid AS oprnamespace, "
3431 "(%s oprowner) AS rolname, "
3433 "oprcode::oid AS oprcode "
3438 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3440 ntups = PQntuples(res);
3443 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3445 i_tableoid = PQfnumber(res, "tableoid");
3446 i_oid = PQfnumber(res, "oid");
3447 i_oprname = PQfnumber(res, "oprname");
3448 i_oprnamespace = PQfnumber(res, "oprnamespace");
3449 i_rolname = PQfnumber(res, "rolname");
3450 i_oprkind = PQfnumber(res, "oprkind");
3451 i_oprcode = PQfnumber(res, "oprcode");
3453 for (i = 0; i < ntups; i++)
3455 oprinfo[i].dobj.objType = DO_OPERATOR;
3456 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3457 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3458 AssignDumpId(&oprinfo[i].dobj);
3459 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3460 oprinfo[i].dobj.namespace =
3462 atooid(PQgetvalue(res, i, i_oprnamespace)),
3463 oprinfo[i].dobj.catId.oid);
3464 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3465 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3466 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3468 /* Decide whether we want to dump it */
3469 selectDumpableObject(&(oprinfo[i].dobj));
3471 if (strlen(oprinfo[i].rolname) == 0)
3472 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3473 oprinfo[i].dobj.name);
3478 destroyPQExpBuffer(query);
3485 * read all collations in the system catalogs and return them in the
3486 * CollInfo* structure
3488 * numCollations is set to the number of collations read in
3491 getCollations(Archive *fout, int *numCollations)
3501 int i_collnamespace;
3504 /* Collations didn't exist pre-9.1 */
3505 if (fout->remoteVersion < 90100)
3511 query = createPQExpBuffer();
3514 * find all collations, including builtin collations; we filter out
3515 * system-defined collations at dump-out time.
3518 /* Make sure we are in proper schema */
3519 selectSourceSchema(fout, "pg_catalog");
3521 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3523 "(%s collowner) AS rolname "
3524 "FROM pg_collation",
3527 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3529 ntups = PQntuples(res);
3530 *numCollations = ntups;
3532 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3534 i_tableoid = PQfnumber(res, "tableoid");
3535 i_oid = PQfnumber(res, "oid");
3536 i_collname = PQfnumber(res, "collname");
3537 i_collnamespace = PQfnumber(res, "collnamespace");
3538 i_rolname = PQfnumber(res, "rolname");
3540 for (i = 0; i < ntups; i++)
3542 collinfo[i].dobj.objType = DO_COLLATION;
3543 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3544 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3545 AssignDumpId(&collinfo[i].dobj);
3546 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3547 collinfo[i].dobj.namespace =
3549 atooid(PQgetvalue(res, i, i_collnamespace)),
3550 collinfo[i].dobj.catId.oid);
3551 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3553 /* Decide whether we want to dump it */
3554 selectDumpableObject(&(collinfo[i].dobj));
3559 destroyPQExpBuffer(query);
3566 * read all conversions in the system catalogs and return them in the
3567 * ConvInfo* structure
3569 * numConversions is set to the number of conversions read in
3572 getConversions(Archive *fout, int *numConversions)
3577 PQExpBuffer query = createPQExpBuffer();
3585 /* Conversions didn't exist pre-7.3 */
3586 if (fout->remoteVersion < 70300)
3588 *numConversions = 0;
3593 * find all conversions, including builtin conversions; we filter out
3594 * system-defined conversions at dump-out time.
3597 /* Make sure we are in proper schema */
3598 selectSourceSchema(fout, "pg_catalog");
3600 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3602 "(%s conowner) AS rolname "
3603 "FROM pg_conversion",
3606 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3608 ntups = PQntuples(res);
3609 *numConversions = ntups;
3611 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3613 i_tableoid = PQfnumber(res, "tableoid");
3614 i_oid = PQfnumber(res, "oid");
3615 i_conname = PQfnumber(res, "conname");
3616 i_connamespace = PQfnumber(res, "connamespace");
3617 i_rolname = PQfnumber(res, "rolname");
3619 for (i = 0; i < ntups; i++)
3621 convinfo[i].dobj.objType = DO_CONVERSION;
3622 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3623 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3624 AssignDumpId(&convinfo[i].dobj);
3625 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3626 convinfo[i].dobj.namespace =
3628 atooid(PQgetvalue(res, i, i_connamespace)),
3629 convinfo[i].dobj.catId.oid);
3630 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3632 /* Decide whether we want to dump it */
3633 selectDumpableObject(&(convinfo[i].dobj));
3638 destroyPQExpBuffer(query);
3645 * read all opclasses in the system catalogs and return them in the
3646 * OpclassInfo* structure
3648 * numOpclasses is set to the number of opclasses read in
3651 getOpclasses(Archive *fout, int *numOpclasses)
3656 PQExpBuffer query = createPQExpBuffer();
3657 OpclassInfo *opcinfo;
3665 * find all opclasses, including builtin opclasses; we filter out
3666 * system-defined opclasses at dump-out time.
3669 /* Make sure we are in proper schema */
3670 selectSourceSchema(fout, "pg_catalog");
3672 if (fout->remoteVersion >= 70300)
3674 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3676 "(%s opcowner) AS rolname "
3680 else if (fout->remoteVersion >= 70100)
3682 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3683 "0::oid AS opcnamespace, "
3684 "''::name AS rolname "
3689 appendPQExpBuffer(query, "SELECT "
3690 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3692 "0::oid AS opcnamespace, "
3693 "''::name AS rolname "
3697 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3699 ntups = PQntuples(res);
3700 *numOpclasses = ntups;
3702 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3704 i_tableoid = PQfnumber(res, "tableoid");
3705 i_oid = PQfnumber(res, "oid");
3706 i_opcname = PQfnumber(res, "opcname");
3707 i_opcnamespace = PQfnumber(res, "opcnamespace");
3708 i_rolname = PQfnumber(res, "rolname");
3710 for (i = 0; i < ntups; i++)
3712 opcinfo[i].dobj.objType = DO_OPCLASS;
3713 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3714 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3715 AssignDumpId(&opcinfo[i].dobj);
3716 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3717 opcinfo[i].dobj.namespace =
3719 atooid(PQgetvalue(res, i, i_opcnamespace)),
3720 opcinfo[i].dobj.catId.oid);
3721 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3723 /* Decide whether we want to dump it */
3724 selectDumpableObject(&(opcinfo[i].dobj));
3726 if (fout->remoteVersion >= 70300)
3728 if (strlen(opcinfo[i].rolname) == 0)
3729 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3730 opcinfo[i].dobj.name);
3736 destroyPQExpBuffer(query);
3743 * read all opfamilies in the system catalogs and return them in the
3744 * OpfamilyInfo* structure
3746 * numOpfamilies is set to the number of opfamilies read in
3749 getOpfamilies(Archive *fout, int *numOpfamilies)
3755 OpfamilyInfo *opfinfo;
3762 /* Before 8.3, there is no separate concept of opfamilies */
3763 if (fout->remoteVersion < 80300)
3769 query = createPQExpBuffer();
3772 * find all opfamilies, including builtin opfamilies; we filter out
3773 * system-defined opfamilies at dump-out time.
3776 /* Make sure we are in proper schema */
3777 selectSourceSchema(fout, "pg_catalog");
3779 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3781 "(%s opfowner) AS rolname "
3785 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3787 ntups = PQntuples(res);
3788 *numOpfamilies = ntups;
3790 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3792 i_tableoid = PQfnumber(res, "tableoid");
3793 i_oid = PQfnumber(res, "oid");
3794 i_opfname = PQfnumber(res, "opfname");
3795 i_opfnamespace = PQfnumber(res, "opfnamespace");
3796 i_rolname = PQfnumber(res, "rolname");
3798 for (i = 0; i < ntups; i++)
3800 opfinfo[i].dobj.objType = DO_OPFAMILY;
3801 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3802 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3803 AssignDumpId(&opfinfo[i].dobj);
3804 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3805 opfinfo[i].dobj.namespace =
3807 atooid(PQgetvalue(res, i, i_opfnamespace)),
3808 opfinfo[i].dobj.catId.oid);
3809 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3811 /* Decide whether we want to dump it */
3812 selectDumpableObject(&(opfinfo[i].dobj));
3814 if (fout->remoteVersion >= 70300)
3816 if (strlen(opfinfo[i].rolname) == 0)
3817 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3818 opfinfo[i].dobj.name);
3824 destroyPQExpBuffer(query);
3831 * read all the user-defined aggregates in the system catalogs and
3832 * return them in the AggInfo* structure
3834 * numAggs is set to the number of aggregates read in
3837 getAggregates(Archive *fout, int *numAggs)
3842 PQExpBuffer query = createPQExpBuffer();
3854 /* Make sure we are in proper schema */
3855 selectSourceSchema(fout, "pg_catalog");
3858 * Find all user-defined aggregates. See comment in getFuncs() for the
3859 * rationale behind the filtering logic.
3862 if (fout->remoteVersion >= 80400)
3864 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3865 "pronamespace AS aggnamespace, "
3866 "pronargs, proargtypes, "
3867 "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
3868 "(%s proowner) AS rolname, "
3871 "WHERE proisagg AND ("
3873 "(SELECT oid FROM pg_namespace "
3874 "WHERE nspname = 'pg_catalog')",
3876 if (binary_upgrade && fout->remoteVersion >= 90100)
3877 appendPQExpBuffer(query,
3878 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3879 "classid = 'pg_proc'::regclass AND "
3880 "objid = p.oid AND "
3881 "refclassid = 'pg_extension'::regclass AND "
3883 appendPQExpBuffer(query, ")");
3885 else if (fout->remoteVersion >= 80200)
3887 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3888 "pronamespace AS aggnamespace, "
3889 "pronargs, proargtypes, "
3890 "NULL::text AS proiargs,"
3891 "(%s proowner) AS rolname, "
3894 "WHERE proisagg AND ("
3896 "(SELECT oid FROM pg_namespace "
3897 "WHERE nspname = 'pg_catalog'))",
3900 else if (fout->remoteVersion >= 70300)
3902 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3903 "pronamespace AS aggnamespace, "
3904 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3906 "NULL::text AS proiargs, "
3907 "(%s proowner) AS rolname, "
3911 "AND pronamespace != "
3912 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3915 else if (fout->remoteVersion >= 70100)
3917 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3918 "0::oid AS aggnamespace, "
3919 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3920 "aggbasetype AS proargtypes, "
3921 "NULL::text AS proiargs, "
3922 "(%s aggowner) AS rolname, "
3924 "FROM pg_aggregate "
3925 "where oid > '%u'::oid",
3927 g_last_builtin_oid);
3931 appendPQExpBuffer(query, "SELECT "
3932 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3934 "0::oid AS aggnamespace, "
3935 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3936 "aggbasetype AS proargtypes, "
3937 "NULL::text AS proiargs, "
3938 "(%s aggowner) AS rolname, "
3940 "FROM pg_aggregate "
3941 "where oid > '%u'::oid",
3943 g_last_builtin_oid);
3946 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3948 ntups = PQntuples(res);
3951 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3953 i_tableoid = PQfnumber(res, "tableoid");
3954 i_oid = PQfnumber(res, "oid");
3955 i_aggname = PQfnumber(res, "aggname");
3956 i_aggnamespace = PQfnumber(res, "aggnamespace");
3957 i_pronargs = PQfnumber(res, "pronargs");
3958 i_proargtypes = PQfnumber(res, "proargtypes");
3959 i_rolname = PQfnumber(res, "rolname");
3960 i_aggacl = PQfnumber(res, "aggacl");
3961 i_proiargs = PQfnumber(res, "proiargs");
3963 for (i = 0; i < ntups; i++)
3965 agginfo[i].aggfn.dobj.objType = DO_AGG;
3966 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3967 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3968 AssignDumpId(&agginfo[i].aggfn.dobj);
3969 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3970 agginfo[i].aggfn.dobj.namespace =
3972 atooid(PQgetvalue(res, i, i_aggnamespace)),
3973 agginfo[i].aggfn.dobj.catId.oid);
3974 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3975 if (strlen(agginfo[i].aggfn.rolname) == 0)
3976 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3977 agginfo[i].aggfn.dobj.name);
3978 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3979 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3980 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3981 agginfo[i].aggfn.proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
3982 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3983 if (agginfo[i].aggfn.nargs == 0)
3984 agginfo[i].aggfn.argtypes = NULL;
3987 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3988 if (fout->remoteVersion >= 70300)
3989 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3990 agginfo[i].aggfn.argtypes,
3991 agginfo[i].aggfn.nargs);
3993 /* it's just aggbasetype */
3994 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3997 /* Decide whether we want to dump it */
3998 selectDumpableObject(&(agginfo[i].aggfn.dobj));
4003 destroyPQExpBuffer(query);
4010 * read all the user-defined functions in the system catalogs and
4011 * return them in the FuncInfo* structure
4013 * numFuncs is set to the number of functions read in
4016 getFuncs(Archive *fout, int *numFuncs)
4021 PQExpBuffer query = createPQExpBuffer();
4035 /* Make sure we are in proper schema */
4036 selectSourceSchema(fout, "pg_catalog");
4039 * Find all user-defined functions. Normally we can exclude functions in
4040 * pg_catalog, which is worth doing since there are several thousand of
4041 * 'em. However, there are some extensions that create functions in
4042 * pg_catalog. In normal dumps we can still ignore those --- but in
4043 * binary-upgrade mode, we must dump the member objects of the extension,
4044 * so be sure to fetch any such functions.
4046 * Also, in 9.2 and up, exclude functions that are internally dependent on
4047 * something else, since presumably those will be created as a result of
4048 * creating the something else. This currently only acts to suppress
4049 * constructor functions for range types. Note that this is OK only
4050 * because the constructors don't have any dependencies the range type
4051 * doesn't have; otherwise we might not get creation ordering correct.
4054 if (fout->remoteVersion >= 80400)
4056 appendPQExpBuffer(query,
4057 "SELECT tableoid, oid, proname, prolang, "
4058 "pronargs, proargtypes, prorettype, proacl, "
4060 "pg_catalog.pg_get_function_identity_arguments(oid) AS proiargs,"
4061 "(%s proowner) AS rolname "
4063 "WHERE NOT proisagg AND ("
4065 "(SELECT oid FROM pg_namespace "
4066 "WHERE nspname = 'pg_catalog')",
4068 if (fout->remoteVersion >= 90200)
4069 appendPQExpBuffer(query,
4070 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
4071 "WHERE classid = 'pg_proc'::regclass AND "
4072 "objid = p.oid AND deptype = 'i')");
4073 if (binary_upgrade && fout->remoteVersion >= 90100)
4074 appendPQExpBuffer(query,
4075 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
4076 "classid = 'pg_proc'::regclass AND "
4077 "objid = p.oid AND "
4078 "refclassid = 'pg_extension'::regclass AND "
4080 appendPQExpBuffer(query, ")");
4082 else if (fout->remoteVersion >= 70300)
4084 appendPQExpBuffer(query,
4085 "SELECT tableoid, oid, proname, prolang, "
4086 "pronargs, proargtypes, prorettype, proacl, "
4088 "NULL::text AS proiargs,"
4089 "(%s proowner) AS rolname "
4091 "WHERE NOT proisagg AND ("
4093 "(SELECT oid FROM pg_namespace "
4094 "WHERE nspname = 'pg_catalog'))",
4097 else if (fout->remoteVersion >= 70100)
4099 appendPQExpBuffer(query,
4100 "SELECT tableoid, oid, proname, prolang, "
4101 "pronargs, proargtypes, prorettype, "
4102 "'{=X}' AS proacl, "
4103 "0::oid AS pronamespace, "
4104 "NULL::text AS proiargs,"
4105 "(%s proowner) AS rolname "
4107 "WHERE pg_proc.oid > '%u'::oid",
4109 g_last_builtin_oid);
4113 appendPQExpBuffer(query,
4115 "(SELECT oid FROM pg_class "
4116 " WHERE relname = 'pg_proc') AS tableoid, "
4117 "oid, proname, prolang, "
4118 "pronargs, proargtypes, prorettype, "
4119 "'{=X}' AS proacl, "
4120 "0::oid AS pronamespace, "
4121 "NULL::text AS proiargs,"
4122 "(%s proowner) AS rolname "
4124 "where pg_proc.oid > '%u'::oid",
4126 g_last_builtin_oid);
4129 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4131 ntups = PQntuples(res);
4135 finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
4137 i_tableoid = PQfnumber(res, "tableoid");
4138 i_oid = PQfnumber(res, "oid");
4139 i_proname = PQfnumber(res, "proname");
4140 i_pronamespace = PQfnumber(res, "pronamespace");
4141 i_rolname = PQfnumber(res, "rolname");
4142 i_prolang = PQfnumber(res, "prolang");
4143 i_pronargs = PQfnumber(res, "pronargs");
4144 i_proargtypes = PQfnumber(res, "proargtypes");
4145 i_prorettype = PQfnumber(res, "prorettype");
4146 i_proacl = PQfnumber(res, "proacl");
4147 i_proiargs = PQfnumber(res, "proiargs");
4149 for (i = 0; i < ntups; i++)
4151 finfo[i].dobj.objType = DO_FUNC;
4152 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4153 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4154 AssignDumpId(&finfo[i].dobj);
4155 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
4156 finfo[i].dobj.namespace =
4158 atooid(PQgetvalue(res, i, i_pronamespace)),
4159 finfo[i].dobj.catId.oid);
4160 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4161 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
4162 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
4163 finfo[i].proiargs = pg_strdup(PQgetvalue(res, i, i_proiargs));
4164 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
4165 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
4166 if (finfo[i].nargs == 0)
4167 finfo[i].argtypes = NULL;
4170 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
4171 parseOidArray(PQgetvalue(res, i, i_proargtypes),
4172 finfo[i].argtypes, finfo[i].nargs);
4175 /* Decide whether we want to dump it */
4176 selectDumpableObject(&(finfo[i].dobj));
4178 if (strlen(finfo[i].rolname) == 0)
4180 "WARNING: owner of function \"%s\" appears to be invalid\n",
4181 finfo[i].dobj.name);
4186 destroyPQExpBuffer(query);
4193 * read all the user-defined tables (no indexes, no catalogs)
4194 * in the system catalogs return them in the TableInfo* structure
4196 * numTables is set to the number of tables read in
4199 getTables(Archive *fout, int *numTables)
4204 PQExpBuffer query = createPQExpBuffer();
4214 int i_relhastriggers;
4220 int i_toastfrozenxid;
4221 int i_relpersistence;
4222 int i_relispopulated;
4225 int i_reltablespace;
4228 int i_toastreloptions;
4232 /* Make sure we are in proper schema */
4233 selectSourceSchema(fout, "pg_catalog");
4236 * Find all the tables and table-like objects.
4238 * We include system catalogs, so that we can work if a user table is
4239 * defined to inherit from a system catalog (pretty weird, but...)
4241 * We ignore relations that are not ordinary tables, sequences, views,
4242 * materialized views, composite types, or foreign tables.
4244 * Composite-type table entries won't be dumped as such, but we have to
4245 * make a DumpableObject for them so that we can track dependencies of the
4246 * composite type (pg_depend entries for columns of the composite type
4247 * link to the pg_class entry not the pg_type entry).
4249 * Note: in this phase we should collect only a minimal amount of
4250 * information about each table, basically just enough to decide if it is
4251 * interesting. We must fetch all tables in this phase because otherwise
4252 * we cannot correctly identify inherited columns, owned sequences, etc.
4255 if (fout->remoteVersion >= 90300)
4258 * Left join to pick up dependency info linking sequences to their
4259 * owning column, if any (note this dependency is AUTO as of 8.2)
4261 appendPQExpBuffer(query,
4262 "SELECT c.tableoid, c.oid, c.relname, "
4263 "c.relacl, c.relkind, c.relnamespace, "
4264 "(%s c.relowner) AS rolname, "
4265 "c.relchecks, c.relhastriggers, "
4266 "c.relhasindex, c.relhasrules, c.relhasoids, "
4267 "c.relfrozenxid, tc.oid AS toid, "
4268 "tc.relfrozenxid AS tfrozenxid, "
4269 "c.relpersistence, c.relispopulated, "
4271 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4272 "d.refobjid AS owning_tab, "
4273 "d.refobjsubid AS owning_col, "
4274 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4275 "array_to_string(array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded'), ', ') AS reloptions, "
4276 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
4277 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
4278 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4280 "LEFT JOIN pg_depend d ON "
4281 "(c.relkind = '%c' AND "
4282 "d.classid = c.tableoid AND d.objid = c.oid AND "
4283 "d.objsubid = 0 AND "
4284 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4285 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4286 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4290 RELKIND_RELATION, RELKIND_SEQUENCE,
4291 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4292 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4294 else if (fout->remoteVersion >= 90100)
4297 * Left join to pick up dependency info linking sequences to their
4298 * owning column, if any (note this dependency is AUTO as of 8.2)
4300 appendPQExpBuffer(query,
4301 "SELECT c.tableoid, c.oid, c.relname, "
4302 "c.relacl, c.relkind, c.relnamespace, "
4303 "(%s c.relowner) AS rolname, "
4304 "c.relchecks, c.relhastriggers, "
4305 "c.relhasindex, c.relhasrules, c.relhasoids, "
4306 "c.relfrozenxid, tc.oid AS toid, "
4307 "tc.relfrozenxid AS tfrozenxid, "
4308 "c.relpersistence, 't' as relispopulated, "
4310 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4311 "d.refobjid AS owning_tab, "
4312 "d.refobjsubid AS owning_col, "
4313 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4314 "array_to_string(c.reloptions, ', ') AS reloptions, "
4315 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4317 "LEFT JOIN pg_depend d ON "
4318 "(c.relkind = '%c' AND "
4319 "d.classid = c.tableoid AND d.objid = c.oid AND "
4320 "d.objsubid = 0 AND "
4321 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4322 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4323 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4327 RELKIND_RELATION, RELKIND_SEQUENCE,
4328 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4329 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4331 else if (fout->remoteVersion >= 90000)
4334 * Left join to pick up dependency info linking sequences to their
4335 * owning column, if any (note this dependency is AUTO as of 8.2)
4337 appendPQExpBuffer(query,
4338 "SELECT c.tableoid, c.oid, c.relname, "
4339 "c.relacl, c.relkind, c.relnamespace, "
4340 "(%s c.relowner) AS rolname, "
4341 "c.relchecks, c.relhastriggers, "
4342 "c.relhasindex, c.relhasrules, c.relhasoids, "
4343 "c.relfrozenxid, tc.oid AS toid, "
4344 "tc.relfrozenxid AS tfrozenxid, "
4345 "'p' AS relpersistence, 't' as relispopulated, "
4347 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4348 "d.refobjid AS owning_tab, "
4349 "d.refobjsubid AS owning_col, "
4350 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4351 "array_to_string(c.reloptions, ', ') AS reloptions, "
4352 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4354 "LEFT JOIN pg_depend d ON "
4355 "(c.relkind = '%c' AND "
4356 "d.classid = c.tableoid AND d.objid = c.oid AND "
4357 "d.objsubid = 0 AND "
4358 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4359 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4360 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4364 RELKIND_RELATION, RELKIND_SEQUENCE,
4365 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4367 else if (fout->remoteVersion >= 80400)
4370 * Left join to pick up dependency info linking sequences to their
4371 * owning column, if any (note this dependency is AUTO as of 8.2)
4373 appendPQExpBuffer(query,
4374 "SELECT c.tableoid, c.oid, c.relname, "
4375 "c.relacl, c.relkind, c.relnamespace, "
4376 "(%s c.relowner) AS rolname, "
4377 "c.relchecks, c.relhastriggers, "
4378 "c.relhasindex, c.relhasrules, c.relhasoids, "
4379 "c.relfrozenxid, tc.oid AS toid, "
4380 "tc.relfrozenxid AS tfrozenxid, "
4381 "'p' AS relpersistence, 't' as relispopulated, "
4383 "NULL AS reloftype, "
4384 "d.refobjid AS owning_tab, "
4385 "d.refobjsubid AS owning_col, "
4386 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4387 "array_to_string(c.reloptions, ', ') AS reloptions, "
4388 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4390 "LEFT JOIN pg_depend d ON "
4391 "(c.relkind = '%c' AND "
4392 "d.classid = c.tableoid AND d.objid = c.oid AND "
4393 "d.objsubid = 0 AND "
4394 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4395 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4396 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4400 RELKIND_RELATION, RELKIND_SEQUENCE,
4401 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4403 else if (fout->remoteVersion >= 80200)
4406 * Left join to pick up dependency info linking sequences to their
4407 * owning column, if any (note this dependency is AUTO as of 8.2)
4409 appendPQExpBuffer(query,
4410 "SELECT c.tableoid, c.oid, c.relname, "
4411 "c.relacl, c.relkind, c.relnamespace, "
4412 "(%s c.relowner) AS rolname, "
4413 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4414 "c.relhasindex, c.relhasrules, c.relhasoids, "
4415 "c.relfrozenxid, tc.oid AS toid, "
4416 "tc.relfrozenxid AS tfrozenxid, "
4417 "'p' AS relpersistence, 't' as relispopulated, "
4419 "NULL AS reloftype, "
4420 "d.refobjid AS owning_tab, "
4421 "d.refobjsubid AS owning_col, "
4422 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4423 "array_to_string(c.reloptions, ', ') AS reloptions, "
4424 "NULL AS toast_reloptions "
4426 "LEFT JOIN pg_depend d ON "
4427 "(c.relkind = '%c' AND "
4428 "d.classid = c.tableoid AND d.objid = c.oid AND "
4429 "d.objsubid = 0 AND "
4430 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4431 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4432 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4436 RELKIND_RELATION, RELKIND_SEQUENCE,
4437 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4439 else if (fout->remoteVersion >= 80000)
4442 * Left join to pick up dependency info linking sequences to their
4443 * owning column, if any
4445 appendPQExpBuffer(query,
4446 "SELECT c.tableoid, c.oid, relname, "
4447 "relacl, relkind, relnamespace, "
4448 "(%s relowner) AS rolname, "
4449 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4450 "relhasindex, relhasrules, relhasoids, "
4451 "0 AS relfrozenxid, "
4454 "'p' AS relpersistence, 't' as relispopulated, "
4456 "NULL AS reloftype, "
4457 "d.refobjid AS owning_tab, "
4458 "d.refobjsubid AS owning_col, "
4459 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4460 "NULL AS reloptions, "
4461 "NULL AS toast_reloptions "
4463 "LEFT JOIN pg_depend d ON "
4464 "(c.relkind = '%c' AND "
4465 "d.classid = c.tableoid AND d.objid = c.oid AND "
4466 "d.objsubid = 0 AND "
4467 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4468 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4472 RELKIND_RELATION, RELKIND_SEQUENCE,
4473 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4475 else if (fout->remoteVersion >= 70300)
4478 * Left join to pick up dependency info linking sequences to their
4479 * owning column, if any
4481 appendPQExpBuffer(query,
4482 "SELECT c.tableoid, c.oid, relname, "
4483 "relacl, relkind, relnamespace, "
4484 "(%s relowner) AS rolname, "
4485 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4486 "relhasindex, relhasrules, relhasoids, "
4487 "0 AS relfrozenxid, "
4490 "'p' AS relpersistence, 't' as relispopulated, "
4492 "NULL AS reloftype, "
4493 "d.refobjid AS owning_tab, "
4494 "d.refobjsubid AS owning_col, "
4495 "NULL AS reltablespace, "
4496 "NULL AS reloptions, "
4497 "NULL AS toast_reloptions "
4499 "LEFT JOIN pg_depend d ON "
4500 "(c.relkind = '%c' AND "
4501 "d.classid = c.tableoid AND d.objid = c.oid AND "
4502 "d.objsubid = 0 AND "
4503 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4504 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4508 RELKIND_RELATION, RELKIND_SEQUENCE,
4509 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4511 else if (fout->remoteVersion >= 70200)
4513 appendPQExpBuffer(query,
4514 "SELECT tableoid, oid, relname, relacl, relkind, "
4515 "0::oid AS relnamespace, "
4516 "(%s relowner) AS rolname, "
4517 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4518 "relhasindex, relhasrules, relhasoids, "
4519 "0 AS relfrozenxid, "
4522 "'p' AS relpersistence, 't' as relispopulated, "
4524 "NULL AS reloftype, "
4525 "NULL::oid AS owning_tab, "
4526 "NULL::int4 AS owning_col, "
4527 "NULL AS reltablespace, "
4528 "NULL AS reloptions, "
4529 "NULL AS toast_reloptions "
4531 "WHERE relkind IN ('%c', '%c', '%c') "
4534 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4536 else if (fout->remoteVersion >= 70100)
4538 /* all tables have oids in 7.1 */
4539 appendPQExpBuffer(query,
4540 "SELECT tableoid, oid, relname, relacl, relkind, "
4541 "0::oid AS relnamespace, "
4542 "(%s relowner) AS rolname, "
4543 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4544 "relhasindex, relhasrules, "
4545 "'t'::bool AS relhasoids, "
4546 "0 AS relfrozenxid, "
4549 "'p' AS relpersistence, 't' as relispopulated, "
4551 "NULL AS reloftype, "
4552 "NULL::oid AS owning_tab, "
4553 "NULL::int4 AS owning_col, "
4554 "NULL AS reltablespace, "
4555 "NULL AS reloptions, "
4556 "NULL AS toast_reloptions "
4558 "WHERE relkind IN ('%c', '%c', '%c') "
4561 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4566 * Before 7.1, view relkind was not set to 'v', so we must check if we
4567 * have a view by looking for a rule in pg_rewrite.
4569 appendPQExpBuffer(query,
4571 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4572 "oid, relname, relacl, "
4573 "CASE WHEN relhasrules and relkind = 'r' "
4574 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4575 " r.ev_class = c.oid AND r.ev_type = '1') "
4576 "THEN '%c'::\"char\" "
4577 "ELSE relkind END AS relkind,"
4578 "0::oid AS relnamespace, "
4579 "(%s relowner) AS rolname, "
4580 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4581 "relhasindex, relhasrules, "
4582 "'t'::bool AS relhasoids, "
4583 "0 as relfrozenxid, "
4586 "'p' AS relpersistence, 't' as relispopulated, "
4588 "NULL AS reloftype, "
4589 "NULL::oid AS owning_tab, "
4590 "NULL::int4 AS owning_col, "
4591 "NULL AS reltablespace, "
4592 "NULL AS reloptions, "
4593 "NULL AS toast_reloptions "
4595 "WHERE relkind IN ('%c', '%c') "
4599 RELKIND_RELATION, RELKIND_SEQUENCE);
4602 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4604 ntups = PQntuples(res);
4609 * Extract data from result and lock dumpable tables. We do the locking
4610 * before anything else, to minimize the window wherein a table could
4611 * disappear under us.
4613 * Note that we have to save info about all tables here, even when dumping
4614 * only one, because we don't yet know which tables might be inheritance
4615 * ancestors of the target table.
4617 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4619 i_reltableoid = PQfnumber(res, "tableoid");
4620 i_reloid = PQfnumber(res, "oid");
4621 i_relname = PQfnumber(res, "relname");
4622 i_relnamespace = PQfnumber(res, "relnamespace");
4623 i_relacl = PQfnumber(res, "relacl");
4624 i_relkind = PQfnumber(res, "relkind");
4625 i_rolname = PQfnumber(res, "rolname");
4626 i_relchecks = PQfnumber(res, "relchecks");
4627 i_relhastriggers = PQfnumber(res, "relhastriggers");
4628 i_relhasindex = PQfnumber(res, "relhasindex");
4629 i_relhasrules = PQfnumber(res, "relhasrules");
4630 i_relhasoids = PQfnumber(res, "relhasoids");
4631 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4632 i_toastoid = PQfnumber(res, "toid");
4633 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4634 i_relpersistence = PQfnumber(res, "relpersistence");
4635 i_relispopulated = PQfnumber(res, "relispopulated");
4636 i_relpages = PQfnumber(res, "relpages");
4637 i_owning_tab = PQfnumber(res, "owning_tab");
4638 i_owning_col = PQfnumber(res, "owning_col");
4639 i_reltablespace = PQfnumber(res, "reltablespace");
4640 i_reloptions = PQfnumber(res, "reloptions");
4641 i_checkoption = PQfnumber(res, "checkoption");
4642 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4643 i_reloftype = PQfnumber(res, "reloftype");
4645 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4648 * Arrange to fail instead of waiting forever for a table lock.
4650 * NB: this coding assumes that the only queries issued within the
4651 * following loop are LOCK TABLEs; else the timeout may be undesirably
4652 * applied to other things too.
4654 resetPQExpBuffer(query);
4655 appendPQExpBuffer(query, "SET statement_timeout = ");
4656 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4657 ExecuteSqlStatement(fout, query->data);
4660 for (i = 0; i < ntups; i++)
4662 tblinfo[i].dobj.objType = DO_TABLE;
4663 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4664 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4665 AssignDumpId(&tblinfo[i].dobj);
4666 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4667 tblinfo[i].dobj.namespace =
4669 atooid(PQgetvalue(res, i, i_relnamespace)),
4670 tblinfo[i].dobj.catId.oid);
4671 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4672 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4673 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4674 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4675 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4676 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4677 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4678 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4679 tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
4680 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
4681 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4682 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4683 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4684 if (PQgetisnull(res, i, i_reloftype))
4685 tblinfo[i].reloftype = NULL;
4687 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4688 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4689 if (PQgetisnull(res, i, i_owning_tab))
4691 tblinfo[i].owning_tab = InvalidOid;
4692 tblinfo[i].owning_col = 0;
4696 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4697 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4699 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4700 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4701 if (i_checkoption == -1 || PQgetisnull(res, i, i_checkoption))
4702 tblinfo[i].checkoption = NULL;
4704 tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
4705 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4707 /* other fields were zeroed above */
4710 * Decide whether we want to dump this table.
4712 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4713 tblinfo[i].dobj.dump = false;
4715 selectDumpableTable(&tblinfo[i]);
4716 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4719 * Read-lock target tables to make sure they aren't DROPPED or altered
4720 * in schema before we get around to dumping them.
4722 * Note that we don't explicitly lock parents of the target tables; we
4723 * assume our lock on the child is enough to prevent schema
4724 * alterations to parent tables.
4726 * NOTE: it'd be kinda nice to lock other relations too, not only
4727 * plain tables, but the backend doesn't presently allow that.
4729 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4731 resetPQExpBuffer(query);
4732 appendPQExpBuffer(query,
4733 "LOCK TABLE %s IN ACCESS SHARE MODE",
4734 fmtQualifiedId(fout->remoteVersion,
4735 tblinfo[i].dobj.namespace->dobj.name,
4736 tblinfo[i].dobj.name));
4737 ExecuteSqlStatement(fout, query->data);
4740 /* Emit notice if join for owner failed */
4741 if (strlen(tblinfo[i].rolname) == 0)
4742 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4743 tblinfo[i].dobj.name);
4746 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4748 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4753 destroyPQExpBuffer(query);
4760 * identify owned sequences and mark them as dumpable if owning table is
4762 * We used to do this in getTables(), but it's better to do it after the
4763 * index used by findTableByOid() has been set up.
4766 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4771 * Force sequences that are "owned" by table columns to be dumped whenever
4772 * their owning table is being dumped.
4774 for (i = 0; i < numTables; i++)
4776 TableInfo *seqinfo = &tblinfo[i];
4777 TableInfo *owning_tab;
4779 if (!OidIsValid(seqinfo->owning_tab))
4780 continue; /* not an owned sequence */
4781 if (seqinfo->dobj.dump)
4782 continue; /* no need to search */
4783 owning_tab = findTableByOid(seqinfo->owning_tab);
4784 if (owning_tab && owning_tab->dobj.dump)
4786 seqinfo->interesting = true;
4787 seqinfo->dobj.dump = true;
4794 * read all the inheritance information
4795 * from the system catalogs return them in the InhInfo* structure
4797 * numInherits is set to the number of pairs read in
4800 getInherits(Archive *fout, int *numInherits)
4805 PQExpBuffer query = createPQExpBuffer();
4811 /* Make sure we are in proper schema */
4812 selectSourceSchema(fout, "pg_catalog");
4814 /* find all the inheritance information */
4816 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4818 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4820 ntups = PQntuples(res);
4822 *numInherits = ntups;
4824 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4826 i_inhrelid = PQfnumber(res, "inhrelid");
4827 i_inhparent = PQfnumber(res, "inhparent");
4829 for (i = 0; i < ntups; i++)
4831 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4832 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4837 destroyPQExpBuffer(query);
4844 * get information about every index on a dumpable table
4846 * Note: index data is not returned directly to the caller, but it
4847 * does get entered into the DumpableObject tables.
4850 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4854 PQExpBuffer query = createPQExpBuffer();
4857 ConstraintInfo *constrinfo;
4877 for (i = 0; i < numTables; i++)
4879 TableInfo *tbinfo = &tblinfo[i];
4881 /* Only plain tables and materialized views have indexes. */
4882 if (tbinfo->relkind != RELKIND_RELATION &&
4883 tbinfo->relkind != RELKIND_MATVIEW)
4885 if (!tbinfo->hasindex)
4888 /* Ignore indexes of tables not to be dumped */
4889 if (!tbinfo->dobj.dump)
4893 write_msg(NULL, "reading indexes for table \"%s\"\n",
4896 /* Make sure we are in proper schema so indexdef is right */
4897 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4900 * The point of the messy-looking outer join is to find a constraint
4901 * that is related by an internal dependency link to the index. If we
4902 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4903 * assume an index won't have more than one internal dependency.
4905 * As of 9.0 we don't need to look at pg_depend but can check for a
4906 * match to pg_constraint.conindid. The check on conrelid is
4907 * redundant but useful because that column is indexed while conindid
4910 resetPQExpBuffer(query);
4911 if (fout->remoteVersion >= 90000)
4914 * the test on indisready is necessary in 9.2, and harmless in
4915 * earlier/later versions
4917 appendPQExpBuffer(query,
4918 "SELECT t.tableoid, t.oid, "
4919 "t.relname AS indexname, "
4920 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4921 "t.relnatts AS indnkeys, "
4922 "i.indkey, i.indisclustered, "
4924 "c.contype, c.conname, "
4925 "c.condeferrable, c.condeferred, "
4926 "c.tableoid AS contableoid, "
4928 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4929 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4930 "array_to_string(t.reloptions, ', ') AS options "
4931 "FROM pg_catalog.pg_index i "
4932 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4933 "LEFT JOIN pg_catalog.pg_constraint c "
4934 "ON (i.indrelid = c.conrelid AND "
4935 "i.indexrelid = c.conindid AND "
4936 "c.contype IN ('p','u','x')) "
4937 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4938 "AND i.indisvalid AND i.indisready "
4939 "ORDER BY indexname",
4940 tbinfo->dobj.catId.oid);
4942 else if (fout->remoteVersion >= 80200)
4944 appendPQExpBuffer(query,
4945 "SELECT t.tableoid, t.oid, "
4946 "t.relname AS indexname, "
4947 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4948 "t.relnatts AS indnkeys, "
4949 "i.indkey, i.indisclustered, "
4951 "c.contype, c.conname, "
4952 "c.condeferrable, c.condeferred, "
4953 "c.tableoid AS contableoid, "
4956 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4957 "array_to_string(t.reloptions, ', ') AS options "
4958 "FROM pg_catalog.pg_index i "
4959 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4960 "LEFT JOIN pg_catalog.pg_depend d "
4961 "ON (d.classid = t.tableoid "
4962 "AND d.objid = t.oid "
4963 "AND d.deptype = 'i') "
4964 "LEFT JOIN pg_catalog.pg_constraint c "
4965 "ON (d.refclassid = c.tableoid "
4966 "AND d.refobjid = c.oid) "
4967 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4969 "ORDER BY indexname",
4970 tbinfo->dobj.catId.oid);
4972 else if (fout->remoteVersion >= 80000)
4974 appendPQExpBuffer(query,
4975 "SELECT t.tableoid, t.oid, "
4976 "t.relname AS indexname, "
4977 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4978 "t.relnatts AS indnkeys, "
4979 "i.indkey, i.indisclustered, "
4981 "c.contype, c.conname, "
4982 "c.condeferrable, c.condeferred, "
4983 "c.tableoid AS contableoid, "
4986 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4988 "FROM pg_catalog.pg_index i "
4989 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4990 "LEFT JOIN pg_catalog.pg_depend d "
4991 "ON (d.classid = t.tableoid "
4992 "AND d.objid = t.oid "
4993 "AND d.deptype = 'i') "
4994 "LEFT JOIN pg_catalog.pg_constraint c "
4995 "ON (d.refclassid = c.tableoid "
4996 "AND d.refobjid = c.oid) "
4997 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4998 "ORDER BY indexname",
4999 tbinfo->dobj.catId.oid);
5001 else if (fout->remoteVersion >= 70300)
5003 appendPQExpBuffer(query,
5004 "SELECT t.tableoid, t.oid, "
5005 "t.relname AS indexname, "
5006 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
5007 "t.relnatts AS indnkeys, "
5008 "i.indkey, i.indisclustered, "
5010 "c.contype, c.conname, "
5011 "c.condeferrable, c.condeferred, "
5012 "c.tableoid AS contableoid, "
5015 "NULL AS tablespace, "
5017 "FROM pg_catalog.pg_index i "
5018 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
5019 "LEFT JOIN pg_catalog.pg_depend d "
5020 "ON (d.classid = t.tableoid "
5021 "AND d.objid = t.oid "
5022 "AND d.deptype = 'i') "
5023 "LEFT JOIN pg_catalog.pg_constraint c "
5024 "ON (d.refclassid = c.tableoid "
5025 "AND d.refobjid = c.oid) "
5026 "WHERE i.indrelid = '%u'::pg_catalog.oid "
5027 "ORDER BY indexname",
5028 tbinfo->dobj.catId.oid);
5030 else if (fout->remoteVersion >= 70100)
5032 appendPQExpBuffer(query,
5033 "SELECT t.tableoid, t.oid, "
5034 "t.relname AS indexname, "
5035 "pg_get_indexdef(i.indexrelid) AS indexdef, "
5036 "t.relnatts AS indnkeys, "
5037 "i.indkey, false AS indisclustered, "
5039 "CASE WHEN i.indisprimary THEN 'p'::char "
5040 "ELSE '0'::char END AS contype, "
5041 "t.relname AS conname, "
5042 "false AS condeferrable, "
5043 "false AS condeferred, "
5044 "0::oid AS contableoid, "
5047 "NULL AS tablespace, "
5049 "FROM pg_index i, pg_class t "
5050 "WHERE t.oid = i.indexrelid "
5051 "AND i.indrelid = '%u'::oid "
5052 "ORDER BY indexname",
5053 tbinfo->dobj.catId.oid);
5057 appendPQExpBuffer(query,
5059 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
5061 "t.relname AS indexname, "
5062 "pg_get_indexdef(i.indexrelid) AS indexdef, "
5063 "t.relnatts AS indnkeys, "
5064 "i.indkey, false AS indisclustered, "
5066 "CASE WHEN i.indisprimary THEN 'p'::char "
5067 "ELSE '0'::char END AS contype, "
5068 "t.relname AS conname, "
5069 "false AS condeferrable, "
5070 "false AS condeferred, "
5071 "0::oid AS contableoid, "
5074 "NULL AS tablespace, "
5076 "FROM pg_index i, pg_class t "
5077 "WHERE t.oid = i.indexrelid "
5078 "AND i.indrelid = '%u'::oid "
5079 "ORDER BY indexname",
5080 tbinfo->dobj.catId.oid);
5083 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5085 ntups = PQntuples(res);
5087 i_tableoid = PQfnumber(res, "tableoid");
5088 i_oid = PQfnumber(res, "oid");
5089 i_indexname = PQfnumber(res, "indexname");
5090 i_indexdef = PQfnumber(res, "indexdef");
5091 i_indnkeys = PQfnumber(res, "indnkeys");
5092 i_indkey = PQfnumber(res, "indkey");
5093 i_indisclustered = PQfnumber(res, "indisclustered");
5094 i_relpages = PQfnumber(res, "relpages");
5095 i_contype = PQfnumber(res, "contype");
5096 i_conname = PQfnumber(res, "conname");
5097 i_condeferrable = PQfnumber(res, "condeferrable");
5098 i_condeferred = PQfnumber(res, "condeferred");
5099 i_contableoid = PQfnumber(res, "contableoid");
5100 i_conoid = PQfnumber(res, "conoid");
5101 i_condef = PQfnumber(res, "condef");
5102 i_tablespace = PQfnumber(res, "tablespace");
5103 i_options = PQfnumber(res, "options");
5105 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
5106 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5108 for (j = 0; j < ntups; j++)
5112 indxinfo[j].dobj.objType = DO_INDEX;
5113 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5114 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5115 AssignDumpId(&indxinfo[j].dobj);
5116 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
5117 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5118 indxinfo[j].indextable = tbinfo;
5119 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
5120 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
5121 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
5122 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
5125 * In pre-7.4 releases, indkeys may contain more entries than
5126 * indnkeys says (since indnkeys will be 1 for a functional
5127 * index). We don't actually care about this case since we don't
5128 * examine indkeys except for indexes associated with PRIMARY and
5129 * UNIQUE constraints, which are never functional indexes. But we
5130 * have to allocate enough space to keep parseOidArray from
5133 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
5134 parseOidArray(PQgetvalue(res, j, i_indkey),
5135 indxinfo[j].indkeys, INDEX_MAX_KEYS);
5136 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
5137 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
5138 contype = *(PQgetvalue(res, j, i_contype));
5140 if (contype == 'p' || contype == 'u' || contype == 'x')
5143 * If we found a constraint matching the index, create an
5146 * In a pre-7.3 database, we take this path iff the index was
5147 * marked indisprimary.
5149 constrinfo[j].dobj.objType = DO_CONSTRAINT;
5150 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5151 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5152 AssignDumpId(&constrinfo[j].dobj);
5153 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5154 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5155 constrinfo[j].contable = tbinfo;
5156 constrinfo[j].condomain = NULL;
5157 constrinfo[j].contype = contype;
5159 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5161 constrinfo[j].condef = NULL;
5162 constrinfo[j].confrelid = InvalidOid;
5163 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
5164 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
5165 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
5166 constrinfo[j].conislocal = true;
5167 constrinfo[j].separate = true;
5169 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
5171 /* If pre-7.3 DB, better make sure table comes first */
5172 addObjectDependency(&constrinfo[j].dobj,
5173 tbinfo->dobj.dumpId);
5177 /* Plain secondary index */
5178 indxinfo[j].indexconstraint = 0;
5185 destroyPQExpBuffer(query);
5191 * Get info about constraints on dumpable tables.
5193 * Currently handles foreign keys only.
5194 * Unique and primary key constraints are handled with indexes,
5195 * while check constraints are processed in getTableAttrs().
5198 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
5202 ConstraintInfo *constrinfo;
5212 /* pg_constraint was created in 7.3, so nothing to do if older */
5213 if (fout->remoteVersion < 70300)
5216 query = createPQExpBuffer();
5218 for (i = 0; i < numTables; i++)
5220 TableInfo *tbinfo = &tblinfo[i];
5222 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5226 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
5230 * select table schema to ensure constraint expr is qualified if
5233 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5235 resetPQExpBuffer(query);
5236 appendPQExpBuffer(query,
5237 "SELECT tableoid, oid, conname, confrelid, "
5238 "pg_catalog.pg_get_constraintdef(oid) AS condef "
5239 "FROM pg_catalog.pg_constraint "
5240 "WHERE conrelid = '%u'::pg_catalog.oid "
5241 "AND contype = 'f'",
5242 tbinfo->dobj.catId.oid);
5243 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5245 ntups = PQntuples(res);
5247 i_contableoid = PQfnumber(res, "tableoid");
5248 i_conoid = PQfnumber(res, "oid");
5249 i_conname = PQfnumber(res, "conname");
5250 i_confrelid = PQfnumber(res, "confrelid");
5251 i_condef = PQfnumber(res, "condef");
5253 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5255 for (j = 0; j < ntups; j++)
5257 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
5258 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5259 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5260 AssignDumpId(&constrinfo[j].dobj);
5261 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5262 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5263 constrinfo[j].contable = tbinfo;
5264 constrinfo[j].condomain = NULL;
5265 constrinfo[j].contype = 'f';
5266 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5267 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
5268 constrinfo[j].conindex = 0;
5269 constrinfo[j].condeferrable = false;
5270 constrinfo[j].condeferred = false;
5271 constrinfo[j].conislocal = true;
5272 constrinfo[j].separate = true;
5278 destroyPQExpBuffer(query);
5282 * getDomainConstraints
5284 * Get info about constraints on a domain.
5287 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
5290 ConstraintInfo *constrinfo;
5299 /* pg_constraint was created in 7.3, so nothing to do if older */
5300 if (fout->remoteVersion < 70300)
5304 * select appropriate schema to ensure names in constraint are properly
5307 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
5309 query = createPQExpBuffer();
5311 if (fout->remoteVersion >= 90100)
5312 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5313 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5315 "FROM pg_catalog.pg_constraint "
5316 "WHERE contypid = '%u'::pg_catalog.oid "
5318 tyinfo->dobj.catId.oid);
5320 else if (fout->remoteVersion >= 70400)
5321 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5322 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5323 "true as convalidated "
5324 "FROM pg_catalog.pg_constraint "
5325 "WHERE contypid = '%u'::pg_catalog.oid "
5327 tyinfo->dobj.catId.oid);
5329 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5330 "'CHECK (' || consrc || ')' AS consrc, "
5331 "true as convalidated "
5332 "FROM pg_catalog.pg_constraint "
5333 "WHERE contypid = '%u'::pg_catalog.oid "
5335 tyinfo->dobj.catId.oid);
5337 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5339 ntups = PQntuples(res);
5341 i_tableoid = PQfnumber(res, "tableoid");
5342 i_oid = PQfnumber(res, "oid");
5343 i_conname = PQfnumber(res, "conname");
5344 i_consrc = PQfnumber(res, "consrc");
5346 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5348 tyinfo->nDomChecks = ntups;
5349 tyinfo->domChecks = constrinfo;
5351 for (i = 0; i < ntups; i++)
5353 bool validated = PQgetvalue(res, i, 4)[0] == 't';
5355 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5356 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5357 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5358 AssignDumpId(&constrinfo[i].dobj);
5359 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5360 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5361 constrinfo[i].contable = NULL;
5362 constrinfo[i].condomain = tyinfo;
5363 constrinfo[i].contype = 'c';
5364 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5365 constrinfo[i].confrelid = InvalidOid;
5366 constrinfo[i].conindex = 0;
5367 constrinfo[i].condeferrable = false;
5368 constrinfo[i].condeferred = false;
5369 constrinfo[i].conislocal = true;
5371 constrinfo[i].separate = !validated;
5374 * Make the domain depend on the constraint, ensuring it won't be
5375 * output till any constraint dependencies are OK. If the constraint
5376 * has not been validated, it's going to be dumped after the domain
5377 * anyway, so this doesn't matter.
5380 addObjectDependency(&tyinfo->dobj,
5381 constrinfo[i].dobj.dumpId);
5386 destroyPQExpBuffer(query);
5391 * get basic information about every rule in the system
5393 * numRules is set to the number of rules read in
5396 getRules(Archive *fout, int *numRules)
5401 PQExpBuffer query = createPQExpBuffer();
5411 /* Make sure we are in proper schema */
5412 selectSourceSchema(fout, "pg_catalog");
5414 if (fout->remoteVersion >= 80300)
5416 appendPQExpBuffer(query, "SELECT "
5417 "tableoid, oid, rulename, "
5418 "ev_class AS ruletable, ev_type, is_instead, "
5423 else if (fout->remoteVersion >= 70100)
5425 appendPQExpBuffer(query, "SELECT "
5426 "tableoid, oid, rulename, "
5427 "ev_class AS ruletable, ev_type, is_instead, "
5428 "'O'::char AS ev_enabled "
5434 appendPQExpBuffer(query, "SELECT "
5435 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5437 "ev_class AS ruletable, ev_type, is_instead, "
5438 "'O'::char AS ev_enabled "
5443 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5445 ntups = PQntuples(res);
5449 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5451 i_tableoid = PQfnumber(res, "tableoid");
5452 i_oid = PQfnumber(res, "oid");
5453 i_rulename = PQfnumber(res, "rulename");
5454 i_ruletable = PQfnumber(res, "ruletable");
5455 i_ev_type = PQfnumber(res, "ev_type");
5456 i_is_instead = PQfnumber(res, "is_instead");
5457 i_ev_enabled = PQfnumber(res, "ev_enabled");
5459 for (i = 0; i < ntups; i++)
5463 ruleinfo[i].dobj.objType = DO_RULE;
5464 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5465 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5466 AssignDumpId(&ruleinfo[i].dobj);
5467 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5468 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5469 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5470 if (ruleinfo[i].ruletable == NULL)
5471 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5472 ruletableoid, ruleinfo[i].dobj.catId.oid);
5473 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5474 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5475 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5476 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5477 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5478 if (ruleinfo[i].ruletable)
5481 * If the table is a view or materialized view, force its ON
5482 * SELECT rule to be sorted before the view itself --- this
5483 * ensures that any dependencies for the rule affect the table's
5484 * positioning. Other rules are forced to appear after their
5487 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
5488 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
5489 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5491 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5492 ruleinfo[i].dobj.dumpId);
5493 /* We'll merge the rule into CREATE VIEW, if possible */
5494 ruleinfo[i].separate = false;
5498 addObjectDependency(&ruleinfo[i].dobj,
5499 ruleinfo[i].ruletable->dobj.dumpId);
5500 ruleinfo[i].separate = true;
5504 ruleinfo[i].separate = true;
5507 * If we're forced to break a dependency loop by dumping a view as a
5508 * table and separate _RETURN rule, we'll move the view's reloptions
5509 * to the rule. (This is necessary because tables and views have
5510 * different valid reloptions, so we can't apply the options until the
5511 * backend knows it's a view.) Otherwise the rule's reloptions stay
5514 ruleinfo[i].reloptions = NULL;
5519 destroyPQExpBuffer(query);
5526 * get information about every trigger on a dumpable table
5528 * Note: trigger data is not returned directly to the caller, but it
5529 * does get entered into the DumpableObject tables.
5532 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5536 PQExpBuffer query = createPQExpBuffer();
5538 TriggerInfo *tginfo;
5556 for (i = 0; i < numTables; i++)
5558 TableInfo *tbinfo = &tblinfo[i];
5560 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5564 write_msg(NULL, "reading triggers for table \"%s\"\n",
5568 * select table schema to ensure regproc name is qualified if needed
5570 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5572 resetPQExpBuffer(query);
5573 if (fout->remoteVersion >= 90000)
5576 * NB: think not to use pretty=true in pg_get_triggerdef. It
5577 * could result in non-forward-compatible dumps of WHEN clauses
5578 * due to under-parenthesization.
5580 appendPQExpBuffer(query,
5582 "tgfoid::pg_catalog.regproc AS tgfname, "
5583 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5584 "tgenabled, tableoid, oid "
5585 "FROM pg_catalog.pg_trigger t "
5586 "WHERE tgrelid = '%u'::pg_catalog.oid "
5587 "AND NOT tgisinternal",
5588 tbinfo->dobj.catId.oid);
5590 else if (fout->remoteVersion >= 80300)
5593 * We ignore triggers that are tied to a foreign-key constraint
5595 appendPQExpBuffer(query,
5597 "tgfoid::pg_catalog.regproc AS tgfname, "
5598 "tgtype, tgnargs, tgargs, tgenabled, "
5599 "tgisconstraint, tgconstrname, tgdeferrable, "
5600 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5601 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5602 "FROM pg_catalog.pg_trigger t "
5603 "WHERE tgrelid = '%u'::pg_catalog.oid "
5604 "AND tgconstraint = 0",
5605 tbinfo->dobj.catId.oid);
5607 else if (fout->remoteVersion >= 70300)
5610 * We ignore triggers that are tied to a foreign-key constraint,
5611 * but in these versions we have to grovel through pg_constraint
5614 appendPQExpBuffer(query,
5616 "tgfoid::pg_catalog.regproc AS tgfname, "
5617 "tgtype, tgnargs, tgargs, tgenabled, "
5618 "tgisconstraint, tgconstrname, tgdeferrable, "
5619 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5620 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5621 "FROM pg_catalog.pg_trigger t "
5622 "WHERE tgrelid = '%u'::pg_catalog.oid "
5623 "AND (NOT tgisconstraint "
5625 " (SELECT 1 FROM pg_catalog.pg_depend d "
5626 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5627 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5628 tbinfo->dobj.catId.oid);
5630 else if (fout->remoteVersion >= 70100)
5632 appendPQExpBuffer(query,
5633 "SELECT tgname, tgfoid::regproc AS tgfname, "
5634 "tgtype, tgnargs, tgargs, tgenabled, "
5635 "tgisconstraint, tgconstrname, tgdeferrable, "
5636 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5637 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5638 " AS tgconstrrelname "
5640 "WHERE tgrelid = '%u'::oid",
5641 tbinfo->dobj.catId.oid);
5645 appendPQExpBuffer(query,
5646 "SELECT tgname, tgfoid::regproc AS tgfname, "
5647 "tgtype, tgnargs, tgargs, tgenabled, "
5648 "tgisconstraint, tgconstrname, tgdeferrable, "
5649 "tgconstrrelid, tginitdeferred, "
5650 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5652 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5653 " AS tgconstrrelname "
5655 "WHERE tgrelid = '%u'::oid",
5656 tbinfo->dobj.catId.oid);
5658 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5660 ntups = PQntuples(res);
5662 i_tableoid = PQfnumber(res, "tableoid");
5663 i_oid = PQfnumber(res, "oid");
5664 i_tgname = PQfnumber(res, "tgname");
5665 i_tgfname = PQfnumber(res, "tgfname");
5666 i_tgtype = PQfnumber(res, "tgtype");
5667 i_tgnargs = PQfnumber(res, "tgnargs");
5668 i_tgargs = PQfnumber(res, "tgargs");
5669 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5670 i_tgconstrname = PQfnumber(res, "tgconstrname");
5671 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5672 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5673 i_tgenabled = PQfnumber(res, "tgenabled");
5674 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5675 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5676 i_tgdef = PQfnumber(res, "tgdef");
5678 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5680 for (j = 0; j < ntups; j++)
5682 tginfo[j].dobj.objType = DO_TRIGGER;
5683 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5684 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5685 AssignDumpId(&tginfo[j].dobj);
5686 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5687 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5688 tginfo[j].tgtable = tbinfo;
5689 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5692 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5694 /* remaining fields are not valid if we have tgdef */
5695 tginfo[j].tgfname = NULL;
5696 tginfo[j].tgtype = 0;
5697 tginfo[j].tgnargs = 0;
5698 tginfo[j].tgargs = NULL;
5699 tginfo[j].tgisconstraint = false;
5700 tginfo[j].tgdeferrable = false;
5701 tginfo[j].tginitdeferred = false;
5702 tginfo[j].tgconstrname = NULL;
5703 tginfo[j].tgconstrrelid = InvalidOid;
5704 tginfo[j].tgconstrrelname = NULL;
5708 tginfo[j].tgdef = NULL;
5710 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5711 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5712 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5713 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5714 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5715 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5716 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5718 if (tginfo[j].tgisconstraint)
5720 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5721 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5722 if (OidIsValid(tginfo[j].tgconstrrelid))
5724 if (PQgetisnull(res, j, i_tgconstrrelname))
5725 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5726 tginfo[j].dobj.name,
5728 tginfo[j].tgconstrrelid);
5729 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5732 tginfo[j].tgconstrrelname = NULL;
5736 tginfo[j].tgconstrname = NULL;
5737 tginfo[j].tgconstrrelid = InvalidOid;
5738 tginfo[j].tgconstrrelname = NULL;
5746 destroyPQExpBuffer(query);
5751 * get information about event triggers
5754 getEventTriggers(Archive *fout, int *numEventTriggers)
5759 EventTriggerInfo *evtinfo;
5770 /* Before 9.3, there are no event triggers */
5771 if (fout->remoteVersion < 90300)
5773 *numEventTriggers = 0;
5777 query = createPQExpBuffer();
5779 /* Make sure we are in proper schema */
5780 selectSourceSchema(fout, "pg_catalog");
5782 appendPQExpBuffer(query,
5783 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5784 "evtevent, (%s evtowner) AS evtowner, "
5785 "array_to_string(array("
5786 "select quote_literal(x) "
5787 " from unnest(evttags) as t(x)), ', ') as evttags, "
5788 "e.evtfoid::regproc as evtfname "
5789 "FROM pg_event_trigger e "
5793 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5795 ntups = PQntuples(res);
5797 *numEventTriggers = ntups;
5799 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5801 i_tableoid = PQfnumber(res, "tableoid");
5802 i_oid = PQfnumber(res, "oid");
5803 i_evtname = PQfnumber(res, "evtname");
5804 i_evtevent = PQfnumber(res, "evtevent");
5805 i_evtowner = PQfnumber(res, "evtowner");
5806 i_evttags = PQfnumber(res, "evttags");
5807 i_evtfname = PQfnumber(res, "evtfname");
5808 i_evtenabled = PQfnumber(res, "evtenabled");
5810 for (i = 0; i < ntups; i++)
5812 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5813 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5814 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5815 AssignDumpId(&evtinfo[i].dobj);
5816 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5817 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5818 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5819 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5820 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5821 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5822 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5827 destroyPQExpBuffer(query);
5834 * get basic information about every procedural language in the system
5836 * numProcLangs is set to the number of langs read in
5838 * NB: this must run after getFuncs() because we assume we can do
5842 getProcLangs(Archive *fout, int *numProcLangs)
5847 PQExpBuffer query = createPQExpBuffer();
5848 ProcLangInfo *planginfo;
5853 int i_lanplcallfoid;
5859 /* Make sure we are in proper schema */
5860 selectSourceSchema(fout, "pg_catalog");
5862 if (fout->remoteVersion >= 90000)
5864 /* pg_language has a laninline column */
5865 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5866 "lanname, lanpltrusted, lanplcallfoid, "
5867 "laninline, lanvalidator, lanacl, "
5868 "(%s lanowner) AS lanowner "
5874 else if (fout->remoteVersion >= 80300)
5876 /* pg_language has a lanowner column */
5877 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5878 "lanname, lanpltrusted, lanplcallfoid, "
5879 "lanvalidator, lanacl, "
5880 "(%s lanowner) AS lanowner "
5886 else if (fout->remoteVersion >= 80100)
5888 /* Languages are owned by the bootstrap superuser, OID 10 */
5889 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5890 "(%s '10') AS lanowner "
5896 else if (fout->remoteVersion >= 70400)
5898 /* Languages are owned by the bootstrap superuser, sysid 1 */
5899 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5900 "(%s '1') AS lanowner "
5906 else if (fout->remoteVersion >= 70100)
5908 /* No clear notion of an owner at all before 7.4 ... */
5909 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5915 appendPQExpBuffer(query, "SELECT "
5916 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5917 "oid, * FROM pg_language "
5922 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5924 ntups = PQntuples(res);
5926 *numProcLangs = ntups;
5928 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5930 i_tableoid = PQfnumber(res, "tableoid");
5931 i_oid = PQfnumber(res, "oid");
5932 i_lanname = PQfnumber(res, "lanname");
5933 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5934 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5935 /* these may fail and return -1: */
5936 i_laninline = PQfnumber(res, "laninline");
5937 i_lanvalidator = PQfnumber(res, "lanvalidator");
5938 i_lanacl = PQfnumber(res, "lanacl");
5939 i_lanowner = PQfnumber(res, "lanowner");
5941 for (i = 0; i < ntups; i++)
5943 planginfo[i].dobj.objType = DO_PROCLANG;
5944 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5945 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5946 AssignDumpId(&planginfo[i].dobj);
5948 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5949 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5950 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5951 if (i_laninline >= 0)
5952 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5954 planginfo[i].laninline = InvalidOid;
5955 if (i_lanvalidator >= 0)
5956 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5958 planginfo[i].lanvalidator = InvalidOid;
5960 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5962 planginfo[i].lanacl = pg_strdup("{=U}");
5963 if (i_lanowner >= 0)
5964 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5966 planginfo[i].lanowner = pg_strdup("");
5968 if (fout->remoteVersion < 70300)
5971 * We need to make a dependency to ensure the function will be
5972 * dumped first. (In 7.3 and later the regular dependency
5973 * mechanism will handle this for us.)
5975 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5978 addObjectDependency(&planginfo[i].dobj,
5979 funcInfo->dobj.dumpId);
5985 destroyPQExpBuffer(query);
5992 * get basic information about every cast in the system
5994 * numCasts is set to the number of casts read in
5997 getCasts(Archive *fout, int *numCasts)
6002 PQExpBuffer query = createPQExpBuffer();
6012 /* Make sure we are in proper schema */
6013 selectSourceSchema(fout, "pg_catalog");
6015 if (fout->remoteVersion >= 80400)
6017 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6018 "castsource, casttarget, castfunc, castcontext, "
6020 "FROM pg_cast ORDER BY 3,4");
6022 else if (fout->remoteVersion >= 70300)
6024 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6025 "castsource, casttarget, castfunc, castcontext, "
6026 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
6027 "FROM pg_cast ORDER BY 3,4");
6031 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
6032 "t1.oid AS castsource, t2.oid AS casttarget, "
6033 "p.oid AS castfunc, 'e' AS castcontext, "
6034 "'f' AS castmethod "
6035 "FROM pg_type t1, pg_type t2, pg_proc p "
6036 "WHERE p.pronargs = 1 AND "
6037 "p.proargtypes[0] = t1.oid AND "
6038 "p.prorettype = t2.oid AND p.proname = t2.typname "
6042 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6044 ntups = PQntuples(res);
6048 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
6050 i_tableoid = PQfnumber(res, "tableoid");
6051 i_oid = PQfnumber(res, "oid");
6052 i_castsource = PQfnumber(res, "castsource");
6053 i_casttarget = PQfnumber(res, "casttarget");
6054 i_castfunc = PQfnumber(res, "castfunc");
6055 i_castcontext = PQfnumber(res, "castcontext");
6056 i_castmethod = PQfnumber(res, "castmethod");
6058 for (i = 0; i < ntups; i++)
6060 PQExpBufferData namebuf;
6061 TypeInfo *sTypeInfo;
6062 TypeInfo *tTypeInfo;
6064 castinfo[i].dobj.objType = DO_CAST;
6065 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6066 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6067 AssignDumpId(&castinfo[i].dobj);
6068 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
6069 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
6070 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
6071 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
6072 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
6075 * Try to name cast as concatenation of typnames. This is only used
6076 * for purposes of sorting. If we fail to find either type, the name
6077 * will be an empty string.
6079 initPQExpBuffer(&namebuf);
6080 sTypeInfo = findTypeByOid(castinfo[i].castsource);
6081 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
6082 if (sTypeInfo && tTypeInfo)
6083 appendPQExpBuffer(&namebuf, "%s %s",
6084 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
6085 castinfo[i].dobj.name = namebuf.data;
6087 if (OidIsValid(castinfo[i].castfunc))
6090 * We need to make a dependency to ensure the function will be
6091 * dumped first. (In 7.3 and later the regular dependency
6092 * mechanism will handle this for us.)
6096 funcInfo = findFuncByOid(castinfo[i].castfunc);
6098 addObjectDependency(&castinfo[i].dobj,
6099 funcInfo->dobj.dumpId);
6105 destroyPQExpBuffer(query);
6112 * for each interesting table, read info about its attributes
6113 * (names, types, default values, CHECK constraints, etc)
6115 * This is implemented in a very inefficient way right now, looping
6116 * through the tblinfo and doing a join per table to find the attrs and their
6117 * types. However, because we want type names and so forth to be named
6118 * relative to the schema of each table, we couldn't do it in just one
6119 * query. (Maybe one query per schema?)
6124 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
6128 PQExpBuffer q = createPQExpBuffer();
6133 int i_attstattarget;
6144 int i_attfdwoptions;
6149 for (i = 0; i < numTables; i++)
6151 TableInfo *tbinfo = &tblinfo[i];
6153 /* Don't bother to collect info for sequences */
6154 if (tbinfo->relkind == RELKIND_SEQUENCE)
6157 /* Don't bother with uninteresting tables, either */
6158 if (!tbinfo->interesting)
6162 * Make sure we are in proper schema for this table; this allows
6163 * correct retrieval of formatted type names and default exprs
6165 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6167 /* find all the user attributes and their types */
6170 * we must read the attribute names in attribute number order! because
6171 * we will use the attnum to index into the attnames array later. We
6172 * actually ask to order by "attrelid, attnum" because (at least up to
6173 * 7.3) the planner is not smart enough to realize it needn't re-sort
6174 * the output of an indexscan on pg_attribute_relid_attnum_index.
6177 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
6180 resetPQExpBuffer(q);
6182 if (fout->remoteVersion >= 90200)
6185 * attfdwoptions is new in 9.2.
6187 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6188 "a.attstattarget, a.attstorage, t.typstorage, "
6189 "a.attnotnull, a.atthasdef, a.attisdropped, "
6190 "a.attlen, a.attalign, a.attislocal, "
6191 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6192 "array_to_string(a.attoptions, ', ') AS attoptions, "
6193 "CASE WHEN a.attcollation <> t.typcollation "
6194 "THEN a.attcollation ELSE 0 END AS attcollation, "
6195 "pg_catalog.array_to_string(ARRAY("
6196 "SELECT pg_catalog.quote_ident(option_name) || "
6197 "' ' || pg_catalog.quote_literal(option_value) "
6198 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
6199 "ORDER BY option_name"
6200 "), E',\n ') AS attfdwoptions "
6201 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6202 "ON a.atttypid = t.oid "
6203 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6204 "AND a.attnum > 0::pg_catalog.int2 "
6205 "ORDER BY a.attrelid, a.attnum",
6206 tbinfo->dobj.catId.oid);
6208 else if (fout->remoteVersion >= 90100)
6211 * attcollation is new in 9.1. Since we only want to dump COLLATE
6212 * clauses for attributes whose collation is different from their
6213 * type's default, we use a CASE here to suppress uninteresting
6214 * attcollations cheaply.
6216 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6217 "a.attstattarget, a.attstorage, t.typstorage, "
6218 "a.attnotnull, a.atthasdef, a.attisdropped, "
6219 "a.attlen, a.attalign, a.attislocal, "
6220 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6221 "array_to_string(a.attoptions, ', ') AS attoptions, "
6222 "CASE WHEN a.attcollation <> t.typcollation "
6223 "THEN a.attcollation ELSE 0 END AS attcollation, "
6224 "NULL AS attfdwoptions "
6225 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6226 "ON a.atttypid = t.oid "
6227 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6228 "AND a.attnum > 0::pg_catalog.int2 "
6229 "ORDER BY a.attrelid, a.attnum",
6230 tbinfo->dobj.catId.oid);
6232 else if (fout->remoteVersion >= 90000)
6234 /* attoptions is new in 9.0 */
6235 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6236 "a.attstattarget, a.attstorage, t.typstorage, "
6237 "a.attnotnull, a.atthasdef, a.attisdropped, "
6238 "a.attlen, a.attalign, a.attislocal, "
6239 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6240 "array_to_string(a.attoptions, ', ') AS attoptions, "
6241 "0 AS attcollation, "
6242 "NULL AS attfdwoptions "
6243 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6244 "ON a.atttypid = t.oid "
6245 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6246 "AND a.attnum > 0::pg_catalog.int2 "
6247 "ORDER BY a.attrelid, a.attnum",
6248 tbinfo->dobj.catId.oid);
6250 else if (fout->remoteVersion >= 70300)
6252 /* need left join here to not fail on dropped columns ... */
6253 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6254 "a.attstattarget, a.attstorage, t.typstorage, "
6255 "a.attnotnull, a.atthasdef, a.attisdropped, "
6256 "a.attlen, a.attalign, a.attislocal, "
6257 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6258 "'' AS attoptions, 0 AS attcollation, "
6259 "NULL AS attfdwoptions "
6260 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6261 "ON a.atttypid = t.oid "
6262 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6263 "AND a.attnum > 0::pg_catalog.int2 "
6264 "ORDER BY a.attrelid, a.attnum",
6265 tbinfo->dobj.catId.oid);
6267 else if (fout->remoteVersion >= 70100)
6270 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
6271 * we don't dump it because we can't tell whether it's been
6272 * explicitly set or was just a default.
6274 * attislocal doesn't exist before 7.3, either; in older databases
6275 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
6277 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6278 "-1 AS attstattarget, a.attstorage, "
6279 "t.typstorage, a.attnotnull, a.atthasdef, "
6280 "false AS attisdropped, a.attlen, "
6281 "a.attalign, true AS attislocal, "
6282 "format_type(t.oid,a.atttypmod) AS atttypname, "
6283 "'' AS attoptions, 0 AS attcollation, "
6284 "NULL AS attfdwoptions "
6285 "FROM pg_attribute a LEFT JOIN pg_type t "
6286 "ON a.atttypid = t.oid "
6287 "WHERE a.attrelid = '%u'::oid "
6288 "AND a.attnum > 0::int2 "
6289 "ORDER BY a.attrelid, a.attnum",
6290 tbinfo->dobj.catId.oid);
6294 /* format_type not available before 7.1 */
6295 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
6296 "-1 AS attstattarget, "
6297 "attstorage, attstorage AS typstorage, "
6298 "attnotnull, atthasdef, false AS attisdropped, "
6299 "attlen, attalign, "
6300 "true AS attislocal, "
6301 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
6302 "'' AS attoptions, 0 AS attcollation, "
6303 "NULL AS attfdwoptions "
6304 "FROM pg_attribute a "
6305 "WHERE attrelid = '%u'::oid "
6306 "AND attnum > 0::int2 "
6307 "ORDER BY attrelid, attnum",
6308 tbinfo->dobj.catId.oid);
6311 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6313 ntups = PQntuples(res);
6315 i_attnum = PQfnumber(res, "attnum");
6316 i_attname = PQfnumber(res, "attname");
6317 i_atttypname = PQfnumber(res, "atttypname");
6318 i_atttypmod = PQfnumber(res, "atttypmod");
6319 i_attstattarget = PQfnumber(res, "attstattarget");
6320 i_attstorage = PQfnumber(res, "attstorage");
6321 i_typstorage = PQfnumber(res, "typstorage");
6322 i_attnotnull = PQfnumber(res, "attnotnull");
6323 i_atthasdef = PQfnumber(res, "atthasdef");
6324 i_attisdropped = PQfnumber(res, "attisdropped");
6325 i_attlen = PQfnumber(res, "attlen");
6326 i_attalign = PQfnumber(res, "attalign");
6327 i_attislocal = PQfnumber(res, "attislocal");
6328 i_attoptions = PQfnumber(res, "attoptions");
6329 i_attcollation = PQfnumber(res, "attcollation");
6330 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
6332 tbinfo->numatts = ntups;
6333 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
6334 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
6335 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
6336 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
6337 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
6338 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
6339 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
6340 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
6341 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
6342 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
6343 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
6344 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
6345 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
6346 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
6347 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
6348 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
6349 hasdefaults = false;
6351 for (j = 0; j < ntups; j++)
6353 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
6355 "invalid column numbering in table \"%s\"\n",
6357 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6358 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6359 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6360 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6361 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6362 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6363 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6364 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6365 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6366 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6367 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6368 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6369 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6370 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6371 tbinfo->attrdefs[j] = NULL; /* fix below */
6372 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6374 /* these flags will be set in flagInhAttrs() */
6375 tbinfo->inhNotNull[j] = false;
6381 * Get info about column defaults
6385 AttrDefInfo *attrdefs;
6389 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6392 resetPQExpBuffer(q);
6393 if (fout->remoteVersion >= 70300)
6395 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6396 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6397 "FROM pg_catalog.pg_attrdef "
6398 "WHERE adrelid = '%u'::pg_catalog.oid",
6399 tbinfo->dobj.catId.oid);
6401 else if (fout->remoteVersion >= 70200)
6403 /* 7.2 did not have OIDs in pg_attrdef */
6404 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6405 "pg_get_expr(adbin, adrelid) AS adsrc "
6407 "WHERE adrelid = '%u'::oid",
6408 tbinfo->dobj.catId.oid);
6410 else if (fout->remoteVersion >= 70100)
6412 /* no pg_get_expr, so must rely on adsrc */
6413 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6415 "WHERE adrelid = '%u'::oid",
6416 tbinfo->dobj.catId.oid);
6420 /* no pg_get_expr, no tableoid either */
6421 appendPQExpBuffer(q, "SELECT "
6422 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6423 "oid, adnum, adsrc "
6425 "WHERE adrelid = '%u'::oid",
6426 tbinfo->dobj.catId.oid);
6428 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6430 numDefaults = PQntuples(res);
6431 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6433 for (j = 0; j < numDefaults; j++)
6437 adnum = atoi(PQgetvalue(res, j, 2));
6439 if (adnum <= 0 || adnum > ntups)
6441 "invalid adnum value %d for table \"%s\"\n",
6442 adnum, tbinfo->dobj.name);
6445 * dropped columns shouldn't have defaults, but just in case,
6448 if (tbinfo->attisdropped[adnum - 1])
6451 attrdefs[j].dobj.objType = DO_ATTRDEF;
6452 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6453 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6454 AssignDumpId(&attrdefs[j].dobj);
6455 attrdefs[j].adtable = tbinfo;
6456 attrdefs[j].adnum = adnum;
6457 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6459 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6460 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6462 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6465 * Defaults on a VIEW must always be dumped as separate ALTER
6466 * TABLE commands. Defaults on regular tables are dumped as
6467 * part of the CREATE TABLE if possible, which it won't be if
6468 * the column is not going to be emitted explicitly.
6470 if (tbinfo->relkind == RELKIND_VIEW)
6472 attrdefs[j].separate = true;
6473 /* needed in case pre-7.3 DB: */
6474 addObjectDependency(&attrdefs[j].dobj,
6475 tbinfo->dobj.dumpId);
6477 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6479 /* column will be suppressed, print default separately */
6480 attrdefs[j].separate = true;
6481 /* needed in case pre-7.3 DB: */
6482 addObjectDependency(&attrdefs[j].dobj,
6483 tbinfo->dobj.dumpId);
6487 attrdefs[j].separate = false;
6490 * Mark the default as needing to appear before the table,
6491 * so that any dependencies it has must be emitted before
6492 * the CREATE TABLE. If this is not possible, we'll
6493 * change to "separate" mode while sorting dependencies.
6495 addObjectDependency(&tbinfo->dobj,
6496 attrdefs[j].dobj.dumpId);
6499 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6505 * Get info about table CHECK constraints
6507 if (tbinfo->ncheck > 0)
6509 ConstraintInfo *constrs;
6513 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6516 resetPQExpBuffer(q);
6517 if (fout->remoteVersion >= 90200)
6520 * convalidated is new in 9.2 (actually, it is there in 9.1,
6521 * but it wasn't ever false for check constraints until 9.2).
6523 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6524 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6525 "conislocal, convalidated "
6526 "FROM pg_catalog.pg_constraint "
6527 "WHERE conrelid = '%u'::pg_catalog.oid "
6528 " AND contype = 'c' "
6530 tbinfo->dobj.catId.oid);
6532 else if (fout->remoteVersion >= 80400)
6534 /* conislocal is new in 8.4 */
6535 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6536 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6537 "conislocal, true AS convalidated "
6538 "FROM pg_catalog.pg_constraint "
6539 "WHERE conrelid = '%u'::pg_catalog.oid "
6540 " AND contype = 'c' "
6542 tbinfo->dobj.catId.oid);
6544 else if (fout->remoteVersion >= 70400)
6546 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6547 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6548 "true AS conislocal, true AS convalidated "
6549 "FROM pg_catalog.pg_constraint "
6550 "WHERE conrelid = '%u'::pg_catalog.oid "
6551 " AND contype = 'c' "
6553 tbinfo->dobj.catId.oid);
6555 else if (fout->remoteVersion >= 70300)
6557 /* no pg_get_constraintdef, must use consrc */
6558 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6559 "'CHECK (' || consrc || ')' AS consrc, "
6560 "true AS conislocal, true AS convalidated "
6561 "FROM pg_catalog.pg_constraint "
6562 "WHERE conrelid = '%u'::pg_catalog.oid "
6563 " AND contype = 'c' "
6565 tbinfo->dobj.catId.oid);
6567 else if (fout->remoteVersion >= 70200)
6569 /* 7.2 did not have OIDs in pg_relcheck */
6570 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6571 "rcname AS conname, "
6572 "'CHECK (' || rcsrc || ')' AS consrc, "
6573 "true AS conislocal, true AS convalidated "
6575 "WHERE rcrelid = '%u'::oid "
6577 tbinfo->dobj.catId.oid);
6579 else if (fout->remoteVersion >= 70100)
6581 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6582 "rcname AS conname, "
6583 "'CHECK (' || rcsrc || ')' AS consrc, "
6584 "true AS conislocal, true AS convalidated "
6586 "WHERE rcrelid = '%u'::oid "
6588 tbinfo->dobj.catId.oid);
6592 /* no tableoid in 7.0 */
6593 appendPQExpBuffer(q, "SELECT "
6594 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6595 "oid, rcname AS conname, "
6596 "'CHECK (' || rcsrc || ')' AS consrc, "
6597 "true AS conislocal, true AS convalidated "
6599 "WHERE rcrelid = '%u'::oid "
6601 tbinfo->dobj.catId.oid);
6603 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6605 numConstrs = PQntuples(res);
6606 if (numConstrs != tbinfo->ncheck)
6608 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6609 "expected %d check constraints on table \"%s\" but found %d\n",
6611 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6612 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6616 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6617 tbinfo->checkexprs = constrs;
6619 for (j = 0; j < numConstrs; j++)
6621 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6623 constrs[j].dobj.objType = DO_CONSTRAINT;
6624 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6625 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6626 AssignDumpId(&constrs[j].dobj);
6627 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6628 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6629 constrs[j].contable = tbinfo;
6630 constrs[j].condomain = NULL;
6631 constrs[j].contype = 'c';
6632 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6633 constrs[j].confrelid = InvalidOid;
6634 constrs[j].conindex = 0;
6635 constrs[j].condeferrable = false;
6636 constrs[j].condeferred = false;
6637 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6640 * An unvalidated constraint needs to be dumped separately, so
6641 * that potentially-violating existing data is loaded before
6644 constrs[j].separate = !validated;
6646 constrs[j].dobj.dump = tbinfo->dobj.dump;
6649 * Mark the constraint as needing to appear before the table
6650 * --- this is so that any other dependencies of the
6651 * constraint will be emitted before we try to create the
6652 * table. If the constraint is to be dumped separately, it
6653 * will be dumped after data is loaded anyway, so don't do it.
6654 * (There's an automatic dependency in the opposite direction
6655 * anyway, so don't need to add one manually here.)
6657 if (!constrs[j].separate)
6658 addObjectDependency(&tbinfo->dobj,
6659 constrs[j].dobj.dumpId);
6662 * If the constraint is inherited, this will be detected later
6663 * (in pre-8.4 databases). We also detect later if the
6664 * constraint must be split out from the table definition.
6671 destroyPQExpBuffer(q);
6675 * Test whether a column should be printed as part of table's CREATE TABLE.
6676 * Column number is zero-based.
6678 * Normally this is always true, but it's false for dropped columns, as well
6679 * as those that were inherited without any local definition. (If we print
6680 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6681 * However, in binary_upgrade mode, we must print all such columns anyway and
6682 * fix the attislocal/attisdropped state later, so as to keep control of the
6683 * physical column order.
6685 * This function exists because there are scattered nonobvious places that
6686 * must be kept in sync with this decision.
6689 shouldPrintColumn(TableInfo *tbinfo, int colno)
6693 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6699 * read all text search parsers in the system catalogs and return them
6700 * in the TSParserInfo* structure
6702 * numTSParsers is set to the number of parsers read in
6705 getTSParsers(Archive *fout, int *numTSParsers)
6711 TSParserInfo *prsinfo;
6722 /* Before 8.3, there is no built-in text search support */
6723 if (fout->remoteVersion < 80300)
6729 query = createPQExpBuffer();
6732 * find all text search objects, including builtin ones; we filter out
6733 * system-defined objects at dump-out time.
6736 /* Make sure we are in proper schema */
6737 selectSourceSchema(fout, "pg_catalog");
6739 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6740 "prsstart::oid, prstoken::oid, "
6741 "prsend::oid, prsheadline::oid, prslextype::oid "
6742 "FROM pg_ts_parser");
6744 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6746 ntups = PQntuples(res);
6747 *numTSParsers = ntups;
6749 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6751 i_tableoid = PQfnumber(res, "tableoid");
6752 i_oid = PQfnumber(res, "oid");
6753 i_prsname = PQfnumber(res, "prsname");
6754 i_prsnamespace = PQfnumber(res, "prsnamespace");
6755 i_prsstart = PQfnumber(res, "prsstart");
6756 i_prstoken = PQfnumber(res, "prstoken");
6757 i_prsend = PQfnumber(res, "prsend");
6758 i_prsheadline = PQfnumber(res, "prsheadline");
6759 i_prslextype = PQfnumber(res, "prslextype");
6761 for (i = 0; i < ntups; i++)
6763 prsinfo[i].dobj.objType = DO_TSPARSER;
6764 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6765 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6766 AssignDumpId(&prsinfo[i].dobj);
6767 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6768 prsinfo[i].dobj.namespace =
6770 atooid(PQgetvalue(res, i, i_prsnamespace)),
6771 prsinfo[i].dobj.catId.oid);
6772 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6773 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6774 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6775 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6776 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6778 /* Decide whether we want to dump it */
6779 selectDumpableObject(&(prsinfo[i].dobj));
6784 destroyPQExpBuffer(query);
6790 * getTSDictionaries:
6791 * read all text search dictionaries in the system catalogs and return them
6792 * in the TSDictInfo* structure
6794 * numTSDicts is set to the number of dictionaries read in
6797 getTSDictionaries(Archive *fout, int *numTSDicts)
6803 TSDictInfo *dictinfo;
6807 int i_dictnamespace;
6810 int i_dictinitoption;
6812 /* Before 8.3, there is no built-in text search support */
6813 if (fout->remoteVersion < 80300)
6819 query = createPQExpBuffer();
6821 /* Make sure we are in proper schema */
6822 selectSourceSchema(fout, "pg_catalog");
6824 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6825 "dictnamespace, (%s dictowner) AS rolname, "
6826 "dicttemplate, dictinitoption "
6830 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6832 ntups = PQntuples(res);
6833 *numTSDicts = ntups;
6835 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6837 i_tableoid = PQfnumber(res, "tableoid");
6838 i_oid = PQfnumber(res, "oid");
6839 i_dictname = PQfnumber(res, "dictname");
6840 i_dictnamespace = PQfnumber(res, "dictnamespace");
6841 i_rolname = PQfnumber(res, "rolname");
6842 i_dictinitoption = PQfnumber(res, "dictinitoption");
6843 i_dicttemplate = PQfnumber(res, "dicttemplate");
6845 for (i = 0; i < ntups; i++)
6847 dictinfo[i].dobj.objType = DO_TSDICT;
6848 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6849 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6850 AssignDumpId(&dictinfo[i].dobj);
6851 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6852 dictinfo[i].dobj.namespace =
6854 atooid(PQgetvalue(res, i, i_dictnamespace)),
6855 dictinfo[i].dobj.catId.oid);
6856 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6857 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6858 if (PQgetisnull(res, i, i_dictinitoption))
6859 dictinfo[i].dictinitoption = NULL;
6861 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6863 /* Decide whether we want to dump it */
6864 selectDumpableObject(&(dictinfo[i].dobj));
6869 destroyPQExpBuffer(query);
6876 * read all text search templates in the system catalogs and return them
6877 * in the TSTemplateInfo* structure
6879 * numTSTemplates is set to the number of templates read in
6882 getTSTemplates(Archive *fout, int *numTSTemplates)
6888 TSTemplateInfo *tmplinfo;
6892 int i_tmplnamespace;
6896 /* Before 8.3, there is no built-in text search support */
6897 if (fout->remoteVersion < 80300)
6899 *numTSTemplates = 0;
6903 query = createPQExpBuffer();
6905 /* Make sure we are in proper schema */
6906 selectSourceSchema(fout, "pg_catalog");
6908 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6909 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6910 "FROM pg_ts_template");
6912 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6914 ntups = PQntuples(res);
6915 *numTSTemplates = ntups;
6917 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6919 i_tableoid = PQfnumber(res, "tableoid");
6920 i_oid = PQfnumber(res, "oid");
6921 i_tmplname = PQfnumber(res, "tmplname");
6922 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6923 i_tmplinit = PQfnumber(res, "tmplinit");
6924 i_tmpllexize = PQfnumber(res, "tmpllexize");
6926 for (i = 0; i < ntups; i++)
6928 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6929 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6930 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6931 AssignDumpId(&tmplinfo[i].dobj);
6932 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6933 tmplinfo[i].dobj.namespace =
6935 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6936 tmplinfo[i].dobj.catId.oid);
6937 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6938 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6940 /* Decide whether we want to dump it */
6941 selectDumpableObject(&(tmplinfo[i].dobj));
6946 destroyPQExpBuffer(query);
6952 * getTSConfigurations:
6953 * read all text search configurations in the system catalogs and return
6954 * them in the TSConfigInfo* structure
6956 * numTSConfigs is set to the number of configurations read in
6959 getTSConfigurations(Archive *fout, int *numTSConfigs)
6965 TSConfigInfo *cfginfo;
6973 /* Before 8.3, there is no built-in text search support */
6974 if (fout->remoteVersion < 80300)
6980 query = createPQExpBuffer();
6982 /* Make sure we are in proper schema */
6983 selectSourceSchema(fout, "pg_catalog");
6985 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6986 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6987 "FROM pg_ts_config",
6990 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6992 ntups = PQntuples(res);
6993 *numTSConfigs = ntups;
6995 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6997 i_tableoid = PQfnumber(res, "tableoid");
6998 i_oid = PQfnumber(res, "oid");
6999 i_cfgname = PQfnumber(res, "cfgname");
7000 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
7001 i_rolname = PQfnumber(res, "rolname");
7002 i_cfgparser = PQfnumber(res, "cfgparser");
7004 for (i = 0; i < ntups; i++)
7006 cfginfo[i].dobj.objType = DO_TSCONFIG;
7007 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7008 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7009 AssignDumpId(&cfginfo[i].dobj);
7010 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
7011 cfginfo[i].dobj.namespace =
7013 atooid(PQgetvalue(res, i, i_cfgnamespace)),
7014 cfginfo[i].dobj.catId.oid);
7015 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7016 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
7018 /* Decide whether we want to dump it */
7019 selectDumpableObject(&(cfginfo[i].dobj));
7024 destroyPQExpBuffer(query);
7030 * getForeignDataWrappers:
7031 * read all foreign-data wrappers in the system catalogs and return
7032 * them in the FdwInfo* structure
7034 * numForeignDataWrappers is set to the number of fdws read in
7037 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
7042 PQExpBuffer query = createPQExpBuffer();
7053 /* Before 8.4, there are no foreign-data wrappers */
7054 if (fout->remoteVersion < 80400)
7056 *numForeignDataWrappers = 0;
7060 /* Make sure we are in proper schema */
7061 selectSourceSchema(fout, "pg_catalog");
7063 if (fout->remoteVersion >= 90100)
7065 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7066 "(%s fdwowner) AS rolname, "
7067 "fdwhandler::pg_catalog.regproc, "
7068 "fdwvalidator::pg_catalog.regproc, fdwacl, "
7069 "array_to_string(ARRAY("
7070 "SELECT quote_ident(option_name) || ' ' || "
7071 "quote_literal(option_value) "
7072 "FROM pg_options_to_table(fdwoptions) "
7073 "ORDER BY option_name"
7074 "), E',\n ') AS fdwoptions "
7075 "FROM pg_foreign_data_wrapper",
7080 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7081 "(%s fdwowner) AS rolname, "
7082 "'-' AS fdwhandler, "
7083 "fdwvalidator::pg_catalog.regproc, fdwacl, "
7084 "array_to_string(ARRAY("
7085 "SELECT quote_ident(option_name) || ' ' || "
7086 "quote_literal(option_value) "
7087 "FROM pg_options_to_table(fdwoptions) "
7088 "ORDER BY option_name"
7089 "), E',\n ') AS fdwoptions "
7090 "FROM pg_foreign_data_wrapper",
7094 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7096 ntups = PQntuples(res);
7097 *numForeignDataWrappers = ntups;
7099 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
7101 i_tableoid = PQfnumber(res, "tableoid");
7102 i_oid = PQfnumber(res, "oid");
7103 i_fdwname = PQfnumber(res, "fdwname");
7104 i_rolname = PQfnumber(res, "rolname");
7105 i_fdwhandler = PQfnumber(res, "fdwhandler");
7106 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
7107 i_fdwacl = PQfnumber(res, "fdwacl");
7108 i_fdwoptions = PQfnumber(res, "fdwoptions");
7110 for (i = 0; i < ntups; i++)
7112 fdwinfo[i].dobj.objType = DO_FDW;
7113 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7114 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7115 AssignDumpId(&fdwinfo[i].dobj);
7116 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
7117 fdwinfo[i].dobj.namespace = NULL;
7118 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7119 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
7120 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
7121 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
7122 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
7124 /* Decide whether we want to dump it */
7125 selectDumpableObject(&(fdwinfo[i].dobj));
7130 destroyPQExpBuffer(query);
7136 * getForeignServers:
7137 * read all foreign servers in the system catalogs and return
7138 * them in the ForeignServerInfo * structure
7140 * numForeignServers is set to the number of servers read in
7143 getForeignServers(Archive *fout, int *numForeignServers)
7148 PQExpBuffer query = createPQExpBuffer();
7149 ForeignServerInfo *srvinfo;
7160 /* Before 8.4, there are no foreign servers */
7161 if (fout->remoteVersion < 80400)
7163 *numForeignServers = 0;
7167 /* Make sure we are in proper schema */
7168 selectSourceSchema(fout, "pg_catalog");
7170 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
7171 "(%s srvowner) AS rolname, "
7172 "srvfdw, srvtype, srvversion, srvacl,"
7173 "array_to_string(ARRAY("
7174 "SELECT quote_ident(option_name) || ' ' || "
7175 "quote_literal(option_value) "
7176 "FROM pg_options_to_table(srvoptions) "
7177 "ORDER BY option_name"
7178 "), E',\n ') AS srvoptions "
7179 "FROM pg_foreign_server",
7182 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7184 ntups = PQntuples(res);
7185 *numForeignServers = ntups;
7187 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
7189 i_tableoid = PQfnumber(res, "tableoid");
7190 i_oid = PQfnumber(res, "oid");
7191 i_srvname = PQfnumber(res, "srvname");
7192 i_rolname = PQfnumber(res, "rolname");
7193 i_srvfdw = PQfnumber(res, "srvfdw");
7194 i_srvtype = PQfnumber(res, "srvtype");
7195 i_srvversion = PQfnumber(res, "srvversion");
7196 i_srvacl = PQfnumber(res, "srvacl");
7197 i_srvoptions = PQfnumber(res, "srvoptions");
7199 for (i = 0; i < ntups; i++)
7201 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
7202 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7203 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7204 AssignDumpId(&srvinfo[i].dobj);
7205 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
7206 srvinfo[i].dobj.namespace = NULL;
7207 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7208 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
7209 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
7210 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
7211 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
7212 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
7214 /* Decide whether we want to dump it */
7215 selectDumpableObject(&(srvinfo[i].dobj));
7220 destroyPQExpBuffer(query);
7227 * read all default ACL information in the system catalogs and return
7228 * them in the DefaultACLInfo structure
7230 * numDefaultACLs is set to the number of ACLs read in
7233 getDefaultACLs(Archive *fout, int *numDefaultACLs)
7235 DefaultACLInfo *daclinfo;
7241 int i_defaclnamespace;
7242 int i_defaclobjtype;
7247 if (fout->remoteVersion < 90000)
7249 *numDefaultACLs = 0;
7253 query = createPQExpBuffer();
7255 /* Make sure we are in proper schema */
7256 selectSourceSchema(fout, "pg_catalog");
7258 appendPQExpBuffer(query, "SELECT oid, tableoid, "
7259 "(%s defaclrole) AS defaclrole, "
7263 "FROM pg_default_acl",
7266 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7268 ntups = PQntuples(res);
7269 *numDefaultACLs = ntups;
7271 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
7273 i_oid = PQfnumber(res, "oid");
7274 i_tableoid = PQfnumber(res, "tableoid");
7275 i_defaclrole = PQfnumber(res, "defaclrole");
7276 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
7277 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
7278 i_defaclacl = PQfnumber(res, "defaclacl");
7280 for (i = 0; i < ntups; i++)
7282 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
7284 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
7285 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7286 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7287 AssignDumpId(&daclinfo[i].dobj);
7288 /* cheesy ... is it worth coming up with a better object name? */
7289 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
7291 if (nspid != InvalidOid)
7292 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
7293 daclinfo[i].dobj.catId.oid);
7295 daclinfo[i].dobj.namespace = NULL;
7297 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
7298 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
7299 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
7301 /* Decide whether we want to dump it */
7302 selectDumpableDefaultACL(&(daclinfo[i]));
7307 destroyPQExpBuffer(query);
7315 * This routine is used to dump any comments associated with the
7316 * object handed to this routine. The routine takes a constant character
7317 * string for the target part of the comment-creation command, plus
7318 * the namespace and owner of the object (for labeling the ArchiveEntry),
7319 * plus catalog ID and subid which are the lookup key for pg_description,
7320 * plus the dump ID for the object (for setting a dependency).
7321 * If a matching pg_description entry is found, it is dumped.
7323 * Note: although this routine takes a dumpId for dependency purposes,
7324 * that purpose is just to mark the dependency in the emitted dump file
7325 * for possible future use by pg_restore. We do NOT use it for determining
7326 * ordering of the comment in the dump file, because this routine is called
7327 * after dependency sorting occurs. This routine should be called just after
7328 * calling ArchiveEntry() for the specified object.
7331 dumpComment(Archive *fout, const char *target,
7332 const char *namespace, const char *owner,
7333 CatalogId catalogId, int subid, DumpId dumpId)
7335 CommentItem *comments;
7338 /* Comments are schema not data ... except blob comments are data */
7339 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
7350 /* Search for comments associated with catalogId, using table */
7351 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
7354 /* Is there one matching the subid? */
7355 while (ncomments > 0)
7357 if (comments->objsubid == subid)
7363 /* If a comment exists, build COMMENT ON statement */
7366 PQExpBuffer query = createPQExpBuffer();
7368 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7369 appendStringLiteralAH(query, comments->descr, fout);
7370 appendPQExpBuffer(query, ";\n");
7373 * We mark comments as SECTION_NONE because they really belong in the
7374 * same section as their parent, whether that is pre-data or
7377 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7378 target, namespace, NULL, owner,
7379 false, "COMMENT", SECTION_NONE,
7380 query->data, "", NULL,
7384 destroyPQExpBuffer(query);
7389 * dumpTableComment --
7391 * As above, but dump comments for both the specified table (or view)
7395 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7396 const char *reltypename)
7398 CommentItem *comments;
7403 /* Comments are SCHEMA not data */
7407 /* Search for comments associated with relation, using table */
7408 ncomments = findComments(fout,
7409 tbinfo->dobj.catId.tableoid,
7410 tbinfo->dobj.catId.oid,
7413 /* If comments exist, build COMMENT ON statements */
7417 query = createPQExpBuffer();
7418 target = createPQExpBuffer();
7420 while (ncomments > 0)
7422 const char *descr = comments->descr;
7423 int objsubid = comments->objsubid;
7427 resetPQExpBuffer(target);
7428 appendPQExpBuffer(target, "%s %s", reltypename,
7429 fmtId(tbinfo->dobj.name));
7431 resetPQExpBuffer(query);
7432 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7433 appendStringLiteralAH(query, descr, fout);
7434 appendPQExpBuffer(query, ";\n");
7436 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7438 tbinfo->dobj.namespace->dobj.name,
7439 NULL, tbinfo->rolname,
7440 false, "COMMENT", SECTION_NONE,
7441 query->data, "", NULL,
7442 &(tbinfo->dobj.dumpId), 1,
7445 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7447 resetPQExpBuffer(target);
7448 appendPQExpBuffer(target, "COLUMN %s.",
7449 fmtId(tbinfo->dobj.name));
7450 appendPQExpBuffer(target, "%s",
7451 fmtId(tbinfo->attnames[objsubid - 1]));
7453 resetPQExpBuffer(query);
7454 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7455 appendStringLiteralAH(query, descr, fout);
7456 appendPQExpBuffer(query, ";\n");
7458 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7460 tbinfo->dobj.namespace->dobj.name,
7461 NULL, tbinfo->rolname,
7462 false, "COMMENT", SECTION_NONE,
7463 query->data, "", NULL,
7464 &(tbinfo->dobj.dumpId), 1,
7472 destroyPQExpBuffer(query);
7473 destroyPQExpBuffer(target);
7479 * Find the comment(s), if any, associated with the given object. All the
7480 * objsubid values associated with the given classoid/objoid are found with
7484 findComments(Archive *fout, Oid classoid, Oid objoid,
7485 CommentItem **items)
7487 /* static storage for table of comments */
7488 static CommentItem *comments = NULL;
7489 static int ncomments = -1;
7491 CommentItem *middle = NULL;
7496 /* Get comments if we didn't already */
7498 ncomments = collectComments(fout, &comments);
7501 * Pre-7.2, pg_description does not contain classoid, so collectComments
7502 * just stores a zero. If there's a collision on object OID, well, you
7503 * get duplicate comments.
7505 if (fout->remoteVersion < 70200)
7509 * Do binary search to find some item matching the object.
7512 high = &comments[ncomments - 1];
7515 middle = low + (high - low) / 2;
7517 if (classoid < middle->classoid)
7519 else if (classoid > middle->classoid)
7521 else if (objoid < middle->objoid)
7523 else if (objoid > middle->objoid)
7526 break; /* found a match */
7529 if (low > high) /* no matches */
7536 * Now determine how many items match the object. The search loop
7537 * invariant still holds: only items between low and high inclusive could
7541 while (middle > low)
7543 if (classoid != middle[-1].classoid ||
7544 objoid != middle[-1].objoid)
7553 while (middle <= high)
7555 if (classoid != middle->classoid ||
7556 objoid != middle->objoid)
7566 * collectComments --
7568 * Construct a table of all comments available for database objects.
7569 * We used to do per-object queries for the comments, but it's much faster
7570 * to pull them all over at once, and on most databases the memory cost
7573 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7576 collectComments(Archive *fout, CommentItem **items)
7586 CommentItem *comments;
7589 * Note we do NOT change source schema here; preserve the caller's
7593 query = createPQExpBuffer();
7595 if (fout->remoteVersion >= 70300)
7597 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7598 "FROM pg_catalog.pg_description "
7599 "ORDER BY classoid, objoid, objsubid");
7601 else if (fout->remoteVersion >= 70200)
7603 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7604 "FROM pg_description "
7605 "ORDER BY classoid, objoid, objsubid");
7609 /* Note: this will fail to find attribute comments in pre-7.2... */
7610 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7611 "FROM pg_description "
7615 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7617 /* Construct lookup table containing OIDs in numeric form */
7619 i_description = PQfnumber(res, "description");
7620 i_classoid = PQfnumber(res, "classoid");
7621 i_objoid = PQfnumber(res, "objoid");
7622 i_objsubid = PQfnumber(res, "objsubid");
7624 ntups = PQntuples(res);
7626 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7628 for (i = 0; i < ntups; i++)
7630 comments[i].descr = PQgetvalue(res, i, i_description);
7631 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7632 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7633 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7636 /* Do NOT free the PGresult since we are keeping pointers into it */
7637 destroyPQExpBuffer(query);
7644 * dumpDumpableObject
7646 * This routine and its subsidiaries are responsible for creating
7647 * ArchiveEntries (TOC objects) for each object to be dumped.
7650 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7652 switch (dobj->objType)
7655 dumpNamespace(fout, (NamespaceInfo *) dobj);
7658 dumpExtension(fout, (ExtensionInfo *) dobj);
7661 dumpType(fout, (TypeInfo *) dobj);
7664 dumpShellType(fout, (ShellTypeInfo *) dobj);
7667 dumpFunc(fout, (FuncInfo *) dobj);
7670 dumpAgg(fout, (AggInfo *) dobj);
7673 dumpOpr(fout, (OprInfo *) dobj);
7676 dumpOpclass(fout, (OpclassInfo *) dobj);
7679 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7682 dumpCollation(fout, (CollInfo *) dobj);
7685 dumpConversion(fout, (ConvInfo *) dobj);
7688 dumpTable(fout, (TableInfo *) dobj);
7691 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7694 dumpIndex(fout, (IndxInfo *) dobj);
7696 case DO_REFRESH_MATVIEW:
7697 refreshMatViewData(fout, (TableDataInfo *) dobj);
7700 dumpRule(fout, (RuleInfo *) dobj);
7703 dumpTrigger(fout, (TriggerInfo *) dobj);
7705 case DO_EVENT_TRIGGER:
7706 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7709 dumpConstraint(fout, (ConstraintInfo *) dobj);
7711 case DO_FK_CONSTRAINT:
7712 dumpConstraint(fout, (ConstraintInfo *) dobj);
7715 dumpProcLang(fout, (ProcLangInfo *) dobj);
7718 dumpCast(fout, (CastInfo *) dobj);
7721 if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7722 dumpSequenceData(fout, (TableDataInfo *) dobj);
7724 dumpTableData(fout, (TableDataInfo *) dobj);
7727 /* table rowtypes and array types are never dumped separately */
7730 dumpTSParser(fout, (TSParserInfo *) dobj);
7733 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7736 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7739 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7742 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7744 case DO_FOREIGN_SERVER:
7745 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7747 case DO_DEFAULT_ACL:
7748 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7751 dumpBlob(fout, (BlobInfo *) dobj);
7754 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7755 dobj->name, NULL, NULL, "",
7756 false, "BLOBS", SECTION_DATA,
7761 case DO_PRE_DATA_BOUNDARY:
7762 case DO_POST_DATA_BOUNDARY:
7763 /* never dumped, nothing to do */
7770 * writes out to fout the queries to recreate a user-defined namespace
7773 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7780 /* Skip if not to be dumped */
7781 if (!nspinfo->dobj.dump || dataOnly)
7784 /* don't dump dummy namespace from pre-7.3 source */
7785 if (strlen(nspinfo->dobj.name) == 0)
7788 q = createPQExpBuffer();
7789 delq = createPQExpBuffer();
7790 labelq = createPQExpBuffer();
7792 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7794 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7796 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7798 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7801 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7803 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7807 false, "SCHEMA", SECTION_PRE_DATA,
7808 q->data, delq->data, NULL,
7812 /* Dump Schema Comments and Security Labels */
7813 dumpComment(fout, labelq->data,
7814 NULL, nspinfo->rolname,
7815 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7816 dumpSecLabel(fout, labelq->data,
7817 NULL, nspinfo->rolname,
7818 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7820 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7821 qnspname, NULL, nspinfo->dobj.name, NULL,
7822 nspinfo->rolname, nspinfo->nspacl);
7826 destroyPQExpBuffer(q);
7827 destroyPQExpBuffer(delq);
7828 destroyPQExpBuffer(labelq);
7833 * writes out to fout the queries to recreate an extension
7836 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7843 /* Skip if not to be dumped */
7844 if (!extinfo->dobj.dump || dataOnly)
7847 q = createPQExpBuffer();
7848 delq = createPQExpBuffer();
7849 labelq = createPQExpBuffer();
7851 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7853 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7855 if (!binary_upgrade)
7858 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7859 * problem if the extension already exists in the target database;
7860 * this is essential for installed-by-default extensions such as
7863 * In binary-upgrade mode, that doesn't work well, so instead we skip
7864 * built-in extensions based on their OIDs; see
7865 * selectDumpableExtension.
7867 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7868 qextname, fmtId(extinfo->namespace));
7875 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7878 * We unconditionally create the extension, so we must drop it if it
7879 * exists. This could happen if the user deleted 'plpgsql' and then
7880 * readded it, causing its oid to be greater than FirstNormalObjectId.
7881 * The FirstNormalObjectId test was kept to avoid repeatedly dropping
7882 * and recreating extensions like 'plpgsql'.
7884 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7886 appendPQExpBuffer(q,
7887 "SELECT binary_upgrade.create_empty_extension(");
7888 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7889 appendPQExpBuffer(q, ", ");
7890 appendStringLiteralAH(q, extinfo->namespace, fout);
7891 appendPQExpBuffer(q, ", ");
7892 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7893 appendStringLiteralAH(q, extinfo->extversion, fout);
7894 appendPQExpBuffer(q, ", ");
7897 * Note that we're pushing extconfig (an OID array) back into
7898 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7899 * preserved in binary upgrade.
7901 if (strlen(extinfo->extconfig) > 2)
7902 appendStringLiteralAH(q, extinfo->extconfig, fout);
7904 appendPQExpBuffer(q, "NULL");
7905 appendPQExpBuffer(q, ", ");
7906 if (strlen(extinfo->extcondition) > 2)
7907 appendStringLiteralAH(q, extinfo->extcondition, fout);
7909 appendPQExpBuffer(q, "NULL");
7910 appendPQExpBuffer(q, ", ");
7911 appendPQExpBuffer(q, "ARRAY[");
7913 for (i = 0; i < extinfo->dobj.nDeps; i++)
7915 DumpableObject *extobj;
7917 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7918 if (extobj && extobj->objType == DO_EXTENSION)
7921 appendPQExpBuffer(q, ",");
7922 appendStringLiteralAH(q, extobj->name, fout);
7925 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7926 appendPQExpBuffer(q, ");\n");
7929 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7931 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7935 false, "EXTENSION", SECTION_PRE_DATA,
7936 q->data, delq->data, NULL,
7940 /* Dump Extension Comments and Security Labels */
7941 dumpComment(fout, labelq->data,
7943 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7944 dumpSecLabel(fout, labelq->data,
7946 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7950 destroyPQExpBuffer(q);
7951 destroyPQExpBuffer(delq);
7952 destroyPQExpBuffer(labelq);
7957 * writes out to fout the queries to recreate a user-defined type
7960 dumpType(Archive *fout, TypeInfo *tyinfo)
7962 /* Skip if not to be dumped */
7963 if (!tyinfo->dobj.dump || dataOnly)
7966 /* Dump out in proper style */
7967 if (tyinfo->typtype == TYPTYPE_BASE)
7968 dumpBaseType(fout, tyinfo);
7969 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7970 dumpDomain(fout, tyinfo);
7971 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7972 dumpCompositeType(fout, tyinfo);
7973 else if (tyinfo->typtype == TYPTYPE_ENUM)
7974 dumpEnumType(fout, tyinfo);
7975 else if (tyinfo->typtype == TYPTYPE_RANGE)
7976 dumpRangeType(fout, tyinfo);
7978 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7984 * writes out to fout the queries to recreate a user-defined enum type
7987 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7989 PQExpBuffer q = createPQExpBuffer();
7990 PQExpBuffer delq = createPQExpBuffer();
7991 PQExpBuffer labelq = createPQExpBuffer();
7992 PQExpBuffer query = createPQExpBuffer();
8000 /* Set proper schema search path */
8001 selectSourceSchema(fout, "pg_catalog");
8003 if (fout->remoteVersion >= 90100)
8004 appendPQExpBuffer(query, "SELECT oid, enumlabel "
8005 "FROM pg_catalog.pg_enum "
8006 "WHERE enumtypid = '%u'"
8007 "ORDER BY enumsortorder",
8008 tyinfo->dobj.catId.oid);
8010 appendPQExpBuffer(query, "SELECT oid, enumlabel "
8011 "FROM pg_catalog.pg_enum "
8012 "WHERE enumtypid = '%u'"
8014 tyinfo->dobj.catId.oid);
8016 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8018 num = PQntuples(res);
8020 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8023 * DROP must be fully qualified in case same name appears in pg_catalog.
8024 * CASCADE shouldn't be required here as for normal types since the I/O
8025 * functions are generic and do not get dropped.
8027 appendPQExpBuffer(delq, "DROP TYPE %s.",
8028 fmtId(tyinfo->dobj.namespace->dobj.name));
8029 appendPQExpBuffer(delq, "%s;\n",
8033 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8034 tyinfo->dobj.catId.oid);
8036 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
8039 if (!binary_upgrade)
8041 /* Labels with server-assigned oids */
8042 for (i = 0; i < num; i++)
8044 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8046 appendPQExpBuffer(q, ",");
8047 appendPQExpBuffer(q, "\n ");
8048 appendStringLiteralAH(q, label, fout);
8052 appendPQExpBuffer(q, "\n);\n");
8056 /* Labels with dump-assigned (preserved) oids */
8057 for (i = 0; i < num; i++)
8059 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
8060 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8063 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
8064 appendPQExpBuffer(q,
8065 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
8067 appendPQExpBuffer(q, "ALTER TYPE %s.",
8068 fmtId(tyinfo->dobj.namespace->dobj.name));
8069 appendPQExpBuffer(q, "%s ADD VALUE ",
8071 appendStringLiteralAH(q, label, fout);
8072 appendPQExpBuffer(q, ";\n\n");
8076 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8079 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8081 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8083 tyinfo->dobj.namespace->dobj.name,
8085 tyinfo->rolname, false,
8086 "TYPE", SECTION_PRE_DATA,
8087 q->data, delq->data, NULL,
8091 /* Dump Type Comments and Security Labels */
8092 dumpComment(fout, labelq->data,
8093 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8094 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8095 dumpSecLabel(fout, labelq->data,
8096 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8097 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8099 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8100 qtypname, NULL, tyinfo->dobj.name,
8101 tyinfo->dobj.namespace->dobj.name,
8102 tyinfo->rolname, tyinfo->typacl);
8105 destroyPQExpBuffer(q);
8106 destroyPQExpBuffer(delq);
8107 destroyPQExpBuffer(labelq);
8108 destroyPQExpBuffer(query);
8113 * writes out to fout the queries to recreate a user-defined range type
8116 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
8118 PQExpBuffer q = createPQExpBuffer();
8119 PQExpBuffer delq = createPQExpBuffer();
8120 PQExpBuffer labelq = createPQExpBuffer();
8121 PQExpBuffer query = createPQExpBuffer();
8128 * select appropriate schema to ensure names in CREATE are properly
8131 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8133 appendPQExpBuffer(query,
8134 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
8135 "opc.opcname AS opcname, "
8136 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
8137 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
8139 "CASE WHEN rngcollation = st.typcollation THEN 0 "
8140 " ELSE rngcollation END AS collation, "
8141 "rngcanonical, rngsubdiff "
8142 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
8143 " pg_catalog.pg_opclass opc "
8144 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
8146 tyinfo->dobj.catId.oid);
8148 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8150 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8153 * DROP must be fully qualified in case same name appears in pg_catalog.
8154 * CASCADE shouldn't be required here as for normal types since the I/O
8155 * functions are generic and do not get dropped.
8157 appendPQExpBuffer(delq, "DROP TYPE %s.",
8158 fmtId(tyinfo->dobj.namespace->dobj.name));
8159 appendPQExpBuffer(delq, "%s;\n",
8163 binary_upgrade_set_type_oids_by_type_oid(fout,
8164 q, tyinfo->dobj.catId.oid);
8166 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
8169 appendPQExpBuffer(q, "\n subtype = %s",
8170 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
8172 /* print subtype_opclass only if not default for subtype */
8173 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
8175 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
8176 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
8178 /* always schema-qualify, don't try to be smart */
8179 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
8181 appendPQExpBuffer(q, "%s", fmtId(opcname));
8184 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
8185 if (OidIsValid(collationOid))
8187 CollInfo *coll = findCollationByOid(collationOid);
8191 /* always schema-qualify, don't try to be smart */
8192 appendPQExpBuffer(q, ",\n collation = %s.",
8193 fmtId(coll->dobj.namespace->dobj.name));
8194 appendPQExpBuffer(q, "%s",
8195 fmtId(coll->dobj.name));
8199 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
8200 if (strcmp(procname, "-") != 0)
8201 appendPQExpBuffer(q, ",\n canonical = %s", procname);
8203 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
8204 if (strcmp(procname, "-") != 0)
8205 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
8207 appendPQExpBuffer(q, "\n);\n");
8209 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8212 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8214 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8216 tyinfo->dobj.namespace->dobj.name,
8218 tyinfo->rolname, false,
8219 "TYPE", SECTION_PRE_DATA,
8220 q->data, delq->data, NULL,
8224 /* Dump Type Comments and Security Labels */
8225 dumpComment(fout, labelq->data,
8226 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8227 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8228 dumpSecLabel(fout, labelq->data,
8229 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8230 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8232 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8233 qtypname, NULL, tyinfo->dobj.name,
8234 tyinfo->dobj.namespace->dobj.name,
8235 tyinfo->rolname, tyinfo->typacl);
8238 destroyPQExpBuffer(q);
8239 destroyPQExpBuffer(delq);
8240 destroyPQExpBuffer(labelq);
8241 destroyPQExpBuffer(query);
8246 * writes out to fout the queries to recreate a user-defined base type
8249 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
8251 PQExpBuffer q = createPQExpBuffer();
8252 PQExpBuffer delq = createPQExpBuffer();
8253 PQExpBuffer labelq = createPQExpBuffer();
8254 PQExpBuffer query = createPQExpBuffer();
8271 char *typispreferred;
8276 char *typcollatable;
8278 bool typdefault_is_literal = false;
8280 /* Set proper schema search path so regproc references list correctly */
8281 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8283 /* Fetch type-specific details */
8284 if (fout->remoteVersion >= 90100)
8286 appendPQExpBuffer(query, "SELECT typlen, "
8287 "typinput, typoutput, typreceive, typsend, "
8288 "typmodin, typmodout, typanalyze, "
8289 "typreceive::pg_catalog.oid AS typreceiveoid, "
8290 "typsend::pg_catalog.oid AS typsendoid, "
8291 "typmodin::pg_catalog.oid AS typmodinoid, "
8292 "typmodout::pg_catalog.oid AS typmodoutoid, "
8293 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8294 "typcategory, typispreferred, "
8295 "typdelim, typbyval, typalign, typstorage, "
8296 "(typcollation <> 0) AS typcollatable, "
8297 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8298 "FROM pg_catalog.pg_type "
8299 "WHERE oid = '%u'::pg_catalog.oid",
8300 tyinfo->dobj.catId.oid);
8302 else if (fout->remoteVersion >= 80400)
8304 appendPQExpBuffer(query, "SELECT typlen, "
8305 "typinput, typoutput, typreceive, typsend, "
8306 "typmodin, typmodout, typanalyze, "
8307 "typreceive::pg_catalog.oid AS typreceiveoid, "
8308 "typsend::pg_catalog.oid AS typsendoid, "
8309 "typmodin::pg_catalog.oid AS typmodinoid, "
8310 "typmodout::pg_catalog.oid AS typmodoutoid, "
8311 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8312 "typcategory, typispreferred, "
8313 "typdelim, typbyval, typalign, typstorage, "
8314 "false AS typcollatable, "
8315 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8316 "FROM pg_catalog.pg_type "
8317 "WHERE oid = '%u'::pg_catalog.oid",
8318 tyinfo->dobj.catId.oid);
8320 else if (fout->remoteVersion >= 80300)
8322 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
8323 appendPQExpBuffer(query, "SELECT typlen, "
8324 "typinput, typoutput, typreceive, typsend, "
8325 "typmodin, typmodout, typanalyze, "
8326 "typreceive::pg_catalog.oid AS typreceiveoid, "
8327 "typsend::pg_catalog.oid AS typsendoid, "
8328 "typmodin::pg_catalog.oid AS typmodinoid, "
8329 "typmodout::pg_catalog.oid AS typmodoutoid, "
8330 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8331 "'U' AS typcategory, false AS typispreferred, "
8332 "typdelim, typbyval, typalign, typstorage, "
8333 "false AS typcollatable, "
8334 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8335 "FROM pg_catalog.pg_type "
8336 "WHERE oid = '%u'::pg_catalog.oid",
8337 tyinfo->dobj.catId.oid);
8339 else if (fout->remoteVersion >= 80000)
8341 appendPQExpBuffer(query, "SELECT typlen, "
8342 "typinput, typoutput, typreceive, typsend, "
8343 "'-' AS typmodin, '-' AS typmodout, "
8345 "typreceive::pg_catalog.oid AS typreceiveoid, "
8346 "typsend::pg_catalog.oid AS typsendoid, "
8347 "0 AS typmodinoid, 0 AS typmodoutoid, "
8348 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8349 "'U' AS typcategory, false AS typispreferred, "
8350 "typdelim, typbyval, typalign, typstorage, "
8351 "false AS typcollatable, "
8352 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8353 "FROM pg_catalog.pg_type "
8354 "WHERE oid = '%u'::pg_catalog.oid",
8355 tyinfo->dobj.catId.oid);
8357 else if (fout->remoteVersion >= 70400)
8359 appendPQExpBuffer(query, "SELECT typlen, "
8360 "typinput, typoutput, typreceive, typsend, "
8361 "'-' AS typmodin, '-' AS typmodout, "
8362 "'-' AS typanalyze, "
8363 "typreceive::pg_catalog.oid AS typreceiveoid, "
8364 "typsend::pg_catalog.oid AS typsendoid, "
8365 "0 AS typmodinoid, 0 AS typmodoutoid, "
8366 "0 AS typanalyzeoid, "
8367 "'U' AS typcategory, false AS typispreferred, "
8368 "typdelim, typbyval, typalign, typstorage, "
8369 "false AS typcollatable, "
8370 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8371 "FROM pg_catalog.pg_type "
8372 "WHERE oid = '%u'::pg_catalog.oid",
8373 tyinfo->dobj.catId.oid);
8375 else if (fout->remoteVersion >= 70300)
8377 appendPQExpBuffer(query, "SELECT typlen, "
8378 "typinput, typoutput, "
8379 "'-' AS typreceive, '-' AS typsend, "
8380 "'-' AS typmodin, '-' AS typmodout, "
8381 "'-' AS typanalyze, "
8382 "0 AS typreceiveoid, 0 AS typsendoid, "
8383 "0 AS typmodinoid, 0 AS typmodoutoid, "
8384 "0 AS typanalyzeoid, "
8385 "'U' AS typcategory, false AS typispreferred, "
8386 "typdelim, typbyval, typalign, typstorage, "
8387 "false AS typcollatable, "
8388 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8389 "FROM pg_catalog.pg_type "
8390 "WHERE oid = '%u'::pg_catalog.oid",
8391 tyinfo->dobj.catId.oid);
8393 else if (fout->remoteVersion >= 70200)
8396 * Note: although pre-7.3 catalogs contain typreceive and typsend,
8397 * ignore them because they are not right.
8399 appendPQExpBuffer(query, "SELECT typlen, "
8400 "typinput, typoutput, "
8401 "'-' AS typreceive, '-' AS typsend, "
8402 "'-' AS typmodin, '-' AS typmodout, "
8403 "'-' AS typanalyze, "
8404 "0 AS typreceiveoid, 0 AS typsendoid, "
8405 "0 AS typmodinoid, 0 AS typmodoutoid, "
8406 "0 AS typanalyzeoid, "
8407 "'U' AS typcategory, false AS typispreferred, "
8408 "typdelim, typbyval, typalign, typstorage, "
8409 "false AS typcollatable, "
8410 "NULL AS typdefaultbin, typdefault "
8412 "WHERE oid = '%u'::oid",
8413 tyinfo->dobj.catId.oid);
8415 else if (fout->remoteVersion >= 70100)
8418 * Ignore pre-7.2 typdefault; the field exists but has an unusable
8421 appendPQExpBuffer(query, "SELECT typlen, "
8422 "typinput, typoutput, "
8423 "'-' AS typreceive, '-' AS typsend, "
8424 "'-' AS typmodin, '-' AS typmodout, "
8425 "'-' AS typanalyze, "
8426 "0 AS typreceiveoid, 0 AS typsendoid, "
8427 "0 AS typmodinoid, 0 AS typmodoutoid, "
8428 "0 AS typanalyzeoid, "
8429 "'U' AS typcategory, false AS typispreferred, "
8430 "typdelim, typbyval, typalign, typstorage, "
8431 "false AS typcollatable, "
8432 "NULL AS typdefaultbin, NULL AS typdefault "
8434 "WHERE oid = '%u'::oid",
8435 tyinfo->dobj.catId.oid);
8439 appendPQExpBuffer(query, "SELECT typlen, "
8440 "typinput, typoutput, "
8441 "'-' AS typreceive, '-' AS typsend, "
8442 "'-' AS typmodin, '-' AS typmodout, "
8443 "'-' AS typanalyze, "
8444 "0 AS typreceiveoid, 0 AS typsendoid, "
8445 "0 AS typmodinoid, 0 AS typmodoutoid, "
8446 "0 AS typanalyzeoid, "
8447 "'U' AS typcategory, false AS typispreferred, "
8448 "typdelim, typbyval, typalign, "
8449 "'p'::char AS typstorage, "
8450 "false AS typcollatable, "
8451 "NULL AS typdefaultbin, NULL AS typdefault "
8453 "WHERE oid = '%u'::oid",
8454 tyinfo->dobj.catId.oid);
8457 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8459 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8460 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8461 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8462 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8463 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8464 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8465 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8466 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8467 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8468 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8469 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8470 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8471 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8472 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8473 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8474 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8475 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8476 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8477 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8478 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8479 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8480 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8481 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8483 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8484 typdefault_is_literal = true; /* it needs quotes */
8489 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8492 * DROP must be fully qualified in case same name appears in pg_catalog.
8493 * The reason we include CASCADE is that the circular dependency between
8494 * the type and its I/O functions makes it impossible to drop the type any
8497 appendPQExpBuffer(delq, "DROP TYPE %s.",
8498 fmtId(tyinfo->dobj.namespace->dobj.name));
8499 appendPQExpBuffer(delq, "%s CASCADE;\n",
8502 /* We might already have a shell type, but setting pg_type_oid is harmless */
8504 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8505 tyinfo->dobj.catId.oid);
8507 appendPQExpBuffer(q,
8508 "CREATE TYPE %s (\n"
8509 " INTERNALLENGTH = %s",
8511 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8513 if (fout->remoteVersion >= 70300)
8515 /* regproc result is correctly quoted as of 7.3 */
8516 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8517 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8518 if (OidIsValid(typreceiveoid))
8519 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8520 if (OidIsValid(typsendoid))
8521 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8522 if (OidIsValid(typmodinoid))
8523 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8524 if (OidIsValid(typmodoutoid))
8525 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8526 if (OidIsValid(typanalyzeoid))
8527 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8531 /* regproc delivers an unquoted name before 7.3 */
8532 /* cannot combine these because fmtId uses static result area */
8533 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8534 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8535 /* receive/send/typmodin/typmodout/analyze need not be printed */
8538 if (strcmp(typcollatable, "t") == 0)
8539 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8541 if (typdefault != NULL)
8543 appendPQExpBuffer(q, ",\n DEFAULT = ");
8544 if (typdefault_is_literal)
8545 appendStringLiteralAH(q, typdefault, fout);
8547 appendPQExpBufferStr(q, typdefault);
8550 if (OidIsValid(tyinfo->typelem))
8554 /* reselect schema in case changed by function dump */
8555 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8556 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8557 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8561 if (strcmp(typcategory, "U") != 0)
8563 appendPQExpBuffer(q, ",\n CATEGORY = ");
8564 appendStringLiteralAH(q, typcategory, fout);
8567 if (strcmp(typispreferred, "t") == 0)
8568 appendPQExpBuffer(q, ",\n PREFERRED = true");
8570 if (typdelim && strcmp(typdelim, ",") != 0)
8572 appendPQExpBuffer(q, ",\n DELIMITER = ");
8573 appendStringLiteralAH(q, typdelim, fout);
8576 if (strcmp(typalign, "c") == 0)
8577 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8578 else if (strcmp(typalign, "s") == 0)
8579 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8580 else if (strcmp(typalign, "i") == 0)
8581 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8582 else if (strcmp(typalign, "d") == 0)
8583 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8585 if (strcmp(typstorage, "p") == 0)
8586 appendPQExpBuffer(q, ",\n STORAGE = plain");
8587 else if (strcmp(typstorage, "e") == 0)
8588 appendPQExpBuffer(q, ",\n STORAGE = external");
8589 else if (strcmp(typstorage, "x") == 0)
8590 appendPQExpBuffer(q, ",\n STORAGE = extended");
8591 else if (strcmp(typstorage, "m") == 0)
8592 appendPQExpBuffer(q, ",\n STORAGE = main");
8594 if (strcmp(typbyval, "t") == 0)
8595 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8597 appendPQExpBuffer(q, "\n);\n");
8599 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8602 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8604 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8606 tyinfo->dobj.namespace->dobj.name,
8608 tyinfo->rolname, false,
8609 "TYPE", SECTION_PRE_DATA,
8610 q->data, delq->data, NULL,
8614 /* Dump Type Comments and Security Labels */
8615 dumpComment(fout, labelq->data,
8616 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8617 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8618 dumpSecLabel(fout, labelq->data,
8619 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8620 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8622 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8623 qtypname, NULL, tyinfo->dobj.name,
8624 tyinfo->dobj.namespace->dobj.name,
8625 tyinfo->rolname, tyinfo->typacl);
8628 destroyPQExpBuffer(q);
8629 destroyPQExpBuffer(delq);
8630 destroyPQExpBuffer(labelq);
8631 destroyPQExpBuffer(query);
8636 * writes out to fout the queries to recreate a user-defined domain
8639 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8641 PQExpBuffer q = createPQExpBuffer();
8642 PQExpBuffer delq = createPQExpBuffer();
8643 PQExpBuffer labelq = createPQExpBuffer();
8644 PQExpBuffer query = createPQExpBuffer();
8652 bool typdefault_is_literal = false;
8654 /* Set proper schema search path so type references list correctly */
8655 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8657 /* Fetch domain specific details */
8658 if (fout->remoteVersion >= 90100)
8660 /* typcollation is new in 9.1 */
8661 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8662 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8663 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8665 "CASE WHEN t.typcollation <> u.typcollation "
8666 "THEN t.typcollation ELSE 0 END AS typcollation "
8667 "FROM pg_catalog.pg_type t "
8668 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8669 "WHERE t.oid = '%u'::pg_catalog.oid",
8670 tyinfo->dobj.catId.oid);
8674 /* We assume here that remoteVersion must be at least 70300 */
8675 appendPQExpBuffer(query, "SELECT typnotnull, "
8676 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8677 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8678 "typdefault, 0 AS typcollation "
8679 "FROM pg_catalog.pg_type "
8680 "WHERE oid = '%u'::pg_catalog.oid",
8681 tyinfo->dobj.catId.oid);
8684 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8686 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8687 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8688 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8689 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8690 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8692 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8693 typdefault_is_literal = true; /* it needs quotes */
8697 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8700 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8701 tyinfo->dobj.catId.oid);
8703 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8705 appendPQExpBuffer(q,
8706 "CREATE DOMAIN %s AS %s",
8710 /* Print collation only if different from base type's collation */
8711 if (OidIsValid(typcollation))
8715 coll = findCollationByOid(typcollation);
8718 /* always schema-qualify, don't try to be smart */
8719 appendPQExpBuffer(q, " COLLATE %s.",
8720 fmtId(coll->dobj.namespace->dobj.name));
8721 appendPQExpBuffer(q, "%s",
8722 fmtId(coll->dobj.name));
8726 if (typnotnull[0] == 't')
8727 appendPQExpBuffer(q, " NOT NULL");
8729 if (typdefault != NULL)
8731 appendPQExpBuffer(q, " DEFAULT ");
8732 if (typdefault_is_literal)
8733 appendStringLiteralAH(q, typdefault, fout);
8735 appendPQExpBufferStr(q, typdefault);
8741 * Add any CHECK constraints for the domain
8743 for (i = 0; i < tyinfo->nDomChecks; i++)
8745 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8747 if (!domcheck->separate)
8748 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8749 fmtId(domcheck->dobj.name), domcheck->condef);
8752 appendPQExpBuffer(q, ";\n");
8755 * DROP must be fully qualified in case same name appears in pg_catalog
8757 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8758 fmtId(tyinfo->dobj.namespace->dobj.name));
8759 appendPQExpBuffer(delq, "%s;\n",
8762 appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8765 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8767 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8769 tyinfo->dobj.namespace->dobj.name,
8771 tyinfo->rolname, false,
8772 "DOMAIN", SECTION_PRE_DATA,
8773 q->data, delq->data, NULL,
8777 /* Dump Domain Comments and Security Labels */
8778 dumpComment(fout, labelq->data,
8779 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8780 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8781 dumpSecLabel(fout, labelq->data,
8782 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8783 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8785 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8786 qtypname, NULL, tyinfo->dobj.name,
8787 tyinfo->dobj.namespace->dobj.name,
8788 tyinfo->rolname, tyinfo->typacl);
8790 destroyPQExpBuffer(q);
8791 destroyPQExpBuffer(delq);
8792 destroyPQExpBuffer(labelq);
8793 destroyPQExpBuffer(query);
8798 * writes out to fout the queries to recreate a user-defined stand-alone
8802 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8804 PQExpBuffer q = createPQExpBuffer();
8805 PQExpBuffer dropped = createPQExpBuffer();
8806 PQExpBuffer delq = createPQExpBuffer();
8807 PQExpBuffer labelq = createPQExpBuffer();
8808 PQExpBuffer query = createPQExpBuffer();
8822 /* Set proper schema search path so type references list correctly */
8823 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8825 /* Fetch type specific details */
8826 if (fout->remoteVersion >= 90100)
8829 * attcollation is new in 9.1. Since we only want to dump COLLATE
8830 * clauses for attributes whose collation is different from their
8831 * type's default, we use a CASE here to suppress uninteresting
8832 * attcollations cheaply. atttypid will be 0 for dropped columns;
8833 * collation does not matter for those.
8835 appendPQExpBuffer(query, "SELECT a.attname, "
8836 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8837 "a.attlen, a.attalign, a.attisdropped, "
8838 "CASE WHEN a.attcollation <> at.typcollation "
8839 "THEN a.attcollation ELSE 0 END AS attcollation, "
8841 "FROM pg_catalog.pg_type ct "
8842 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8843 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8844 "WHERE ct.oid = '%u'::pg_catalog.oid "
8845 "ORDER BY a.attnum ",
8846 tyinfo->dobj.catId.oid);
8851 * We assume here that remoteVersion must be at least 70300. Since
8852 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8855 appendPQExpBuffer(query, "SELECT a.attname, "
8856 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8857 "a.attlen, a.attalign, a.attisdropped, "
8858 "0 AS attcollation, "
8860 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8861 "WHERE ct.oid = '%u'::pg_catalog.oid "
8862 "AND a.attrelid = ct.typrelid "
8863 "ORDER BY a.attnum ",
8864 tyinfo->dobj.catId.oid);
8867 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8869 ntups = PQntuples(res);
8871 i_attname = PQfnumber(res, "attname");
8872 i_atttypdefn = PQfnumber(res, "atttypdefn");
8873 i_attlen = PQfnumber(res, "attlen");
8874 i_attalign = PQfnumber(res, "attalign");
8875 i_attisdropped = PQfnumber(res, "attisdropped");
8876 i_attcollation = PQfnumber(res, "attcollation");
8877 i_typrelid = PQfnumber(res, "typrelid");
8881 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8883 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8884 tyinfo->dobj.catId.oid);
8885 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8888 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8890 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8894 for (i = 0; i < ntups; i++)
8903 attname = PQgetvalue(res, i, i_attname);
8904 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8905 attlen = PQgetvalue(res, i, i_attlen);
8906 attalign = PQgetvalue(res, i, i_attalign);
8907 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8908 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8910 if (attisdropped && !binary_upgrade)
8913 /* Format properly if not first attr */
8914 if (actual_atts++ > 0)
8915 appendPQExpBuffer(q, ",");
8916 appendPQExpBuffer(q, "\n\t");
8920 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8922 /* Add collation if not default for the column type */
8923 if (OidIsValid(attcollation))
8927 coll = findCollationByOid(attcollation);
8930 /* always schema-qualify, don't try to be smart */
8931 appendPQExpBuffer(q, " COLLATE %s.",
8932 fmtId(coll->dobj.namespace->dobj.name));
8933 appendPQExpBuffer(q, "%s",
8934 fmtId(coll->dobj.name));
8941 * This is a dropped attribute and we're in binary_upgrade mode.
8942 * Insert a placeholder for it in the CREATE TYPE command, and set
8943 * length and alignment with direct UPDATE to the catalogs
8944 * afterwards. See similar code in dumpTableSchema().
8946 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8948 /* stash separately for insertion after the CREATE TYPE */
8949 appendPQExpBuffer(dropped,
8950 "\n-- For binary upgrade, recreate dropped column.\n");
8951 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8953 "attalign = '%s', attbyval = false\n"
8954 "WHERE attname = ", attlen, attalign);
8955 appendStringLiteralAH(dropped, attname, fout);
8956 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8957 appendStringLiteralAH(dropped, qtypname, fout);
8958 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8960 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8962 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8966 appendPQExpBuffer(q, "\n);\n");
8967 appendPQExpBufferStr(q, dropped->data);
8970 * DROP must be fully qualified in case same name appears in pg_catalog
8972 appendPQExpBuffer(delq, "DROP TYPE %s.",
8973 fmtId(tyinfo->dobj.namespace->dobj.name));
8974 appendPQExpBuffer(delq, "%s;\n",
8977 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8980 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8982 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8984 tyinfo->dobj.namespace->dobj.name,
8986 tyinfo->rolname, false,
8987 "TYPE", SECTION_PRE_DATA,
8988 q->data, delq->data, NULL,
8993 /* Dump Type Comments and Security Labels */
8994 dumpComment(fout, labelq->data,
8995 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8996 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8997 dumpSecLabel(fout, labelq->data,
8998 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8999 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
9001 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
9002 qtypname, NULL, tyinfo->dobj.name,
9003 tyinfo->dobj.namespace->dobj.name,
9004 tyinfo->rolname, tyinfo->typacl);
9007 destroyPQExpBuffer(q);
9008 destroyPQExpBuffer(dropped);
9009 destroyPQExpBuffer(delq);
9010 destroyPQExpBuffer(labelq);
9011 destroyPQExpBuffer(query);
9013 /* Dump any per-column comments */
9014 dumpCompositeTypeColComments(fout, tyinfo);
9018 * dumpCompositeTypeColComments
9019 * writes out to fout the queries to recreate comments on the columns of
9020 * a user-defined stand-alone composite type
9023 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
9025 CommentItem *comments;
9036 query = createPQExpBuffer();
9038 /* We assume here that remoteVersion must be at least 70300 */
9039 appendPQExpBuffer(query,
9040 "SELECT c.tableoid, a.attname, a.attnum "
9041 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
9042 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
9043 " AND NOT a.attisdropped "
9044 "ORDER BY a.attnum ",
9047 /* Fetch column attnames */
9048 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9050 ntups = PQntuples(res);
9054 destroyPQExpBuffer(query);
9058 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
9060 /* Search for comments associated with type's pg_class OID */
9061 ncomments = findComments(fout,
9066 /* If no comments exist, we're done */
9070 destroyPQExpBuffer(query);
9074 /* Build COMMENT ON statements */
9075 target = createPQExpBuffer();
9077 i_attnum = PQfnumber(res, "attnum");
9078 i_attname = PQfnumber(res, "attname");
9079 while (ncomments > 0)
9081 const char *attname;
9084 for (i = 0; i < ntups; i++)
9086 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
9088 attname = PQgetvalue(res, i, i_attname);
9092 if (attname) /* just in case we don't find it */
9094 const char *descr = comments->descr;
9096 resetPQExpBuffer(target);
9097 appendPQExpBuffer(target, "COLUMN %s.",
9098 fmtId(tyinfo->dobj.name));
9099 appendPQExpBuffer(target, "%s",
9102 resetPQExpBuffer(query);
9103 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9104 appendStringLiteralAH(query, descr, fout);
9105 appendPQExpBuffer(query, ";\n");
9107 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9109 tyinfo->dobj.namespace->dobj.name,
9110 NULL, tyinfo->rolname,
9111 false, "COMMENT", SECTION_NONE,
9112 query->data, "", NULL,
9113 &(tyinfo->dobj.dumpId), 1,
9122 destroyPQExpBuffer(query);
9123 destroyPQExpBuffer(target);
9128 * writes out to fout the queries to create a shell type
9130 * We dump a shell definition in advance of the I/O functions for the type.
9133 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
9137 /* Skip if not to be dumped */
9138 if (!stinfo->dobj.dump || dataOnly)
9141 q = createPQExpBuffer();
9144 * Note the lack of a DROP command for the shell type; any required DROP
9145 * is driven off the base type entry, instead. This interacts with
9146 * _printTocEntry()'s use of the presence of a DROP command to decide
9147 * whether an entry needs an ALTER OWNER command. We don't want to alter
9148 * the shell type's owner immediately on creation; that should happen only
9149 * after it's filled in, otherwise the backend complains.
9153 binary_upgrade_set_type_oids_by_type_oid(fout, q,
9154 stinfo->baseType->dobj.catId.oid);
9156 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
9157 fmtId(stinfo->dobj.name));
9159 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
9161 stinfo->dobj.namespace->dobj.name,
9163 stinfo->baseType->rolname, false,
9164 "SHELL TYPE", SECTION_PRE_DATA,
9169 destroyPQExpBuffer(q);
9173 * Determine whether we want to dump definitions for procedural languages.
9174 * Since the languages themselves don't have schemas, we can't rely on
9175 * the normal schema-based selection mechanism. We choose to dump them
9176 * whenever neither --schema nor --table was given. (Before 8.1, we used
9177 * the dump flag of the PL's call handler function, but in 8.1 this will
9178 * probably always be false since call handlers are created in pg_catalog.)
9180 * For some backwards compatibility with the older behavior, we forcibly
9181 * dump a PL if its handler function (and validator if any) are in a
9182 * dumpable namespace. That case is not checked here.
9184 * Also, if the PL belongs to an extension, we do not use this heuristic.
9185 * That case isn't checked here either.
9188 shouldDumpProcLangs(void)
9190 if (!include_everything)
9192 /* And they're schema not data */
9200 * writes out to fout the queries to recreate a user-defined
9201 * procedural language
9204 dumpProcLang(Archive *fout, ProcLangInfo *plang)
9213 FuncInfo *inlineInfo = NULL;
9214 FuncInfo *validatorInfo = NULL;
9216 /* Skip if not to be dumped */
9217 if (!plang->dobj.dump || dataOnly)
9221 * Try to find the support function(s). It is not an error if we don't
9222 * find them --- if the functions are in the pg_catalog schema, as is
9223 * standard in 8.1 and up, then we won't have loaded them. (In this case
9224 * we will emit a parameterless CREATE LANGUAGE command, which will
9225 * require PL template knowledge in the backend to reload.)
9228 funcInfo = findFuncByOid(plang->lanplcallfoid);
9229 if (funcInfo != NULL && !funcInfo->dobj.dump)
9230 funcInfo = NULL; /* treat not-dumped same as not-found */
9232 if (OidIsValid(plang->laninline))
9234 inlineInfo = findFuncByOid(plang->laninline);
9235 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
9239 if (OidIsValid(plang->lanvalidator))
9241 validatorInfo = findFuncByOid(plang->lanvalidator);
9242 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
9243 validatorInfo = NULL;
9247 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
9248 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
9251 * However, for a language that belongs to an extension, we must not use
9252 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
9253 * told to (via dobj.dump). Generally the support functions will belong
9254 * to the same extension and so have the same dump flags ... if they
9255 * don't, this might not work terribly nicely.
9257 useParams = (funcInfo != NULL &&
9258 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
9259 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
9261 if (!plang->dobj.ext_member)
9263 if (!useParams && !shouldDumpProcLangs())
9267 defqry = createPQExpBuffer();
9268 delqry = createPQExpBuffer();
9269 labelq = createPQExpBuffer();
9271 qlanname = pg_strdup(fmtId(plang->dobj.name));
9274 * If dumping a HANDLER clause, treat the language as being in the handler
9275 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
9276 * it doesn't really have a schema.
9279 lanschema = funcInfo->dobj.namespace->dobj.name;
9283 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
9288 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
9289 plang->lanpltrusted ? "TRUSTED " : "",
9291 appendPQExpBuffer(defqry, " HANDLER %s",
9292 fmtId(funcInfo->dobj.name));
9293 if (OidIsValid(plang->laninline))
9295 appendPQExpBuffer(defqry, " INLINE ");
9296 /* Cope with possibility that inline is in different schema */
9297 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
9298 appendPQExpBuffer(defqry, "%s.",
9299 fmtId(inlineInfo->dobj.namespace->dobj.name));
9300 appendPQExpBuffer(defqry, "%s",
9301 fmtId(inlineInfo->dobj.name));
9303 if (OidIsValid(plang->lanvalidator))
9305 appendPQExpBuffer(defqry, " VALIDATOR ");
9306 /* Cope with possibility that validator is in different schema */
9307 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
9308 appendPQExpBuffer(defqry, "%s.",
9309 fmtId(validatorInfo->dobj.namespace->dobj.name));
9310 appendPQExpBuffer(defqry, "%s",
9311 fmtId(validatorInfo->dobj.name));
9317 * If not dumping parameters, then use CREATE OR REPLACE so that the
9318 * command will not fail if the language is preinstalled in the target
9319 * database. We restrict the use of REPLACE to this case so as to
9320 * eliminate the risk of replacing a language with incompatible
9321 * parameter settings: this command will only succeed at all if there
9322 * is a pg_pltemplate entry, and if there is one, the existing entry
9323 * must match it too.
9325 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
9328 appendPQExpBuffer(defqry, ";\n");
9330 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
9333 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
9335 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
9337 lanschema, NULL, plang->lanowner,
9338 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
9339 defqry->data, delqry->data, NULL,
9343 /* Dump Proc Lang Comments and Security Labels */
9344 dumpComment(fout, labelq->data,
9346 plang->dobj.catId, 0, plang->dobj.dumpId);
9347 dumpSecLabel(fout, labelq->data,
9349 plang->dobj.catId, 0, plang->dobj.dumpId);
9351 if (plang->lanpltrusted)
9352 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
9353 qlanname, NULL, plang->dobj.name,
9355 plang->lanowner, plang->lanacl);
9359 destroyPQExpBuffer(defqry);
9360 destroyPQExpBuffer(delqry);
9361 destroyPQExpBuffer(labelq);
9365 * format_function_arguments: generate function name and argument list
9367 * This is used when we can rely on pg_get_function_arguments to format
9368 * the argument list.
9371 format_function_arguments(FuncInfo *finfo, char *funcargs)
9375 initPQExpBuffer(&fn);
9376 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9381 * format_function_arguments_old: generate function name and argument list
9383 * The argument type names are qualified if needed. The function name
9384 * is never qualified.
9386 * This is used only with pre-8.4 servers, so we aren't expecting to see
9387 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9389 * Any or all of allargtypes, argmodes, argnames may be NULL.
9392 format_function_arguments_old(Archive *fout,
9393 FuncInfo *finfo, int nallargs,
9401 initPQExpBuffer(&fn);
9402 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9403 for (j = 0; j < nallargs; j++)
9407 const char *argmode;
9408 const char *argname;
9410 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9411 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9415 switch (argmodes[j][0])
9420 case PROARGMODE_OUT:
9423 case PROARGMODE_INOUT:
9427 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9435 argname = argnames ? argnames[j] : (char *) NULL;
9436 if (argname && argname[0] == '\0')
9439 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9440 (j > 0) ? ", " : "",
9442 argname ? fmtId(argname) : "",
9447 appendPQExpBuffer(&fn, ")");
9452 * format_function_signature: generate function name and argument list
9454 * This is like format_function_arguments_old except that only a minimal
9455 * list of input argument types is generated; this is sufficient to
9456 * reference the function, but not to define it.
9458 * If honor_quotes is false then the function name is never quoted.
9459 * This is appropriate for use in TOC tags, but not in SQL commands.
9462 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9467 initPQExpBuffer(&fn);
9469 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9471 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9472 for (j = 0; j < finfo->nargs; j++)
9476 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9479 appendPQExpBuffer(&fn, "%s%s",
9480 (j > 0) ? ", " : "",
9484 appendPQExpBuffer(&fn, ")");
9491 * dump out one function
9494 dumpFunc(Archive *fout, FuncInfo *finfo)
9502 char *funcsig; /* identity signature */
9503 char *funcfullsig; /* full signature */
9511 char *proallargtypes;
9525 char **allargtypes = NULL;
9526 char **argmodes = NULL;
9527 char **argnames = NULL;
9528 char **configitems = NULL;
9529 int nconfigitems = 0;
9532 /* Skip if not to be dumped */
9533 if (!finfo->dobj.dump || dataOnly)
9536 query = createPQExpBuffer();
9537 q = createPQExpBuffer();
9538 delqry = createPQExpBuffer();
9539 labelq = createPQExpBuffer();
9540 asPart = createPQExpBuffer();
9542 /* Set proper schema search path so type references list correctly */
9543 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9545 /* Fetch function-specific details */
9546 if (fout->remoteVersion >= 90200)
9549 * proleakproof was added at v9.2
9551 appendPQExpBuffer(query,
9552 "SELECT proretset, prosrc, probin, "
9553 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9554 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9555 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9556 "proiswindow, provolatile, proisstrict, prosecdef, "
9557 "proleakproof, proconfig, procost, prorows, "
9558 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9559 "FROM pg_catalog.pg_proc "
9560 "WHERE oid = '%u'::pg_catalog.oid",
9561 finfo->dobj.catId.oid);
9563 else if (fout->remoteVersion >= 80400)
9566 * In 8.4 and up we rely on pg_get_function_arguments and
9567 * pg_get_function_result instead of examining proallargtypes etc.
9569 appendPQExpBuffer(query,
9570 "SELECT proretset, prosrc, probin, "
9571 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9572 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9573 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9574 "proiswindow, provolatile, proisstrict, prosecdef, "
9575 "false AS proleakproof, "
9576 " proconfig, procost, prorows, "
9577 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9578 "FROM pg_catalog.pg_proc "
9579 "WHERE oid = '%u'::pg_catalog.oid",
9580 finfo->dobj.catId.oid);
9582 else if (fout->remoteVersion >= 80300)
9584 appendPQExpBuffer(query,
9585 "SELECT proretset, prosrc, probin, "
9586 "proallargtypes, proargmodes, proargnames, "
9587 "false AS proiswindow, "
9588 "provolatile, proisstrict, prosecdef, "
9589 "false AS proleakproof, "
9590 "proconfig, procost, prorows, "
9591 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9592 "FROM pg_catalog.pg_proc "
9593 "WHERE oid = '%u'::pg_catalog.oid",
9594 finfo->dobj.catId.oid);
9596 else if (fout->remoteVersion >= 80100)
9598 appendPQExpBuffer(query,
9599 "SELECT proretset, prosrc, probin, "
9600 "proallargtypes, proargmodes, proargnames, "
9601 "false AS proiswindow, "
9602 "provolatile, proisstrict, prosecdef, "
9603 "false AS proleakproof, "
9604 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9605 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9606 "FROM pg_catalog.pg_proc "
9607 "WHERE oid = '%u'::pg_catalog.oid",
9608 finfo->dobj.catId.oid);
9610 else if (fout->remoteVersion >= 80000)
9612 appendPQExpBuffer(query,
9613 "SELECT proretset, prosrc, probin, "
9614 "null AS proallargtypes, "
9615 "null AS proargmodes, "
9617 "false AS proiswindow, "
9618 "provolatile, proisstrict, prosecdef, "
9619 "false AS proleakproof, "
9620 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9621 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9622 "FROM pg_catalog.pg_proc "
9623 "WHERE oid = '%u'::pg_catalog.oid",
9624 finfo->dobj.catId.oid);
9626 else if (fout->remoteVersion >= 70300)
9628 appendPQExpBuffer(query,
9629 "SELECT proretset, prosrc, probin, "
9630 "null AS proallargtypes, "
9631 "null AS proargmodes, "
9632 "null AS proargnames, "
9633 "false AS proiswindow, "
9634 "provolatile, proisstrict, prosecdef, "
9635 "false AS proleakproof, "
9636 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9637 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9638 "FROM pg_catalog.pg_proc "
9639 "WHERE oid = '%u'::pg_catalog.oid",
9640 finfo->dobj.catId.oid);
9642 else if (fout->remoteVersion >= 70100)
9644 appendPQExpBuffer(query,
9645 "SELECT proretset, prosrc, probin, "
9646 "null AS proallargtypes, "
9647 "null AS proargmodes, "
9648 "null AS proargnames, "
9649 "false AS proiswindow, "
9650 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9652 "false AS prosecdef, "
9653 "false AS proleakproof, "
9654 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9655 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9657 "WHERE oid = '%u'::oid",
9658 finfo->dobj.catId.oid);
9662 appendPQExpBuffer(query,
9663 "SELECT proretset, prosrc, probin, "
9664 "null AS proallargtypes, "
9665 "null AS proargmodes, "
9666 "null AS proargnames, "
9667 "false AS proiswindow, "
9668 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9669 "false AS proisstrict, "
9670 "false AS prosecdef, "
9671 "false AS proleakproof, "
9672 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9673 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9675 "WHERE oid = '%u'::oid",
9676 finfo->dobj.catId.oid);
9679 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9681 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9682 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9683 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9684 if (fout->remoteVersion >= 80400)
9686 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9687 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9688 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9689 proallargtypes = proargmodes = proargnames = NULL;
9693 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9694 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9695 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9696 funcargs = funciargs = funcresult = NULL;
9698 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9699 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9700 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9701 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9702 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9703 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9704 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9705 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9706 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9709 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9710 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9711 * versions would set it to "-". There are no known cases in which prosrc
9712 * is unused, so the tests below for "-" are probably useless.
9714 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9716 appendPQExpBuffer(asPart, "AS ");
9717 appendStringLiteralAH(asPart, probin, fout);
9718 if (strcmp(prosrc, "-") != 0)
9720 appendPQExpBuffer(asPart, ", ");
9723 * where we have bin, use dollar quoting if allowed and src
9724 * contains quote or backslash; else use regular quoting.
9726 if (disable_dollar_quoting ||
9727 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9728 appendStringLiteralAH(asPart, prosrc, fout);
9730 appendStringLiteralDQ(asPart, prosrc, NULL);
9735 if (strcmp(prosrc, "-") != 0)
9737 appendPQExpBuffer(asPart, "AS ");
9738 /* with no bin, dollar quote src unconditionally if allowed */
9739 if (disable_dollar_quoting)
9740 appendStringLiteralAH(asPart, prosrc, fout);
9742 appendStringLiteralDQ(asPart, prosrc, NULL);
9746 nallargs = finfo->nargs; /* unless we learn different from allargs */
9748 if (proallargtypes && *proallargtypes)
9752 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9753 nitems < finfo->nargs)
9755 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9764 if (proargmodes && *proargmodes)
9768 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9771 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9778 if (proargnames && *proargnames)
9782 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9785 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9792 if (proconfig && *proconfig)
9794 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9796 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9806 /* 8.4 or later; we rely on server-side code for most of the work */
9807 funcfullsig = format_function_arguments(finfo, funcargs);
9808 funcsig = format_function_arguments(finfo, funciargs);
9812 /* pre-8.4, do it ourselves */
9813 funcsig = format_function_arguments_old(fout,
9814 finfo, nallargs, allargtypes,
9815 argmodes, argnames);
9816 funcfullsig = funcsig;
9819 funcsig_tag = format_function_signature(fout, finfo, false);
9822 * DROP must be fully qualified in case same name appears in pg_catalog
9824 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9825 fmtId(finfo->dobj.namespace->dobj.name),
9828 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9830 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9833 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9835 appendPQExpBuffer(q, "RETURNS %s%s",
9836 (proretset[0] == 't') ? "SETOF " : "",
9841 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9843 if (proiswindow[0] == 't')
9844 appendPQExpBuffer(q, " WINDOW");
9846 if (provolatile[0] != PROVOLATILE_VOLATILE)
9848 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9849 appendPQExpBuffer(q, " IMMUTABLE");
9850 else if (provolatile[0] == PROVOLATILE_STABLE)
9851 appendPQExpBuffer(q, " STABLE");
9852 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9853 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9857 if (proisstrict[0] == 't')
9858 appendPQExpBuffer(q, " STRICT");
9860 if (prosecdef[0] == 't')
9861 appendPQExpBuffer(q, " SECURITY DEFINER");
9863 if (proleakproof[0] == 't')
9864 appendPQExpBuffer(q, " LEAKPROOF");
9867 * COST and ROWS are emitted only if present and not default, so as not to
9868 * break backwards-compatibility of the dump without need. Keep this code
9869 * in sync with the defaults in functioncmds.c.
9871 if (strcmp(procost, "0") != 0)
9873 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9875 /* default cost is 1 */
9876 if (strcmp(procost, "1") != 0)
9877 appendPQExpBuffer(q, " COST %s", procost);
9881 /* default cost is 100 */
9882 if (strcmp(procost, "100") != 0)
9883 appendPQExpBuffer(q, " COST %s", procost);
9886 if (proretset[0] == 't' &&
9887 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9888 appendPQExpBuffer(q, " ROWS %s", prorows);
9890 for (i = 0; i < nconfigitems; i++)
9892 /* we feel free to scribble on configitems[] here */
9893 char *configitem = configitems[i];
9896 pos = strchr(configitem, '=');
9900 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9903 * Some GUC variable names are 'LIST' type and hence must not be
9906 if (pg_strcasecmp(configitem, "DateStyle") == 0
9907 || pg_strcasecmp(configitem, "search_path") == 0)
9908 appendPQExpBuffer(q, "%s", pos);
9910 appendStringLiteralAH(q, pos, fout);
9913 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9915 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9918 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9920 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9922 finfo->dobj.namespace->dobj.name,
9924 finfo->rolname, false,
9925 "FUNCTION", SECTION_PRE_DATA,
9926 q->data, delqry->data, NULL,
9930 /* Dump Function Comments and Security Labels */
9931 dumpComment(fout, labelq->data,
9932 finfo->dobj.namespace->dobj.name, finfo->rolname,
9933 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9934 dumpSecLabel(fout, labelq->data,
9935 finfo->dobj.namespace->dobj.name, finfo->rolname,
9936 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9938 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9939 funcsig, NULL, funcsig_tag,
9940 finfo->dobj.namespace->dobj.name,
9941 finfo->rolname, finfo->proacl);
9945 destroyPQExpBuffer(query);
9946 destroyPQExpBuffer(q);
9947 destroyPQExpBuffer(delqry);
9948 destroyPQExpBuffer(labelq);
9949 destroyPQExpBuffer(asPart);
9964 * Dump a user-defined cast
9967 dumpCast(Archive *fout, CastInfo *cast)
9972 FuncInfo *funcInfo = NULL;
9974 /* Skip if not to be dumped */
9975 if (!cast->dobj.dump || dataOnly)
9978 /* Cannot dump if we don't have the cast function's info */
9979 if (OidIsValid(cast->castfunc))
9981 funcInfo = findFuncByOid(cast->castfunc);
9982 if (funcInfo == NULL)
9987 * As per discussion we dump casts if one or more of the underlying
9988 * objects (the conversion function and the two data types) are not
9989 * builtin AND if all of the non-builtin objects are included in the dump.
9990 * Builtin meaning, the namespace name does not start with "pg_".
9992 * However, for a cast that belongs to an extension, we must not use this
9993 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9995 if (!cast->dobj.ext_member)
9997 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9998 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
10000 if (sourceInfo == NULL || targetInfo == NULL)
10004 * Skip this cast if all objects are from pg_
10006 if ((funcInfo == NULL ||
10007 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
10008 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
10009 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
10013 * Skip cast if function isn't from pg_ and is not to be dumped.
10016 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10017 !funcInfo->dobj.dump)
10021 * Same for the source type
10023 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10024 !sourceInfo->dobj.dump)
10028 * and the target type.
10030 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10031 !targetInfo->dobj.dump)
10035 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
10036 selectSourceSchema(fout, "pg_catalog");
10038 defqry = createPQExpBuffer();
10039 delqry = createPQExpBuffer();
10040 labelq = createPQExpBuffer();
10042 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
10043 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10044 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10046 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
10047 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10048 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10050 switch (cast->castmethod)
10052 case COERCION_METHOD_BINARY:
10053 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
10055 case COERCION_METHOD_INOUT:
10056 appendPQExpBuffer(defqry, "WITH INOUT");
10058 case COERCION_METHOD_FUNCTION:
10061 char *fsig = format_function_signature(fout, funcInfo, true);
10064 * Always qualify the function name, in case it is not in
10065 * pg_catalog schema (format_function_signature won't qualify
10068 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
10069 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
10073 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
10076 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
10079 if (cast->castcontext == 'a')
10080 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
10081 else if (cast->castcontext == 'i')
10082 appendPQExpBuffer(defqry, " AS IMPLICIT");
10083 appendPQExpBuffer(defqry, ";\n");
10085 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
10086 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10087 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10089 if (binary_upgrade)
10090 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
10092 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
10094 "pg_catalog", NULL, "",
10095 false, "CAST", SECTION_PRE_DATA,
10096 defqry->data, delqry->data, NULL,
10100 /* Dump Cast Comments */
10101 dumpComment(fout, labelq->data,
10103 cast->dobj.catId, 0, cast->dobj.dumpId);
10105 destroyPQExpBuffer(defqry);
10106 destroyPQExpBuffer(delqry);
10107 destroyPQExpBuffer(labelq);
10112 * write out a single operator definition
10115 dumpOpr(Archive *fout, OprInfo *oprinfo)
10120 PQExpBuffer labelq;
10122 PQExpBuffer details;
10146 /* Skip if not to be dumped */
10147 if (!oprinfo->dobj.dump || dataOnly)
10151 * some operators are invalid because they were the result of user
10152 * defining operators before commutators exist
10154 if (!OidIsValid(oprinfo->oprcode))
10157 query = createPQExpBuffer();
10158 q = createPQExpBuffer();
10159 delq = createPQExpBuffer();
10160 labelq = createPQExpBuffer();
10161 oprid = createPQExpBuffer();
10162 details = createPQExpBuffer();
10164 /* Make sure we are in proper schema so regoperator works correctly */
10165 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
10167 if (fout->remoteVersion >= 80300)
10169 appendPQExpBuffer(query, "SELECT oprkind, "
10170 "oprcode::pg_catalog.regprocedure, "
10171 "oprleft::pg_catalog.regtype, "
10172 "oprright::pg_catalog.regtype, "
10173 "oprcom::pg_catalog.regoperator, "
10174 "oprnegate::pg_catalog.regoperator, "
10175 "oprrest::pg_catalog.regprocedure, "
10176 "oprjoin::pg_catalog.regprocedure, "
10177 "oprcanmerge, oprcanhash "
10178 "FROM pg_catalog.pg_operator "
10179 "WHERE oid = '%u'::pg_catalog.oid",
10180 oprinfo->dobj.catId.oid);
10182 else if (fout->remoteVersion >= 70300)
10184 appendPQExpBuffer(query, "SELECT oprkind, "
10185 "oprcode::pg_catalog.regprocedure, "
10186 "oprleft::pg_catalog.regtype, "
10187 "oprright::pg_catalog.regtype, "
10188 "oprcom::pg_catalog.regoperator, "
10189 "oprnegate::pg_catalog.regoperator, "
10190 "oprrest::pg_catalog.regprocedure, "
10191 "oprjoin::pg_catalog.regprocedure, "
10192 "(oprlsortop != 0) AS oprcanmerge, "
10194 "FROM pg_catalog.pg_operator "
10195 "WHERE oid = '%u'::pg_catalog.oid",
10196 oprinfo->dobj.catId.oid);
10198 else if (fout->remoteVersion >= 70100)
10200 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10201 "CASE WHEN oprleft = 0 THEN '-' "
10202 "ELSE format_type(oprleft, NULL) END AS oprleft, "
10203 "CASE WHEN oprright = 0 THEN '-' "
10204 "ELSE format_type(oprright, NULL) END AS oprright, "
10205 "oprcom, oprnegate, oprrest, oprjoin, "
10206 "(oprlsortop != 0) AS oprcanmerge, "
10208 "FROM pg_operator "
10209 "WHERE oid = '%u'::oid",
10210 oprinfo->dobj.catId.oid);
10214 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10215 "CASE WHEN oprleft = 0 THEN '-'::name "
10216 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
10217 "CASE WHEN oprright = 0 THEN '-'::name "
10218 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
10219 "oprcom, oprnegate, oprrest, oprjoin, "
10220 "(oprlsortop != 0) AS oprcanmerge, "
10222 "FROM pg_operator "
10223 "WHERE oid = '%u'::oid",
10224 oprinfo->dobj.catId.oid);
10227 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10229 i_oprkind = PQfnumber(res, "oprkind");
10230 i_oprcode = PQfnumber(res, "oprcode");
10231 i_oprleft = PQfnumber(res, "oprleft");
10232 i_oprright = PQfnumber(res, "oprright");
10233 i_oprcom = PQfnumber(res, "oprcom");
10234 i_oprnegate = PQfnumber(res, "oprnegate");
10235 i_oprrest = PQfnumber(res, "oprrest");
10236 i_oprjoin = PQfnumber(res, "oprjoin");
10237 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
10238 i_oprcanhash = PQfnumber(res, "oprcanhash");
10240 oprkind = PQgetvalue(res, 0, i_oprkind);
10241 oprcode = PQgetvalue(res, 0, i_oprcode);
10242 oprleft = PQgetvalue(res, 0, i_oprleft);
10243 oprright = PQgetvalue(res, 0, i_oprright);
10244 oprcom = PQgetvalue(res, 0, i_oprcom);
10245 oprnegate = PQgetvalue(res, 0, i_oprnegate);
10246 oprrest = PQgetvalue(res, 0, i_oprrest);
10247 oprjoin = PQgetvalue(res, 0, i_oprjoin);
10248 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
10249 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
10251 appendPQExpBuffer(details, " PROCEDURE = %s",
10252 convertRegProcReference(fout, oprcode));
10254 appendPQExpBuffer(oprid, "%s (",
10255 oprinfo->dobj.name);
10258 * right unary means there's a left arg and left unary means there's a
10261 if (strcmp(oprkind, "r") == 0 ||
10262 strcmp(oprkind, "b") == 0)
10264 if (fout->remoteVersion >= 70100)
10267 name = fmtId(oprleft);
10268 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
10269 appendPQExpBuffer(oprid, "%s", name);
10272 appendPQExpBuffer(oprid, "NONE");
10274 if (strcmp(oprkind, "l") == 0 ||
10275 strcmp(oprkind, "b") == 0)
10277 if (fout->remoteVersion >= 70100)
10280 name = fmtId(oprright);
10281 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
10282 appendPQExpBuffer(oprid, ", %s)", name);
10285 appendPQExpBuffer(oprid, ", NONE)");
10287 name = convertOperatorReference(fout, oprcom);
10289 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
10291 name = convertOperatorReference(fout, oprnegate);
10293 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
10295 if (strcmp(oprcanmerge, "t") == 0)
10296 appendPQExpBuffer(details, ",\n MERGES");
10298 if (strcmp(oprcanhash, "t") == 0)
10299 appendPQExpBuffer(details, ",\n HASHES");
10301 name = convertRegProcReference(fout, oprrest);
10303 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
10305 name = convertRegProcReference(fout, oprjoin);
10307 appendPQExpBuffer(details, ",\n JOIN = %s", name);
10310 * DROP must be fully qualified in case same name appears in pg_catalog
10312 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
10313 fmtId(oprinfo->dobj.namespace->dobj.name),
10316 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
10317 oprinfo->dobj.name, details->data);
10319 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
10321 if (binary_upgrade)
10322 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
10324 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
10325 oprinfo->dobj.name,
10326 oprinfo->dobj.namespace->dobj.name,
10329 false, "OPERATOR", SECTION_PRE_DATA,
10330 q->data, delq->data, NULL,
10334 /* Dump Operator Comments */
10335 dumpComment(fout, labelq->data,
10336 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
10337 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
10341 destroyPQExpBuffer(query);
10342 destroyPQExpBuffer(q);
10343 destroyPQExpBuffer(delq);
10344 destroyPQExpBuffer(labelq);
10345 destroyPQExpBuffer(oprid);
10346 destroyPQExpBuffer(details);
10350 * Convert a function reference obtained from pg_operator
10352 * Returns what to print, or NULL if function references is InvalidOid
10354 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
10355 * argument-types part. In prior versions, the input is a REGPROC display.
10357 static const char *
10358 convertRegProcReference(Archive *fout, const char *proc)
10360 /* In all cases "-" means a null reference */
10361 if (strcmp(proc, "-") == 0)
10364 if (fout->remoteVersion >= 70300)
10370 name = pg_strdup(proc);
10371 /* find non-double-quoted left paren */
10373 for (paren = name; *paren; paren++)
10375 if (*paren == '(' && !inquote)
10381 inquote = !inquote;
10386 /* REGPROC before 7.3 does not quote its result */
10387 return fmtId(proc);
10391 * Convert an operator cross-reference obtained from pg_operator
10393 * Returns what to print, or NULL to print nothing
10395 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10396 * argument-types part, and add OPERATOR() decoration if the name is
10397 * schema-qualified. In older versions, the input is just a numeric OID,
10398 * which we search our operator list for.
10400 static const char *
10401 convertOperatorReference(Archive *fout, const char *opr)
10405 /* In all cases "0" means a null reference */
10406 if (strcmp(opr, "0") == 0)
10409 if (fout->remoteVersion >= 70300)
10417 name = pg_strdup(opr);
10418 /* find non-double-quoted left paren, and check for non-quoted dot */
10421 for (ptr = name; *ptr; ptr++)
10424 inquote = !inquote;
10425 else if (*ptr == '.' && !inquote)
10427 else if (*ptr == '(' && !inquote)
10433 /* If not schema-qualified, don't need to add OPERATOR() */
10436 oname = pg_malloc(strlen(name) + 11);
10437 sprintf(oname, "OPERATOR(%s)", name);
10442 oprInfo = findOprByOid(atooid(opr));
10443 if (oprInfo == NULL)
10445 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10449 return oprInfo->dobj.name;
10453 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10455 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10456 * argument lists of these functions are predetermined. Note that the
10457 * caller should ensure we are in the proper schema, because the results
10458 * are search path dependent!
10460 static const char *
10461 convertTSFunction(Archive *fout, Oid funcOid)
10467 snprintf(query, sizeof(query),
10468 "SELECT '%u'::pg_catalog.regproc", funcOid);
10469 res = ExecuteSqlQueryForSingleRow(fout, query);
10471 result = pg_strdup(PQgetvalue(res, 0, 0));
10481 * write out a single operator class definition
10484 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10489 PQExpBuffer labelq;
10496 int i_opcfamilyname;
10497 int i_opcfamilynsp;
10499 int i_amopstrategy;
10500 int i_amopreqcheck;
10503 int i_sortfamilynsp;
10506 int i_amproclefttype;
10507 int i_amprocrighttype;
10512 char *opcfamilyname;
10513 char *opcfamilynsp;
10515 char *amopstrategy;
10516 char *amopreqcheck;
10519 char *sortfamilynsp;
10522 char *amproclefttype;
10523 char *amprocrighttype;
10527 /* Skip if not to be dumped */
10528 if (!opcinfo->dobj.dump || dataOnly)
10532 * XXX currently we do not implement dumping of operator classes from
10533 * pre-7.3 databases. This could be done but it seems not worth the
10536 if (fout->remoteVersion < 70300)
10539 query = createPQExpBuffer();
10540 q = createPQExpBuffer();
10541 delq = createPQExpBuffer();
10542 labelq = createPQExpBuffer();
10544 /* Make sure we are in proper schema so regoperator works correctly */
10545 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10547 /* Get additional fields from the pg_opclass row */
10548 if (fout->remoteVersion >= 80300)
10550 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10551 "opckeytype::pg_catalog.regtype, "
10552 "opcdefault, opcfamily, "
10553 "opfname AS opcfamilyname, "
10554 "nspname AS opcfamilynsp, "
10555 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10556 "FROM pg_catalog.pg_opclass c "
10557 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10558 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10559 "WHERE c.oid = '%u'::pg_catalog.oid",
10560 opcinfo->dobj.catId.oid);
10564 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10565 "opckeytype::pg_catalog.regtype, "
10566 "opcdefault, NULL AS opcfamily, "
10567 "NULL AS opcfamilyname, "
10568 "NULL AS opcfamilynsp, "
10569 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10570 "FROM pg_catalog.pg_opclass "
10571 "WHERE oid = '%u'::pg_catalog.oid",
10572 opcinfo->dobj.catId.oid);
10575 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10577 i_opcintype = PQfnumber(res, "opcintype");
10578 i_opckeytype = PQfnumber(res, "opckeytype");
10579 i_opcdefault = PQfnumber(res, "opcdefault");
10580 i_opcfamily = PQfnumber(res, "opcfamily");
10581 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10582 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10583 i_amname = PQfnumber(res, "amname");
10585 opcintype = PQgetvalue(res, 0, i_opcintype);
10586 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10587 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10588 /* opcfamily will still be needed after we PQclear res */
10589 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10590 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10591 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10592 /* amname will still be needed after we PQclear res */
10593 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10596 * DROP must be fully qualified in case same name appears in pg_catalog
10598 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10599 fmtId(opcinfo->dobj.namespace->dobj.name));
10600 appendPQExpBuffer(delq, ".%s",
10601 fmtId(opcinfo->dobj.name));
10602 appendPQExpBuffer(delq, " USING %s;\n",
10605 /* Build the fixed portion of the CREATE command */
10606 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10607 fmtId(opcinfo->dobj.name));
10608 if (strcmp(opcdefault, "t") == 0)
10609 appendPQExpBuffer(q, "DEFAULT ");
10610 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10613 if (strlen(opcfamilyname) > 0 &&
10614 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10615 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10617 appendPQExpBuffer(q, " FAMILY ");
10618 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10619 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10620 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10622 appendPQExpBuffer(q, " AS\n ");
10626 if (strcmp(opckeytype, "-") != 0)
10628 appendPQExpBuffer(q, "STORAGE %s",
10636 * Now fetch and print the OPERATOR entries (pg_amop rows).
10638 * Print only those opfamily members that are tied to the opclass by
10639 * pg_depend entries.
10641 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10642 * older server's opclass in which it is used. This is to avoid
10643 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10644 * older server and then reload into that old version. This can go away
10645 * once 8.3 is so old as to not be of interest to anyone.
10647 resetPQExpBuffer(query);
10649 if (fout->remoteVersion >= 90100)
10651 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10652 "amopopr::pg_catalog.regoperator, "
10653 "opfname AS sortfamily, "
10654 "nspname AS sortfamilynsp "
10655 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10656 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10657 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10658 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10659 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10660 "AND refobjid = '%u'::pg_catalog.oid "
10661 "AND amopfamily = '%s'::pg_catalog.oid "
10662 "ORDER BY amopstrategy",
10663 opcinfo->dobj.catId.oid,
10666 else if (fout->remoteVersion >= 80400)
10668 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10669 "amopopr::pg_catalog.regoperator, "
10670 "NULL AS sortfamily, "
10671 "NULL AS sortfamilynsp "
10672 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10673 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10674 "AND refobjid = '%u'::pg_catalog.oid "
10675 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10676 "AND objid = ao.oid "
10677 "ORDER BY amopstrategy",
10678 opcinfo->dobj.catId.oid);
10680 else if (fout->remoteVersion >= 80300)
10682 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10683 "amopopr::pg_catalog.regoperator, "
10684 "NULL AS sortfamily, "
10685 "NULL AS sortfamilynsp "
10686 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10687 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10688 "AND refobjid = '%u'::pg_catalog.oid "
10689 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10690 "AND objid = ao.oid "
10691 "ORDER BY amopstrategy",
10692 opcinfo->dobj.catId.oid);
10697 * Here, we print all entries since there are no opfamilies and hence
10698 * no loose operators to worry about.
10700 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10701 "amopopr::pg_catalog.regoperator, "
10702 "NULL AS sortfamily, "
10703 "NULL AS sortfamilynsp "
10704 "FROM pg_catalog.pg_amop "
10705 "WHERE amopclaid = '%u'::pg_catalog.oid "
10706 "ORDER BY amopstrategy",
10707 opcinfo->dobj.catId.oid);
10710 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10712 ntups = PQntuples(res);
10714 i_amopstrategy = PQfnumber(res, "amopstrategy");
10715 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10716 i_amopopr = PQfnumber(res, "amopopr");
10717 i_sortfamily = PQfnumber(res, "sortfamily");
10718 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10720 for (i = 0; i < ntups; i++)
10722 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10723 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10724 amopopr = PQgetvalue(res, i, i_amopopr);
10725 sortfamily = PQgetvalue(res, i, i_sortfamily);
10726 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10729 appendPQExpBuffer(q, " ,\n ");
10731 appendPQExpBuffer(q, "OPERATOR %s %s",
10732 amopstrategy, amopopr);
10734 if (strlen(sortfamily) > 0)
10736 appendPQExpBuffer(q, " FOR ORDER BY ");
10737 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10738 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10739 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10742 if (strcmp(amopreqcheck, "t") == 0)
10743 appendPQExpBuffer(q, " RECHECK");
10751 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10753 * Print only those opfamily members that are tied to the opclass by
10754 * pg_depend entries.
10756 * We print the amproclefttype/amprocrighttype even though in most cases
10757 * the backend could deduce the right values, because of the corner case
10758 * of a btree sort support function for a cross-type comparison. That's
10759 * only allowed in 9.2 and later, but for simplicity print them in all
10760 * versions that have the columns.
10762 resetPQExpBuffer(query);
10764 if (fout->remoteVersion >= 80300)
10766 appendPQExpBuffer(query, "SELECT amprocnum, "
10767 "amproc::pg_catalog.regprocedure, "
10768 "amproclefttype::pg_catalog.regtype, "
10769 "amprocrighttype::pg_catalog.regtype "
10770 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10771 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10772 "AND refobjid = '%u'::pg_catalog.oid "
10773 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10774 "AND objid = ap.oid "
10775 "ORDER BY amprocnum",
10776 opcinfo->dobj.catId.oid);
10780 appendPQExpBuffer(query, "SELECT amprocnum, "
10781 "amproc::pg_catalog.regprocedure, "
10782 "'' AS amproclefttype, "
10783 "'' AS amprocrighttype "
10784 "FROM pg_catalog.pg_amproc "
10785 "WHERE amopclaid = '%u'::pg_catalog.oid "
10786 "ORDER BY amprocnum",
10787 opcinfo->dobj.catId.oid);
10790 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10792 ntups = PQntuples(res);
10794 i_amprocnum = PQfnumber(res, "amprocnum");
10795 i_amproc = PQfnumber(res, "amproc");
10796 i_amproclefttype = PQfnumber(res, "amproclefttype");
10797 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10799 for (i = 0; i < ntups; i++)
10801 amprocnum = PQgetvalue(res, i, i_amprocnum);
10802 amproc = PQgetvalue(res, i, i_amproc);
10803 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10804 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10807 appendPQExpBuffer(q, " ,\n ");
10809 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10811 if (*amproclefttype && *amprocrighttype)
10812 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10814 appendPQExpBuffer(q, " %s", amproc);
10821 appendPQExpBuffer(q, ";\n");
10823 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10824 fmtId(opcinfo->dobj.name));
10825 appendPQExpBuffer(labelq, " USING %s",
10828 if (binary_upgrade)
10829 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10831 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10832 opcinfo->dobj.name,
10833 opcinfo->dobj.namespace->dobj.name,
10836 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10837 q->data, delq->data, NULL,
10841 /* Dump Operator Class Comments */
10842 dumpComment(fout, labelq->data,
10843 NULL, opcinfo->rolname,
10844 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10847 destroyPQExpBuffer(query);
10848 destroyPQExpBuffer(q);
10849 destroyPQExpBuffer(delq);
10850 destroyPQExpBuffer(labelq);
10855 * write out a single operator family definition
10857 * Note: this also dumps any "loose" operator members that aren't bound to a
10858 * specific opclass within the opfamily.
10861 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10866 PQExpBuffer labelq;
10869 PGresult *res_procs;
10872 int i_amopstrategy;
10873 int i_amopreqcheck;
10876 int i_sortfamilynsp;
10879 int i_amproclefttype;
10880 int i_amprocrighttype;
10882 char *amopstrategy;
10883 char *amopreqcheck;
10886 char *sortfamilynsp;
10889 char *amproclefttype;
10890 char *amprocrighttype;
10894 /* Skip if not to be dumped */
10895 if (!opfinfo->dobj.dump || dataOnly)
10899 * We want to dump the opfamily only if (1) it contains "loose" operators
10900 * or functions, or (2) it contains an opclass with a different name or
10901 * owner. Otherwise it's sufficient to let it be created during creation
10902 * of the contained opclass, and not dumping it improves portability of
10903 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10907 query = createPQExpBuffer();
10908 q = createPQExpBuffer();
10909 delq = createPQExpBuffer();
10910 labelq = createPQExpBuffer();
10912 /* Make sure we are in proper schema so regoperator works correctly */
10913 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10916 * Fetch only those opfamily members that are tied directly to the
10917 * opfamily by pg_depend entries.
10919 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10920 * older server's opclass in which it is used. This is to avoid
10921 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10922 * older server and then reload into that old version. This can go away
10923 * once 8.3 is so old as to not be of interest to anyone.
10925 if (fout->remoteVersion >= 90100)
10927 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10928 "amopopr::pg_catalog.regoperator, "
10929 "opfname AS sortfamily, "
10930 "nspname AS sortfamilynsp "
10931 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10932 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10933 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10934 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10935 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10936 "AND refobjid = '%u'::pg_catalog.oid "
10937 "AND amopfamily = '%u'::pg_catalog.oid "
10938 "ORDER BY amopstrategy",
10939 opfinfo->dobj.catId.oid,
10940 opfinfo->dobj.catId.oid);
10942 else if (fout->remoteVersion >= 80400)
10944 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10945 "amopopr::pg_catalog.regoperator, "
10946 "NULL AS sortfamily, "
10947 "NULL AS sortfamilynsp "
10948 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10949 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10950 "AND refobjid = '%u'::pg_catalog.oid "
10951 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10952 "AND objid = ao.oid "
10953 "ORDER BY amopstrategy",
10954 opfinfo->dobj.catId.oid);
10958 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10959 "amopopr::pg_catalog.regoperator, "
10960 "NULL AS sortfamily, "
10961 "NULL AS sortfamilynsp "
10962 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10963 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10964 "AND refobjid = '%u'::pg_catalog.oid "
10965 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10966 "AND objid = ao.oid "
10967 "ORDER BY amopstrategy",
10968 opfinfo->dobj.catId.oid);
10971 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10973 resetPQExpBuffer(query);
10975 appendPQExpBuffer(query, "SELECT amprocnum, "
10976 "amproc::pg_catalog.regprocedure, "
10977 "amproclefttype::pg_catalog.regtype, "
10978 "amprocrighttype::pg_catalog.regtype "
10979 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10980 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10981 "AND refobjid = '%u'::pg_catalog.oid "
10982 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10983 "AND objid = ap.oid "
10984 "ORDER BY amprocnum",
10985 opfinfo->dobj.catId.oid);
10987 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10989 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10991 /* No loose members, so check contained opclasses */
10992 resetPQExpBuffer(query);
10994 appendPQExpBuffer(query, "SELECT 1 "
10995 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10996 "WHERE f.oid = '%u'::pg_catalog.oid "
10997 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10998 "AND refobjid = f.oid "
10999 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
11000 "AND objid = c.oid "
11001 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
11003 opfinfo->dobj.catId.oid);
11005 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11007 if (PQntuples(res) == 0)
11009 /* no need to dump it, so bail out */
11012 PQclear(res_procs);
11013 destroyPQExpBuffer(query);
11014 destroyPQExpBuffer(q);
11015 destroyPQExpBuffer(delq);
11016 destroyPQExpBuffer(labelq);
11023 /* Get additional fields from the pg_opfamily row */
11024 resetPQExpBuffer(query);
11026 appendPQExpBuffer(query, "SELECT "
11027 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
11028 "FROM pg_catalog.pg_opfamily "
11029 "WHERE oid = '%u'::pg_catalog.oid",
11030 opfinfo->dobj.catId.oid);
11032 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11034 i_amname = PQfnumber(res, "amname");
11036 /* amname will still be needed after we PQclear res */
11037 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
11040 * DROP must be fully qualified in case same name appears in pg_catalog
11042 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
11043 fmtId(opfinfo->dobj.namespace->dobj.name));
11044 appendPQExpBuffer(delq, ".%s",
11045 fmtId(opfinfo->dobj.name));
11046 appendPQExpBuffer(delq, " USING %s;\n",
11049 /* Build the fixed portion of the CREATE command */
11050 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
11051 fmtId(opfinfo->dobj.name));
11052 appendPQExpBuffer(q, " USING %s;\n",
11057 /* Do we need an ALTER to add loose members? */
11058 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
11060 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
11061 fmtId(opfinfo->dobj.name));
11062 appendPQExpBuffer(q, " USING %s ADD\n ",
11068 * Now fetch and print the OPERATOR entries (pg_amop rows).
11070 ntups = PQntuples(res_ops);
11072 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
11073 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
11074 i_amopopr = PQfnumber(res_ops, "amopopr");
11075 i_sortfamily = PQfnumber(res_ops, "sortfamily");
11076 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
11078 for (i = 0; i < ntups; i++)
11080 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
11081 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
11082 amopopr = PQgetvalue(res_ops, i, i_amopopr);
11083 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
11084 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
11087 appendPQExpBuffer(q, " ,\n ");
11089 appendPQExpBuffer(q, "OPERATOR %s %s",
11090 amopstrategy, amopopr);
11092 if (strlen(sortfamily) > 0)
11094 appendPQExpBuffer(q, " FOR ORDER BY ");
11095 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
11096 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
11097 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
11100 if (strcmp(amopreqcheck, "t") == 0)
11101 appendPQExpBuffer(q, " RECHECK");
11107 * Now fetch and print the FUNCTION entries (pg_amproc rows).
11109 ntups = PQntuples(res_procs);
11111 i_amprocnum = PQfnumber(res_procs, "amprocnum");
11112 i_amproc = PQfnumber(res_procs, "amproc");
11113 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
11114 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
11116 for (i = 0; i < ntups; i++)
11118 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
11119 amproc = PQgetvalue(res_procs, i, i_amproc);
11120 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
11121 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
11124 appendPQExpBuffer(q, " ,\n ");
11126 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
11127 amprocnum, amproclefttype, amprocrighttype,
11133 appendPQExpBuffer(q, ";\n");
11136 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
11137 fmtId(opfinfo->dobj.name));
11138 appendPQExpBuffer(labelq, " USING %s",
11141 if (binary_upgrade)
11142 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
11144 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
11145 opfinfo->dobj.name,
11146 opfinfo->dobj.namespace->dobj.name,
11149 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
11150 q->data, delq->data, NULL,
11154 /* Dump Operator Family Comments */
11155 dumpComment(fout, labelq->data,
11156 NULL, opfinfo->rolname,
11157 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
11161 PQclear(res_procs);
11162 destroyPQExpBuffer(query);
11163 destroyPQExpBuffer(q);
11164 destroyPQExpBuffer(delq);
11165 destroyPQExpBuffer(labelq);
11170 * write out a single collation definition
11173 dumpCollation(Archive *fout, CollInfo *collinfo)
11178 PQExpBuffer labelq;
11182 const char *collcollate;
11183 const char *collctype;
11185 /* Skip if not to be dumped */
11186 if (!collinfo->dobj.dump || dataOnly)
11189 query = createPQExpBuffer();
11190 q = createPQExpBuffer();
11191 delq = createPQExpBuffer();
11192 labelq = createPQExpBuffer();
11194 /* Make sure we are in proper schema */
11195 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
11197 /* Get conversion-specific details */
11198 appendPQExpBuffer(query, "SELECT "
11201 "FROM pg_catalog.pg_collation c "
11202 "WHERE c.oid = '%u'::pg_catalog.oid",
11203 collinfo->dobj.catId.oid);
11205 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11207 i_collcollate = PQfnumber(res, "collcollate");
11208 i_collctype = PQfnumber(res, "collctype");
11210 collcollate = PQgetvalue(res, 0, i_collcollate);
11211 collctype = PQgetvalue(res, 0, i_collctype);
11214 * DROP must be fully qualified in case same name appears in pg_catalog
11216 appendPQExpBuffer(delq, "DROP COLLATION %s",
11217 fmtId(collinfo->dobj.namespace->dobj.name));
11218 appendPQExpBuffer(delq, ".%s;\n",
11219 fmtId(collinfo->dobj.name));
11221 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
11222 fmtId(collinfo->dobj.name));
11223 appendStringLiteralAH(q, collcollate, fout);
11224 appendPQExpBuffer(q, ", lc_ctype = ");
11225 appendStringLiteralAH(q, collctype, fout);
11226 appendPQExpBuffer(q, ");\n");
11228 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
11230 if (binary_upgrade)
11231 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
11233 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
11234 collinfo->dobj.name,
11235 collinfo->dobj.namespace->dobj.name,
11238 false, "COLLATION", SECTION_PRE_DATA,
11239 q->data, delq->data, NULL,
11243 /* Dump Collation Comments */
11244 dumpComment(fout, labelq->data,
11245 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
11246 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
11250 destroyPQExpBuffer(query);
11251 destroyPQExpBuffer(q);
11252 destroyPQExpBuffer(delq);
11253 destroyPQExpBuffer(labelq);
11258 * write out a single conversion definition
11261 dumpConversion(Archive *fout, ConvInfo *convinfo)
11266 PQExpBuffer labelq;
11268 int i_conforencoding;
11269 int i_contoencoding;
11272 const char *conforencoding;
11273 const char *contoencoding;
11274 const char *conproc;
11277 /* Skip if not to be dumped */
11278 if (!convinfo->dobj.dump || dataOnly)
11281 query = createPQExpBuffer();
11282 q = createPQExpBuffer();
11283 delq = createPQExpBuffer();
11284 labelq = createPQExpBuffer();
11286 /* Make sure we are in proper schema */
11287 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
11289 /* Get conversion-specific details */
11290 appendPQExpBuffer(query, "SELECT "
11291 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
11292 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
11293 "conproc, condefault "
11294 "FROM pg_catalog.pg_conversion c "
11295 "WHERE c.oid = '%u'::pg_catalog.oid",
11296 convinfo->dobj.catId.oid);
11298 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11300 i_conforencoding = PQfnumber(res, "conforencoding");
11301 i_contoencoding = PQfnumber(res, "contoencoding");
11302 i_conproc = PQfnumber(res, "conproc");
11303 i_condefault = PQfnumber(res, "condefault");
11305 conforencoding = PQgetvalue(res, 0, i_conforencoding);
11306 contoencoding = PQgetvalue(res, 0, i_contoencoding);
11307 conproc = PQgetvalue(res, 0, i_conproc);
11308 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
11311 * DROP must be fully qualified in case same name appears in pg_catalog
11313 appendPQExpBuffer(delq, "DROP CONVERSION %s",
11314 fmtId(convinfo->dobj.namespace->dobj.name));
11315 appendPQExpBuffer(delq, ".%s;\n",
11316 fmtId(convinfo->dobj.name));
11318 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
11319 (condefault) ? "DEFAULT " : "",
11320 fmtId(convinfo->dobj.name));
11321 appendStringLiteralAH(q, conforencoding, fout);
11322 appendPQExpBuffer(q, " TO ");
11323 appendStringLiteralAH(q, contoencoding, fout);
11324 /* regproc is automatically quoted in 7.3 and above */
11325 appendPQExpBuffer(q, " FROM %s;\n", conproc);
11327 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
11329 if (binary_upgrade)
11330 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
11332 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
11333 convinfo->dobj.name,
11334 convinfo->dobj.namespace->dobj.name,
11337 false, "CONVERSION", SECTION_PRE_DATA,
11338 q->data, delq->data, NULL,
11342 /* Dump Conversion Comments */
11343 dumpComment(fout, labelq->data,
11344 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
11345 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
11349 destroyPQExpBuffer(query);
11350 destroyPQExpBuffer(q);
11351 destroyPQExpBuffer(delq);
11352 destroyPQExpBuffer(labelq);
11356 * format_aggregate_signature: generate aggregate name and argument list
11358 * The argument type names are qualified if needed. The aggregate name
11359 * is never qualified.
11362 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11364 PQExpBufferData buf;
11367 initPQExpBuffer(&buf);
11369 appendPQExpBuffer(&buf, "%s",
11370 fmtId(agginfo->aggfn.dobj.name));
11372 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11374 if (agginfo->aggfn.nargs == 0)
11375 appendPQExpBuffer(&buf, "(*)");
11378 appendPQExpBuffer(&buf, "(");
11379 for (j = 0; j < agginfo->aggfn.nargs; j++)
11383 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11386 appendPQExpBuffer(&buf, "%s%s",
11387 (j > 0) ? ", " : "",
11391 appendPQExpBuffer(&buf, ")");
11398 * write out a single aggregate definition
11401 dumpAgg(Archive *fout, AggInfo *agginfo)
11406 PQExpBuffer labelq;
11407 PQExpBuffer details;
11414 int i_aggtranstype;
11417 const char *aggtransfn;
11418 const char *aggfinalfn;
11419 const char *aggsortop;
11420 const char *aggtranstype;
11421 const char *agginitval;
11424 /* Skip if not to be dumped */
11425 if (!agginfo->aggfn.dobj.dump || dataOnly)
11428 query = createPQExpBuffer();
11429 q = createPQExpBuffer();
11430 delq = createPQExpBuffer();
11431 labelq = createPQExpBuffer();
11432 details = createPQExpBuffer();
11434 /* Make sure we are in proper schema */
11435 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11437 /* Get aggregate-specific details */
11438 if (fout->remoteVersion >= 80100)
11440 appendPQExpBuffer(query, "SELECT aggtransfn, "
11441 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11442 "aggsortop::pg_catalog.regoperator, "
11444 "'t'::boolean AS convertok "
11445 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11446 "WHERE a.aggfnoid = p.oid "
11447 "AND p.oid = '%u'::pg_catalog.oid",
11448 agginfo->aggfn.dobj.catId.oid);
11450 else if (fout->remoteVersion >= 70300)
11452 appendPQExpBuffer(query, "SELECT aggtransfn, "
11453 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11456 "'t'::boolean AS convertok "
11457 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11458 "WHERE a.aggfnoid = p.oid "
11459 "AND p.oid = '%u'::pg_catalog.oid",
11460 agginfo->aggfn.dobj.catId.oid);
11462 else if (fout->remoteVersion >= 70100)
11464 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11465 "format_type(aggtranstype, NULL) AS aggtranstype, "
11468 "'t'::boolean AS convertok "
11469 "FROM pg_aggregate "
11470 "WHERE oid = '%u'::oid",
11471 agginfo->aggfn.dobj.catId.oid);
11475 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11477 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11479 "agginitval1 AS agginitval, "
11480 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11481 "FROM pg_aggregate "
11482 "WHERE oid = '%u'::oid",
11483 agginfo->aggfn.dobj.catId.oid);
11486 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11488 i_aggtransfn = PQfnumber(res, "aggtransfn");
11489 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11490 i_aggsortop = PQfnumber(res, "aggsortop");
11491 i_aggtranstype = PQfnumber(res, "aggtranstype");
11492 i_agginitval = PQfnumber(res, "agginitval");
11493 i_convertok = PQfnumber(res, "convertok");
11495 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11496 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11497 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11498 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11499 agginitval = PQgetvalue(res, 0, i_agginitval);
11500 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11502 aggsig = format_aggregate_signature(agginfo, fout, true);
11503 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11507 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11512 if (fout->remoteVersion >= 70300)
11514 /* If using 7.3's regproc or regtype, data is already quoted */
11515 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11519 else if (fout->remoteVersion >= 70100)
11521 /* format_type quotes, regproc does not */
11522 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11528 /* need quotes all around */
11529 appendPQExpBuffer(details, " SFUNC = %s,\n",
11530 fmtId(aggtransfn));
11531 appendPQExpBuffer(details, " STYPE = %s",
11532 fmtId(aggtranstype));
11535 if (!PQgetisnull(res, 0, i_agginitval))
11537 appendPQExpBuffer(details, ",\n INITCOND = ");
11538 appendStringLiteralAH(details, agginitval, fout);
11541 if (strcmp(aggfinalfn, "-") != 0)
11543 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11547 aggsortop = convertOperatorReference(fout, aggsortop);
11550 appendPQExpBuffer(details, ",\n SORTOP = %s",
11555 * DROP must be fully qualified in case same name appears in pg_catalog
11557 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11558 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11561 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11562 aggsig, details->data);
11564 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11566 if (binary_upgrade)
11567 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11569 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11571 agginfo->aggfn.dobj.namespace->dobj.name,
11573 agginfo->aggfn.rolname,
11574 false, "AGGREGATE", SECTION_PRE_DATA,
11575 q->data, delq->data, NULL,
11579 /* Dump Aggregate Comments */
11580 dumpComment(fout, labelq->data,
11581 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11582 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11583 dumpSecLabel(fout, labelq->data,
11584 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11585 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11588 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11589 * command look like a function's GRANT; in particular this affects the
11590 * syntax for zero-argument aggregates.
11595 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11596 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11598 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11600 aggsig, NULL, aggsig_tag,
11601 agginfo->aggfn.dobj.namespace->dobj.name,
11602 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11609 destroyPQExpBuffer(query);
11610 destroyPQExpBuffer(q);
11611 destroyPQExpBuffer(delq);
11612 destroyPQExpBuffer(labelq);
11613 destroyPQExpBuffer(details);
11618 * write out a single text search parser
11621 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11625 PQExpBuffer labelq;
11627 /* Skip if not to be dumped */
11628 if (!prsinfo->dobj.dump || dataOnly)
11631 q = createPQExpBuffer();
11632 delq = createPQExpBuffer();
11633 labelq = createPQExpBuffer();
11635 /* Make sure we are in proper schema */
11636 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11638 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11639 fmtId(prsinfo->dobj.name));
11641 appendPQExpBuffer(q, " START = %s,\n",
11642 convertTSFunction(fout, prsinfo->prsstart));
11643 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11644 convertTSFunction(fout, prsinfo->prstoken));
11645 appendPQExpBuffer(q, " END = %s,\n",
11646 convertTSFunction(fout, prsinfo->prsend));
11647 if (prsinfo->prsheadline != InvalidOid)
11648 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11649 convertTSFunction(fout, prsinfo->prsheadline));
11650 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11651 convertTSFunction(fout, prsinfo->prslextype));
11654 * DROP must be fully qualified in case same name appears in pg_catalog
11656 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11657 fmtId(prsinfo->dobj.namespace->dobj.name));
11658 appendPQExpBuffer(delq, ".%s;\n",
11659 fmtId(prsinfo->dobj.name));
11661 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11662 fmtId(prsinfo->dobj.name));
11664 if (binary_upgrade)
11665 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11667 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11668 prsinfo->dobj.name,
11669 prsinfo->dobj.namespace->dobj.name,
11672 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11673 q->data, delq->data, NULL,
11677 /* Dump Parser Comments */
11678 dumpComment(fout, labelq->data,
11680 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11682 destroyPQExpBuffer(q);
11683 destroyPQExpBuffer(delq);
11684 destroyPQExpBuffer(labelq);
11689 * write out a single text search dictionary
11692 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11696 PQExpBuffer labelq;
11702 /* Skip if not to be dumped */
11703 if (!dictinfo->dobj.dump || dataOnly)
11706 q = createPQExpBuffer();
11707 delq = createPQExpBuffer();
11708 labelq = createPQExpBuffer();
11709 query = createPQExpBuffer();
11711 /* Fetch name and namespace of the dictionary's template */
11712 selectSourceSchema(fout, "pg_catalog");
11713 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11714 "FROM pg_ts_template p, pg_namespace n "
11715 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11716 dictinfo->dicttemplate);
11717 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11718 nspname = PQgetvalue(res, 0, 0);
11719 tmplname = PQgetvalue(res, 0, 1);
11721 /* Make sure we are in proper schema */
11722 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11724 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11725 fmtId(dictinfo->dobj.name));
11727 appendPQExpBuffer(q, " TEMPLATE = ");
11728 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11729 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11730 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11734 /* the dictinitoption can be dumped straight into the command */
11735 if (dictinfo->dictinitoption)
11736 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11738 appendPQExpBuffer(q, " );\n");
11741 * DROP must be fully qualified in case same name appears in pg_catalog
11743 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11744 fmtId(dictinfo->dobj.namespace->dobj.name));
11745 appendPQExpBuffer(delq, ".%s;\n",
11746 fmtId(dictinfo->dobj.name));
11748 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11749 fmtId(dictinfo->dobj.name));
11751 if (binary_upgrade)
11752 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11754 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11755 dictinfo->dobj.name,
11756 dictinfo->dobj.namespace->dobj.name,
11759 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11760 q->data, delq->data, NULL,
11764 /* Dump Dictionary Comments */
11765 dumpComment(fout, labelq->data,
11766 NULL, dictinfo->rolname,
11767 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11769 destroyPQExpBuffer(q);
11770 destroyPQExpBuffer(delq);
11771 destroyPQExpBuffer(labelq);
11772 destroyPQExpBuffer(query);
11777 * write out a single text search template
11780 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11784 PQExpBuffer labelq;
11786 /* Skip if not to be dumped */
11787 if (!tmplinfo->dobj.dump || dataOnly)
11790 q = createPQExpBuffer();
11791 delq = createPQExpBuffer();
11792 labelq = createPQExpBuffer();
11794 /* Make sure we are in proper schema */
11795 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11797 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11798 fmtId(tmplinfo->dobj.name));
11800 if (tmplinfo->tmplinit != InvalidOid)
11801 appendPQExpBuffer(q, " INIT = %s,\n",
11802 convertTSFunction(fout, tmplinfo->tmplinit));
11803 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11804 convertTSFunction(fout, tmplinfo->tmpllexize));
11807 * DROP must be fully qualified in case same name appears in pg_catalog
11809 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11810 fmtId(tmplinfo->dobj.namespace->dobj.name));
11811 appendPQExpBuffer(delq, ".%s;\n",
11812 fmtId(tmplinfo->dobj.name));
11814 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11815 fmtId(tmplinfo->dobj.name));
11817 if (binary_upgrade)
11818 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11820 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11821 tmplinfo->dobj.name,
11822 tmplinfo->dobj.namespace->dobj.name,
11825 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11826 q->data, delq->data, NULL,
11830 /* Dump Template Comments */
11831 dumpComment(fout, labelq->data,
11833 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11835 destroyPQExpBuffer(q);
11836 destroyPQExpBuffer(delq);
11837 destroyPQExpBuffer(labelq);
11842 * write out a single text search configuration
11845 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11849 PQExpBuffer labelq;
11859 /* Skip if not to be dumped */
11860 if (!cfginfo->dobj.dump || dataOnly)
11863 q = createPQExpBuffer();
11864 delq = createPQExpBuffer();
11865 labelq = createPQExpBuffer();
11866 query = createPQExpBuffer();
11868 /* Fetch name and namespace of the config's parser */
11869 selectSourceSchema(fout, "pg_catalog");
11870 appendPQExpBuffer(query, "SELECT nspname, prsname "
11871 "FROM pg_ts_parser p, pg_namespace n "
11872 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11873 cfginfo->cfgparser);
11874 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11875 nspname = PQgetvalue(res, 0, 0);
11876 prsname = PQgetvalue(res, 0, 1);
11878 /* Make sure we are in proper schema */
11879 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11881 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11882 fmtId(cfginfo->dobj.name));
11884 appendPQExpBuffer(q, " PARSER = ");
11885 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11886 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11887 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11891 resetPQExpBuffer(query);
11892 appendPQExpBuffer(query,
11894 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11895 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11896 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11897 "FROM pg_catalog.pg_ts_config_map AS m \n"
11898 "WHERE m.mapcfg = '%u' \n"
11899 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11900 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11902 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11903 ntups = PQntuples(res);
11905 i_tokenname = PQfnumber(res, "tokenname");
11906 i_dictname = PQfnumber(res, "dictname");
11908 for (i = 0; i < ntups; i++)
11910 char *tokenname = PQgetvalue(res, i, i_tokenname);
11911 char *dictname = PQgetvalue(res, i, i_dictname);
11914 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11916 /* starting a new token type, so start a new command */
11918 appendPQExpBuffer(q, ";\n");
11919 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11920 fmtId(cfginfo->dobj.name));
11921 /* tokenname needs quoting, dictname does NOT */
11922 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11923 fmtId(tokenname), dictname);
11926 appendPQExpBuffer(q, ", %s", dictname);
11930 appendPQExpBuffer(q, ";\n");
11935 * DROP must be fully qualified in case same name appears in pg_catalog
11937 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11938 fmtId(cfginfo->dobj.namespace->dobj.name));
11939 appendPQExpBuffer(delq, ".%s;\n",
11940 fmtId(cfginfo->dobj.name));
11942 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11943 fmtId(cfginfo->dobj.name));
11945 if (binary_upgrade)
11946 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11948 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11949 cfginfo->dobj.name,
11950 cfginfo->dobj.namespace->dobj.name,
11953 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11954 q->data, delq->data, NULL,
11958 /* Dump Configuration Comments */
11959 dumpComment(fout, labelq->data,
11960 NULL, cfginfo->rolname,
11961 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11963 destroyPQExpBuffer(q);
11964 destroyPQExpBuffer(delq);
11965 destroyPQExpBuffer(labelq);
11966 destroyPQExpBuffer(query);
11970 * dumpForeignDataWrapper
11971 * write out a single foreign-data wrapper definition
11974 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11978 PQExpBuffer labelq;
11981 /* Skip if not to be dumped */
11982 if (!fdwinfo->dobj.dump || dataOnly)
11986 * FDWs that belong to an extension are dumped based on their "dump"
11987 * field. Otherwise omit them if we are only dumping some specific object.
11989 if (!fdwinfo->dobj.ext_member)
11990 if (!include_everything)
11993 q = createPQExpBuffer();
11994 delq = createPQExpBuffer();
11995 labelq = createPQExpBuffer();
11997 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11999 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
12002 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
12003 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
12005 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
12006 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
12008 if (strlen(fdwinfo->fdwoptions) > 0)
12009 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
12011 appendPQExpBuffer(q, ";\n");
12013 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
12016 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
12019 if (binary_upgrade)
12020 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
12022 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12023 fdwinfo->dobj.name,
12027 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
12028 q->data, delq->data, NULL,
12032 /* Handle the ACL */
12033 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12034 "FOREIGN DATA WRAPPER",
12035 qfdwname, NULL, fdwinfo->dobj.name,
12036 NULL, fdwinfo->rolname,
12039 /* Dump Foreign Data Wrapper Comments */
12040 dumpComment(fout, labelq->data,
12041 NULL, fdwinfo->rolname,
12042 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
12046 destroyPQExpBuffer(q);
12047 destroyPQExpBuffer(delq);
12048 destroyPQExpBuffer(labelq);
12052 * dumpForeignServer
12053 * write out a foreign server definition
12056 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
12060 PQExpBuffer labelq;
12066 /* Skip if not to be dumped */
12067 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
12070 q = createPQExpBuffer();
12071 delq = createPQExpBuffer();
12072 labelq = createPQExpBuffer();
12073 query = createPQExpBuffer();
12075 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
12077 /* look up the foreign-data wrapper */
12078 selectSourceSchema(fout, "pg_catalog");
12079 appendPQExpBuffer(query, "SELECT fdwname "
12080 "FROM pg_foreign_data_wrapper w "
12081 "WHERE w.oid = '%u'",
12083 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12084 fdwname = PQgetvalue(res, 0, 0);
12086 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
12087 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
12089 appendPQExpBuffer(q, " TYPE ");
12090 appendStringLiteralAH(q, srvinfo->srvtype, fout);
12092 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
12094 appendPQExpBuffer(q, " VERSION ");
12095 appendStringLiteralAH(q, srvinfo->srvversion, fout);
12098 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
12099 appendPQExpBuffer(q, "%s", fmtId(fdwname));
12101 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
12102 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
12104 appendPQExpBuffer(q, ";\n");
12106 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
12109 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
12111 if (binary_upgrade)
12112 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
12114 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12115 srvinfo->dobj.name,
12119 false, "SERVER", SECTION_PRE_DATA,
12120 q->data, delq->data, NULL,
12124 /* Handle the ACL */
12125 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12127 qsrvname, NULL, srvinfo->dobj.name,
12128 NULL, srvinfo->rolname,
12131 /* Dump user mappings */
12132 dumpUserMappings(fout,
12133 srvinfo->dobj.name, NULL,
12135 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
12137 /* Dump Foreign Server Comments */
12138 dumpComment(fout, labelq->data,
12139 NULL, srvinfo->rolname,
12140 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
12144 destroyPQExpBuffer(q);
12145 destroyPQExpBuffer(delq);
12146 destroyPQExpBuffer(labelq);
12152 * This routine is used to dump any user mappings associated with the
12153 * server handed to this routine. Should be called after ArchiveEntry()
12157 dumpUserMappings(Archive *fout,
12158 const char *servername, const char *namespace,
12160 CatalogId catalogId, DumpId dumpId)
12172 q = createPQExpBuffer();
12173 tag = createPQExpBuffer();
12174 delq = createPQExpBuffer();
12175 query = createPQExpBuffer();
12178 * We read from the publicly accessible view pg_user_mappings, so as not
12179 * to fail if run by a non-superuser. Note that the view will show
12180 * umoptions as null if the user hasn't got privileges for the associated
12181 * server; this means that pg_dump will dump such a mapping, but with no
12182 * OPTIONS clause. A possible alternative is to skip such mappings
12183 * altogether, but it's not clear that that's an improvement.
12185 selectSourceSchema(fout, "pg_catalog");
12187 appendPQExpBuffer(query,
12189 "array_to_string(ARRAY("
12190 "SELECT quote_ident(option_name) || ' ' || "
12191 "quote_literal(option_value) "
12192 "FROM pg_options_to_table(umoptions) "
12193 "ORDER BY option_name"
12194 "), E',\n ') AS umoptions "
12195 "FROM pg_user_mappings "
12196 "WHERE srvid = '%u' "
12197 "ORDER BY usename",
12200 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12202 ntups = PQntuples(res);
12203 i_usename = PQfnumber(res, "usename");
12204 i_umoptions = PQfnumber(res, "umoptions");
12206 for (i = 0; i < ntups; i++)
12211 usename = PQgetvalue(res, i, i_usename);
12212 umoptions = PQgetvalue(res, i, i_umoptions);
12214 resetPQExpBuffer(q);
12215 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
12216 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
12218 if (umoptions && strlen(umoptions) > 0)
12219 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
12221 appendPQExpBuffer(q, ";\n");
12223 resetPQExpBuffer(delq);
12224 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
12225 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
12227 resetPQExpBuffer(tag);
12228 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
12229 usename, servername);
12231 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12236 "USER MAPPING", SECTION_PRE_DATA,
12237 q->data, delq->data, NULL,
12244 destroyPQExpBuffer(query);
12245 destroyPQExpBuffer(delq);
12246 destroyPQExpBuffer(q);
12250 * Write out default privileges information
12253 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
12259 /* Skip if not to be dumped */
12260 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
12263 q = createPQExpBuffer();
12264 tag = createPQExpBuffer();
12266 switch (daclinfo->defaclobjtype)
12268 case DEFACLOBJ_RELATION:
12271 case DEFACLOBJ_SEQUENCE:
12272 type = "SEQUENCES";
12274 case DEFACLOBJ_FUNCTION:
12275 type = "FUNCTIONS";
12277 case DEFACLOBJ_TYPE:
12281 /* shouldn't get here */
12282 exit_horribly(NULL,
12283 "unrecognized object type in default privileges: %d\n",
12284 (int) daclinfo->defaclobjtype);
12285 type = ""; /* keep compiler quiet */
12288 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
12290 /* build the actual command(s) for this tuple */
12291 if (!buildDefaultACLCommands(type,
12292 daclinfo->dobj.namespace != NULL ?
12293 daclinfo->dobj.namespace->dobj.name : NULL,
12294 daclinfo->defaclacl,
12295 daclinfo->defaclrole,
12296 fout->remoteVersion,
12298 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
12299 daclinfo->defaclacl);
12301 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
12303 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
12305 daclinfo->defaclrole,
12306 false, "DEFAULT ACL", SECTION_POST_DATA,
12311 destroyPQExpBuffer(tag);
12312 destroyPQExpBuffer(q);
12316 * Write out grant/revoke information
12318 * 'objCatId' is the catalog ID of the underlying object.
12319 * 'objDumpId' is the dump ID of the underlying object.
12320 * 'type' must be one of
12321 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
12322 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
12323 * 'name' is the formatted name of the object. Must be quoted etc. already.
12324 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
12325 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12326 * 'nspname' is the namespace the object is in (NULL if none).
12327 * 'owner' is the owner, NULL if there is no owner (for languages).
12328 * 'acls' is the string read out of the fooacl system catalog field;
12329 * it will be parsed here.
12333 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12334 const char *type, const char *name, const char *subname,
12335 const char *tag, const char *nspname, const char *owner,
12340 /* Do nothing if ACL dump is not enabled */
12344 /* --data-only skips ACLs *except* BLOB ACLs */
12345 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12348 sql = createPQExpBuffer();
12350 if (!buildACLCommands(name, subname, type, acls, owner,
12351 "", fout->remoteVersion, sql))
12352 exit_horribly(NULL,
12353 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12357 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12360 owner ? owner : "",
12361 false, "ACL", SECTION_NONE,
12362 sql->data, "", NULL,
12366 destroyPQExpBuffer(sql);
12372 * This routine is used to dump any security labels associated with the
12373 * object handed to this routine. The routine takes a constant character
12374 * string for the target part of the security-label command, plus
12375 * the namespace and owner of the object (for labeling the ArchiveEntry),
12376 * plus catalog ID and subid which are the lookup key for pg_seclabel,
12377 * plus the dump ID for the object (for setting a dependency).
12378 * If a matching pg_seclabel entry is found, it is dumped.
12380 * Note: although this routine takes a dumpId for dependency purposes,
12381 * that purpose is just to mark the dependency in the emitted dump file
12382 * for possible future use by pg_restore. We do NOT use it for determining
12383 * ordering of the label in the dump file, because this routine is called
12384 * after dependency sorting occurs. This routine should be called just after
12385 * calling ArchiveEntry() for the specified object.
12388 dumpSecLabel(Archive *fout, const char *target,
12389 const char *namespace, const char *owner,
12390 CatalogId catalogId, int subid, DumpId dumpId)
12392 SecLabelItem *labels;
12397 /* do nothing, if --no-security-labels is supplied */
12398 if (no_security_labels)
12401 /* Comments are schema not data ... except blob comments are data */
12402 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12413 /* Search for security labels associated with catalogId, using table */
12414 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12416 query = createPQExpBuffer();
12418 for (i = 0; i < nlabels; i++)
12421 * Ignore label entries for which the subid doesn't match.
12423 if (labels[i].objsubid != subid)
12426 appendPQExpBuffer(query,
12427 "SECURITY LABEL FOR %s ON %s IS ",
12428 fmtId(labels[i].provider), target);
12429 appendStringLiteralAH(query, labels[i].label, fout);
12430 appendPQExpBuffer(query, ";\n");
12433 if (query->len > 0)
12435 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12436 target, namespace, NULL, owner,
12437 false, "SECURITY LABEL", SECTION_NONE,
12438 query->data, "", NULL,
12442 destroyPQExpBuffer(query);
12446 * dumpTableSecLabel
12448 * As above, but dump security label for both the specified table (or view)
12452 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12454 SecLabelItem *labels;
12458 PQExpBuffer target;
12460 /* do nothing, if --no-security-labels is supplied */
12461 if (no_security_labels)
12464 /* SecLabel are SCHEMA not data */
12468 /* Search for comments associated with relation, using table */
12469 nlabels = findSecLabels(fout,
12470 tbinfo->dobj.catId.tableoid,
12471 tbinfo->dobj.catId.oid,
12474 /* If security labels exist, build SECURITY LABEL statements */
12478 query = createPQExpBuffer();
12479 target = createPQExpBuffer();
12481 for (i = 0; i < nlabels; i++)
12483 const char *colname;
12484 const char *provider = labels[i].provider;
12485 const char *label = labels[i].label;
12486 int objsubid = labels[i].objsubid;
12488 resetPQExpBuffer(target);
12491 appendPQExpBuffer(target, "%s %s", reltypename,
12492 fmtId(tbinfo->dobj.name));
12496 colname = getAttrName(objsubid, tbinfo);
12497 /* first fmtId result must be consumed before calling it again */
12498 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12499 appendPQExpBuffer(target, ".%s", fmtId(colname));
12501 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12502 fmtId(provider), target->data);
12503 appendStringLiteralAH(query, label, fout);
12504 appendPQExpBuffer(query, ";\n");
12506 if (query->len > 0)
12508 resetPQExpBuffer(target);
12509 appendPQExpBuffer(target, "%s %s", reltypename,
12510 fmtId(tbinfo->dobj.name));
12511 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12513 tbinfo->dobj.namespace->dobj.name,
12514 NULL, tbinfo->rolname,
12515 false, "SECURITY LABEL", SECTION_NONE,
12516 query->data, "", NULL,
12517 &(tbinfo->dobj.dumpId), 1,
12520 destroyPQExpBuffer(query);
12521 destroyPQExpBuffer(target);
12527 * Find the security label(s), if any, associated with the given object.
12528 * All the objsubid values associated with the given classoid/objoid are
12529 * found with one search.
12532 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12534 /* static storage for table of security labels */
12535 static SecLabelItem *labels = NULL;
12536 static int nlabels = -1;
12538 SecLabelItem *middle = NULL;
12540 SecLabelItem *high;
12543 /* Get security labels if we didn't already */
12545 nlabels = collectSecLabels(fout, &labels);
12547 if (nlabels <= 0) /* no labels, so no match is possible */
12554 * Do binary search to find some item matching the object.
12557 high = &labels[nlabels - 1];
12558 while (low <= high)
12560 middle = low + (high - low) / 2;
12562 if (classoid < middle->classoid)
12564 else if (classoid > middle->classoid)
12566 else if (objoid < middle->objoid)
12568 else if (objoid > middle->objoid)
12571 break; /* found a match */
12574 if (low > high) /* no matches */
12581 * Now determine how many items match the object. The search loop
12582 * invariant still holds: only items between low and high inclusive could
12586 while (middle > low)
12588 if (classoid != middle[-1].classoid ||
12589 objoid != middle[-1].objoid)
12598 while (middle <= high)
12600 if (classoid != middle->classoid ||
12601 objoid != middle->objoid)
12613 * Construct a table of all security labels available for database objects.
12614 * It's much faster to pull them all at once.
12616 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12619 collectSecLabels(Archive *fout, SecLabelItem **items)
12630 SecLabelItem *labels;
12632 query = createPQExpBuffer();
12634 appendPQExpBuffer(query,
12635 "SELECT label, provider, classoid, objoid, objsubid "
12636 "FROM pg_catalog.pg_seclabel "
12637 "ORDER BY classoid, objoid, objsubid");
12639 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12641 /* Construct lookup table containing OIDs in numeric form */
12642 i_label = PQfnumber(res, "label");
12643 i_provider = PQfnumber(res, "provider");
12644 i_classoid = PQfnumber(res, "classoid");
12645 i_objoid = PQfnumber(res, "objoid");
12646 i_objsubid = PQfnumber(res, "objsubid");
12648 ntups = PQntuples(res);
12650 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12652 for (i = 0; i < ntups; i++)
12654 labels[i].label = PQgetvalue(res, i, i_label);
12655 labels[i].provider = PQgetvalue(res, i, i_provider);
12656 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12657 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12658 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12661 /* Do NOT free the PGresult since we are keeping pointers into it */
12662 destroyPQExpBuffer(query);
12670 * write out to fout the declarations (not data) of a user-defined table
12673 dumpTable(Archive *fout, TableInfo *tbinfo)
12675 if (tbinfo->dobj.dump && !dataOnly)
12679 if (tbinfo->relkind == RELKIND_SEQUENCE)
12680 dumpSequence(fout, tbinfo);
12682 dumpTableSchema(fout, tbinfo);
12684 /* Handle the ACL here */
12685 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12686 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12687 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12689 namecopy, NULL, tbinfo->dobj.name,
12690 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12694 * Handle column ACLs, if any. Note: we pull these with a separate
12695 * query rather than trying to fetch them during getTableAttrs, so
12696 * that we won't miss ACLs on system columns.
12698 if (fout->remoteVersion >= 80400)
12700 PQExpBuffer query = createPQExpBuffer();
12704 appendPQExpBuffer(query,
12705 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12706 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12708 tbinfo->dobj.catId.oid);
12709 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12711 for (i = 0; i < PQntuples(res); i++)
12713 char *attname = PQgetvalue(res, i, 0);
12714 char *attacl = PQgetvalue(res, i, 1);
12718 attnamecopy = pg_strdup(fmtId(attname));
12719 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12720 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12721 /* Column's GRANT type is always TABLE */
12722 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12723 namecopy, attnamecopy, acltag,
12724 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12730 destroyPQExpBuffer(query);
12738 * Create the AS clause for a view or materialized view. The semicolon is
12739 * stripped because a materialized view must add a WITH NO DATA clause.
12741 * This returns a new buffer which must be freed by the caller.
12744 createViewAsClause(Archive *fout, TableInfo *tbinfo)
12746 PQExpBuffer query = createPQExpBuffer();
12747 PQExpBuffer result = createPQExpBuffer();
12751 /* Fetch the view definition */
12752 if (fout->remoteVersion >= 70300)
12754 /* Beginning in 7.3, viewname is not unique; rely on OID */
12755 appendPQExpBuffer(query,
12756 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12757 tbinfo->dobj.catId.oid);
12761 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12762 "FROM pg_views WHERE viewname = ");
12763 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12764 appendPQExpBuffer(query, ";");
12767 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12769 if (PQntuples(res) != 1)
12771 if (PQntuples(res) < 1)
12772 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12773 tbinfo->dobj.name);
12775 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12776 tbinfo->dobj.name);
12779 len = PQgetlength(res, 0, 0);
12782 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12783 tbinfo->dobj.name);
12785 /* Strip off the trailing semicolon so that other things may follow. */
12786 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
12787 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
12790 destroyPQExpBuffer(query);
12797 * write the declaration (not data) of one user-defined table or view
12800 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12802 PQExpBuffer q = createPQExpBuffer();
12803 PQExpBuffer delq = createPQExpBuffer();
12804 PQExpBuffer labelq = createPQExpBuffer();
12806 TableInfo **parents;
12807 int actual_atts; /* number of attrs in this CREATE statement */
12808 const char *reltypename;
12815 /* Make sure we are in proper schema */
12816 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12818 if (binary_upgrade)
12819 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12820 tbinfo->dobj.catId.oid);
12822 /* Is it a table or a view? */
12823 if (tbinfo->relkind == RELKIND_VIEW)
12825 PQExpBuffer result;
12827 reltypename = "VIEW";
12830 * DROP must be fully qualified in case same name appears in
12833 appendPQExpBuffer(delq, "DROP VIEW %s.",
12834 fmtId(tbinfo->dobj.namespace->dobj.name));
12835 appendPQExpBuffer(delq, "%s;\n",
12836 fmtId(tbinfo->dobj.name));
12838 if (binary_upgrade)
12839 binary_upgrade_set_pg_class_oids(fout, q,
12840 tbinfo->dobj.catId.oid, false);
12842 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12843 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12844 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12845 result = createViewAsClause(fout, tbinfo);
12846 appendPQExpBuffer(q, " AS\n%s", result->data);
12847 destroyPQExpBuffer(result);
12849 if (tbinfo->checkoption != NULL)
12850 appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
12851 appendPQExpBuffer(q, ";\n");
12853 appendPQExpBuffer(labelq, "VIEW %s",
12854 fmtId(tbinfo->dobj.name));
12858 switch (tbinfo->relkind)
12860 case (RELKIND_FOREIGN_TABLE):
12862 PQExpBuffer query = createPQExpBuffer();
12867 reltypename = "FOREIGN TABLE";
12869 /* retrieve name of foreign server and generic options */
12870 appendPQExpBuffer(query,
12871 "SELECT fs.srvname, "
12872 "pg_catalog.array_to_string(ARRAY("
12873 "SELECT pg_catalog.quote_ident(option_name) || "
12874 "' ' || pg_catalog.quote_literal(option_value) "
12875 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12876 "ORDER BY option_name"
12877 "), E',\n ') AS ftoptions "
12878 "FROM pg_catalog.pg_foreign_table ft "
12879 "JOIN pg_catalog.pg_foreign_server fs "
12880 "ON (fs.oid = ft.ftserver) "
12881 "WHERE ft.ftrelid = '%u'",
12882 tbinfo->dobj.catId.oid);
12883 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12884 i_srvname = PQfnumber(res, "srvname");
12885 i_ftoptions = PQfnumber(res, "ftoptions");
12886 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12887 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12889 destroyPQExpBuffer(query);
12892 case (RELKIND_MATVIEW):
12893 reltypename = "MATERIALIZED VIEW";
12898 reltypename = "TABLE";
12903 numParents = tbinfo->numParents;
12904 parents = tbinfo->parents;
12907 * DROP must be fully qualified in case same name appears in
12910 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12911 fmtId(tbinfo->dobj.namespace->dobj.name));
12912 appendPQExpBuffer(delq, "%s;\n",
12913 fmtId(tbinfo->dobj.name));
12915 appendPQExpBuffer(labelq, "%s %s", reltypename,
12916 fmtId(tbinfo->dobj.name));
12918 if (binary_upgrade)
12919 binary_upgrade_set_pg_class_oids(fout, q,
12920 tbinfo->dobj.catId.oid, false);
12922 appendPQExpBuffer(q, "CREATE %s%s %s",
12923 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12926 fmtId(tbinfo->dobj.name));
12929 * Attach to type, if reloftype; except in case of a binary upgrade,
12930 * we dump the table normally and attach it to the type afterward.
12932 if (tbinfo->reloftype && !binary_upgrade)
12933 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12935 if (tbinfo->relkind != RELKIND_MATVIEW)
12937 /* Dump the attributes */
12939 for (j = 0; j < tbinfo->numatts; j++)
12942 * Normally, dump if it's locally defined in this table, and
12943 * not dropped. But for binary upgrade, we'll dump all the
12944 * columns, and then fix up the dropped and nonlocal cases
12947 if (shouldPrintColumn(tbinfo, j))
12950 * Default value --- suppress if to be printed separately.
12952 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12953 !tbinfo->attrdefs[j]->separate);
12956 * Not Null constraint --- suppress if inherited, except
12957 * in binary-upgrade case where that won't work.
12959 bool has_notnull = (tbinfo->notnull[j] &&
12960 (!tbinfo->inhNotNull[j] ||
12963 /* Skip column if fully defined by reloftype */
12964 if (tbinfo->reloftype &&
12965 !has_default && !has_notnull && !binary_upgrade)
12968 /* Format properly if not first attr */
12969 if (actual_atts == 0)
12970 appendPQExpBuffer(q, " (");
12972 appendPQExpBuffer(q, ",");
12973 appendPQExpBuffer(q, "\n ");
12976 /* Attribute name */
12977 appendPQExpBuffer(q, "%s",
12978 fmtId(tbinfo->attnames[j]));
12980 if (tbinfo->attisdropped[j])
12983 * ALTER TABLE DROP COLUMN clears
12984 * pg_attribute.atttypid, so we will not have gotten a
12985 * valid type name; insert INTEGER as a stopgap. We'll
12986 * clean things up later.
12988 appendPQExpBuffer(q, " INTEGER /* dummy */");
12989 /* Skip all the rest, too */
12993 /* Attribute type */
12994 if (tbinfo->reloftype && !binary_upgrade)
12996 appendPQExpBuffer(q, " WITH OPTIONS");
12998 else if (fout->remoteVersion >= 70100)
13000 appendPQExpBuffer(q, " %s",
13001 tbinfo->atttypnames[j]);
13005 /* If no format_type, fake it */
13006 appendPQExpBuffer(q, " %s",
13007 myFormatType(tbinfo->atttypnames[j],
13008 tbinfo->atttypmod[j]));
13011 /* Add collation if not default for the type */
13012 if (OidIsValid(tbinfo->attcollation[j]))
13016 coll = findCollationByOid(tbinfo->attcollation[j]);
13019 /* always schema-qualify, don't try to be smart */
13020 appendPQExpBuffer(q, " COLLATE %s.",
13021 fmtId(coll->dobj.namespace->dobj.name));
13022 appendPQExpBuffer(q, "%s",
13023 fmtId(coll->dobj.name));
13028 appendPQExpBuffer(q, " DEFAULT %s",
13029 tbinfo->attrdefs[j]->adef_expr);
13032 appendPQExpBuffer(q, " NOT NULL");
13037 * Add non-inherited CHECK constraints, if any.
13039 for (j = 0; j < tbinfo->ncheck; j++)
13041 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13043 if (constr->separate || !constr->conislocal)
13046 if (actual_atts == 0)
13047 appendPQExpBuffer(q, " (\n ");
13049 appendPQExpBuffer(q, ",\n ");
13051 appendPQExpBuffer(q, "CONSTRAINT %s ",
13052 fmtId(constr->dobj.name));
13053 appendPQExpBuffer(q, "%s", constr->condef);
13059 appendPQExpBuffer(q, "\n)");
13060 else if (!(tbinfo->reloftype && !binary_upgrade))
13063 * We must have a parenthesized attribute list, even though
13064 * empty, when not using the OF TYPE syntax.
13066 appendPQExpBuffer(q, " (\n)");
13069 if (numParents > 0 && !binary_upgrade)
13071 appendPQExpBuffer(q, "\nINHERITS (");
13072 for (k = 0; k < numParents; k++)
13074 TableInfo *parentRel = parents[k];
13077 appendPQExpBuffer(q, ", ");
13078 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13079 appendPQExpBuffer(q, "%s.",
13080 fmtId(parentRel->dobj.namespace->dobj.name));
13081 appendPQExpBuffer(q, "%s",
13082 fmtId(parentRel->dobj.name));
13084 appendPQExpBuffer(q, ")");
13087 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
13088 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
13091 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
13092 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
13094 bool addcomma = false;
13096 appendPQExpBuffer(q, "\nWITH (");
13097 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
13100 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
13102 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
13104 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
13105 tbinfo->toast_reloptions);
13107 appendPQExpBuffer(q, ")");
13110 /* Dump generic options if any */
13111 if (ftoptions && ftoptions[0])
13112 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
13115 * For materialized views, create the AS clause just like a view. At
13116 * this point, we always mark the view as not populated.
13118 if (tbinfo->relkind == RELKIND_MATVIEW)
13120 PQExpBuffer result;
13122 result = createViewAsClause(fout, tbinfo);
13123 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
13125 destroyPQExpBuffer(result);
13128 appendPQExpBuffer(q, ";\n");
13131 * To create binary-compatible heap files, we have to ensure the same
13132 * physical column order, including dropped columns, as in the
13133 * original. Therefore, we create dropped columns above and drop them
13134 * here, also updating their attlen/attalign values so that the
13135 * dropped column can be skipped properly. (We do not bother with
13136 * restoring the original attbyval setting.) Also, inheritance
13137 * relationships are set up by doing ALTER INHERIT rather than using
13138 * an INHERITS clause --- the latter would possibly mess up the column
13139 * order. That also means we have to take care about setting
13140 * attislocal correctly, plus fix up any inherited CHECK constraints.
13141 * Analogously, we set up typed tables using ALTER TABLE / OF here.
13143 if (binary_upgrade && (tbinfo->relkind == RELKIND_RELATION ||
13144 tbinfo->relkind == RELKIND_FOREIGN_TABLE) )
13146 for (j = 0; j < tbinfo->numatts; j++)
13148 if (tbinfo->attisdropped[j])
13150 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
13151 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13152 "SET attlen = %d, "
13153 "attalign = '%c', attbyval = false\n"
13154 "WHERE attname = ",
13156 tbinfo->attalign[j]);
13157 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13158 appendPQExpBuffer(q, "\n AND attrelid = ");
13159 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13160 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13162 if (tbinfo->relkind == RELKIND_RELATION)
13163 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13164 fmtId(tbinfo->dobj.name));
13166 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13167 fmtId(tbinfo->dobj.name));
13169 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
13170 fmtId(tbinfo->attnames[j]));
13172 else if (!tbinfo->attislocal[j])
13174 Assert(tbinfo->relkind != RELKIND_FOREIGN_TABLE);
13175 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
13176 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13177 "SET attislocal = false\n"
13178 "WHERE attname = ");
13179 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13180 appendPQExpBuffer(q, "\n AND attrelid = ");
13181 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13182 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13186 for (k = 0; k < tbinfo->ncheck; k++)
13188 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
13190 if (constr->separate || constr->conislocal)
13193 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
13194 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13195 fmtId(tbinfo->dobj.name));
13196 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13197 fmtId(constr->dobj.name));
13198 appendPQExpBuffer(q, "%s;\n", constr->condef);
13199 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
13200 "SET conislocal = false\n"
13201 "WHERE contype = 'c' AND conname = ");
13202 appendStringLiteralAH(q, constr->dobj.name, fout);
13203 appendPQExpBuffer(q, "\n AND conrelid = ");
13204 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13205 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13208 if (numParents > 0)
13210 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
13211 for (k = 0; k < numParents; k++)
13213 TableInfo *parentRel = parents[k];
13215 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
13216 fmtId(tbinfo->dobj.name));
13217 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13218 appendPQExpBuffer(q, "%s.",
13219 fmtId(parentRel->dobj.namespace->dobj.name));
13220 appendPQExpBuffer(q, "%s;\n",
13221 fmtId(parentRel->dobj.name));
13225 if (tbinfo->reloftype)
13227 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
13228 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
13229 fmtId(tbinfo->dobj.name),
13230 tbinfo->reloftype);
13233 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
13234 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13235 "SET relfrozenxid = '%u'\n"
13237 tbinfo->frozenxid);
13238 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13239 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13241 if (tbinfo->toast_oid)
13243 /* We preserve the toast oids, so we can use it during restore */
13244 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
13245 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13246 "SET relfrozenxid = '%u'\n"
13247 "WHERE oid = '%u';\n",
13248 tbinfo->toast_frozenxid, tbinfo->toast_oid);
13253 * In binary_upgrade mode, restore matviews' populated status by
13254 * poking pg_class directly. This is pretty ugly, but we can't use
13255 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
13256 * matview is not populated even though this matview is.
13258 if (binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
13259 tbinfo->relispopulated)
13261 appendPQExpBuffer(q, "\n-- For binary upgrade, mark materialized view as populated\n");
13262 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13263 "SET relispopulated = 't'\n"
13265 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13266 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13270 * Dump additional per-column properties that we can't handle in the
13271 * main CREATE TABLE command.
13273 for (j = 0; j < tbinfo->numatts; j++)
13275 /* None of this applies to dropped columns */
13276 if (tbinfo->attisdropped[j])
13280 * If we didn't dump the column definition explicitly above, and
13281 * it is NOT NULL and did not inherit that property from a parent,
13282 * we have to mark it separately.
13284 if (!shouldPrintColumn(tbinfo, j) &&
13285 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
13287 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13288 fmtId(tbinfo->dobj.name));
13289 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
13290 fmtId(tbinfo->attnames[j]));
13294 * Dump per-column statistics information. We only issue an ALTER
13295 * TABLE statement if the attstattarget entry for this column is
13296 * non-negative (i.e. it's not the default value)
13298 if (tbinfo->attstattarget[j] >= 0)
13300 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13301 fmtId(tbinfo->dobj.name));
13302 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13303 fmtId(tbinfo->attnames[j]));
13304 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
13305 tbinfo->attstattarget[j]);
13309 * Dump per-column storage information. The statement is only
13310 * dumped if the storage has been changed from the type's default.
13312 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
13314 switch (tbinfo->attstorage[j])
13320 storage = "EXTERNAL";
13326 storage = "EXTENDED";
13333 * Only dump the statement if it's a storage type we recognize
13335 if (storage != NULL)
13337 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13338 fmtId(tbinfo->dobj.name));
13339 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13340 fmtId(tbinfo->attnames[j]));
13341 appendPQExpBuffer(q, "SET STORAGE %s;\n",
13347 * Dump per-column attributes.
13349 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
13351 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13352 fmtId(tbinfo->dobj.name));
13353 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13354 fmtId(tbinfo->attnames[j]));
13355 appendPQExpBuffer(q, "SET (%s);\n",
13356 tbinfo->attoptions[j]);
13360 * Dump per-column fdw options.
13362 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
13363 tbinfo->attfdwoptions[j] &&
13364 tbinfo->attfdwoptions[j][0] != '\0')
13366 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13367 fmtId(tbinfo->dobj.name));
13368 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13369 fmtId(tbinfo->attnames[j]));
13370 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
13371 tbinfo->attfdwoptions[j]);
13376 if (binary_upgrade)
13377 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
13379 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13381 tbinfo->dobj.namespace->dobj.name,
13382 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
13384 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
13385 reltypename, SECTION_PRE_DATA,
13386 q->data, delq->data, NULL,
13391 /* Dump Table Comments */
13392 dumpTableComment(fout, tbinfo, reltypename);
13394 /* Dump Table Security Labels */
13395 dumpTableSecLabel(fout, tbinfo, reltypename);
13397 /* Dump comments on inlined table constraints */
13398 for (j = 0; j < tbinfo->ncheck; j++)
13400 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13402 if (constr->separate || !constr->conislocal)
13405 dumpTableConstraintComment(fout, constr);
13408 destroyPQExpBuffer(q);
13409 destroyPQExpBuffer(delq);
13410 destroyPQExpBuffer(labelq);
13414 * dumpAttrDef --- dump an attribute's default-value declaration
13417 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13419 TableInfo *tbinfo = adinfo->adtable;
13420 int adnum = adinfo->adnum;
13424 /* Skip if table definition not to be dumped */
13425 if (!tbinfo->dobj.dump || dataOnly)
13428 /* Skip if not "separate"; it was dumped in the table's definition */
13429 if (!adinfo->separate)
13432 q = createPQExpBuffer();
13433 delq = createPQExpBuffer();
13435 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13436 fmtId(tbinfo->dobj.name));
13437 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13438 fmtId(tbinfo->attnames[adnum - 1]),
13439 adinfo->adef_expr);
13442 * DROP must be fully qualified in case same name appears in pg_catalog
13444 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13445 fmtId(tbinfo->dobj.namespace->dobj.name));
13446 appendPQExpBuffer(delq, "%s ",
13447 fmtId(tbinfo->dobj.name));
13448 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13449 fmtId(tbinfo->attnames[adnum - 1]));
13451 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13452 tbinfo->attnames[adnum - 1],
13453 tbinfo->dobj.namespace->dobj.name,
13456 false, "DEFAULT", SECTION_PRE_DATA,
13457 q->data, delq->data, NULL,
13461 destroyPQExpBuffer(q);
13462 destroyPQExpBuffer(delq);
13466 * getAttrName: extract the correct name for an attribute
13468 * The array tblInfo->attnames[] only provides names of user attributes;
13469 * if a system attribute number is supplied, we have to fake it.
13470 * We also do a little bit of bounds checking for safety's sake.
13472 static const char *
13473 getAttrName(int attrnum, TableInfo *tblInfo)
13475 if (attrnum > 0 && attrnum <= tblInfo->numatts)
13476 return tblInfo->attnames[attrnum - 1];
13479 case SelfItemPointerAttributeNumber:
13481 case ObjectIdAttributeNumber:
13483 case MinTransactionIdAttributeNumber:
13485 case MinCommandIdAttributeNumber:
13487 case MaxTransactionIdAttributeNumber:
13489 case MaxCommandIdAttributeNumber:
13491 case TableOidAttributeNumber:
13494 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13495 attrnum, tblInfo->dobj.name);
13496 return NULL; /* keep compiler quiet */
13501 * write out to fout a user-defined index
13504 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13506 TableInfo *tbinfo = indxinfo->indextable;
13507 bool is_constraint = (indxinfo->indexconstraint != 0);
13510 PQExpBuffer labelq;
13515 q = createPQExpBuffer();
13516 delq = createPQExpBuffer();
13517 labelq = createPQExpBuffer();
13519 appendPQExpBuffer(labelq, "INDEX %s",
13520 fmtId(indxinfo->dobj.name));
13523 * If there's an associated constraint, don't dump the index per se, but
13524 * do dump any comment for it. (This is safe because dependency ordering
13525 * will have ensured the constraint is emitted first.) Note that the
13526 * emitted comment has to be shown as depending on the constraint, not
13527 * the index, in such cases.
13529 if (!is_constraint)
13531 if (binary_upgrade)
13532 binary_upgrade_set_pg_class_oids(fout, q,
13533 indxinfo->dobj.catId.oid, true);
13535 /* Plain secondary index */
13536 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13538 /* If the index is clustered, we need to record that. */
13539 if (indxinfo->indisclustered)
13541 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13542 fmtId(tbinfo->dobj.name));
13543 appendPQExpBuffer(q, " ON %s;\n",
13544 fmtId(indxinfo->dobj.name));
13548 * DROP must be fully qualified in case same name appears in
13551 appendPQExpBuffer(delq, "DROP INDEX %s.",
13552 fmtId(tbinfo->dobj.namespace->dobj.name));
13553 appendPQExpBuffer(delq, "%s;\n",
13554 fmtId(indxinfo->dobj.name));
13556 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13557 indxinfo->dobj.name,
13558 tbinfo->dobj.namespace->dobj.name,
13559 indxinfo->tablespace,
13560 tbinfo->rolname, false,
13561 "INDEX", SECTION_POST_DATA,
13562 q->data, delq->data, NULL,
13567 /* Dump Index Comments */
13568 dumpComment(fout, labelq->data,
13569 tbinfo->dobj.namespace->dobj.name,
13571 indxinfo->dobj.catId, 0,
13572 is_constraint ? indxinfo->indexconstraint :
13573 indxinfo->dobj.dumpId);
13575 destroyPQExpBuffer(q);
13576 destroyPQExpBuffer(delq);
13577 destroyPQExpBuffer(labelq);
13582 * write out to fout a user-defined constraint
13585 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13587 TableInfo *tbinfo = coninfo->contable;
13591 /* Skip if not to be dumped */
13592 if (!coninfo->dobj.dump || dataOnly)
13595 q = createPQExpBuffer();
13596 delq = createPQExpBuffer();
13598 if (coninfo->contype == 'p' ||
13599 coninfo->contype == 'u' ||
13600 coninfo->contype == 'x')
13602 /* Index-related constraint */
13603 IndxInfo *indxinfo;
13606 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13608 if (indxinfo == NULL)
13609 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13610 coninfo->dobj.name);
13612 if (binary_upgrade)
13613 binary_upgrade_set_pg_class_oids(fout, q,
13614 indxinfo->dobj.catId.oid, true);
13616 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13617 fmtId(tbinfo->dobj.name));
13618 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13619 fmtId(coninfo->dobj.name));
13621 if (coninfo->condef)
13623 /* pg_get_constraintdef should have provided everything */
13624 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13628 appendPQExpBuffer(q, "%s (",
13629 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13630 for (k = 0; k < indxinfo->indnkeys; k++)
13632 int indkey = (int) indxinfo->indkeys[k];
13633 const char *attname;
13635 if (indkey == InvalidAttrNumber)
13637 attname = getAttrName(indkey, tbinfo);
13639 appendPQExpBuffer(q, "%s%s",
13640 (k == 0) ? "" : ", ",
13644 appendPQExpBuffer(q, ")");
13646 if (indxinfo->options && strlen(indxinfo->options) > 0)
13647 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13649 if (coninfo->condeferrable)
13651 appendPQExpBuffer(q, " DEFERRABLE");
13652 if (coninfo->condeferred)
13653 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13656 appendPQExpBuffer(q, ";\n");
13659 /* If the index is clustered, we need to record that. */
13660 if (indxinfo->indisclustered)
13662 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13663 fmtId(tbinfo->dobj.name));
13664 appendPQExpBuffer(q, " ON %s;\n",
13665 fmtId(indxinfo->dobj.name));
13669 * DROP must be fully qualified in case same name appears in
13672 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13673 fmtId(tbinfo->dobj.namespace->dobj.name));
13674 appendPQExpBuffer(delq, "%s ",
13675 fmtId(tbinfo->dobj.name));
13676 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13677 fmtId(coninfo->dobj.name));
13679 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13680 coninfo->dobj.name,
13681 tbinfo->dobj.namespace->dobj.name,
13682 indxinfo->tablespace,
13683 tbinfo->rolname, false,
13684 "CONSTRAINT", SECTION_POST_DATA,
13685 q->data, delq->data, NULL,
13689 else if (coninfo->contype == 'f')
13692 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13693 * current table data is not processed
13695 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13696 fmtId(tbinfo->dobj.name));
13697 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13698 fmtId(coninfo->dobj.name),
13702 * DROP must be fully qualified in case same name appears in
13705 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13706 fmtId(tbinfo->dobj.namespace->dobj.name));
13707 appendPQExpBuffer(delq, "%s ",
13708 fmtId(tbinfo->dobj.name));
13709 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13710 fmtId(coninfo->dobj.name));
13712 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13713 coninfo->dobj.name,
13714 tbinfo->dobj.namespace->dobj.name,
13716 tbinfo->rolname, false,
13717 "FK CONSTRAINT", SECTION_POST_DATA,
13718 q->data, delq->data, NULL,
13722 else if (coninfo->contype == 'c' && tbinfo)
13724 /* CHECK constraint on a table */
13726 /* Ignore if not to be dumped separately */
13727 if (coninfo->separate)
13729 /* not ONLY since we want it to propagate to children */
13730 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13731 fmtId(tbinfo->dobj.name));
13732 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13733 fmtId(coninfo->dobj.name),
13737 * DROP must be fully qualified in case same name appears in
13740 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13741 fmtId(tbinfo->dobj.namespace->dobj.name));
13742 appendPQExpBuffer(delq, "%s ",
13743 fmtId(tbinfo->dobj.name));
13744 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13745 fmtId(coninfo->dobj.name));
13747 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13748 coninfo->dobj.name,
13749 tbinfo->dobj.namespace->dobj.name,
13751 tbinfo->rolname, false,
13752 "CHECK CONSTRAINT", SECTION_POST_DATA,
13753 q->data, delq->data, NULL,
13758 else if (coninfo->contype == 'c' && tbinfo == NULL)
13760 /* CHECK constraint on a domain */
13761 TypeInfo *tyinfo = coninfo->condomain;
13763 /* Ignore if not to be dumped separately */
13764 if (coninfo->separate)
13766 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13767 fmtId(tyinfo->dobj.name));
13768 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13769 fmtId(coninfo->dobj.name),
13773 * DROP must be fully qualified in case same name appears in
13776 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13777 fmtId(tyinfo->dobj.namespace->dobj.name));
13778 appendPQExpBuffer(delq, "%s ",
13779 fmtId(tyinfo->dobj.name));
13780 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13781 fmtId(coninfo->dobj.name));
13783 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13784 coninfo->dobj.name,
13785 tyinfo->dobj.namespace->dobj.name,
13787 tyinfo->rolname, false,
13788 "CHECK CONSTRAINT", SECTION_POST_DATA,
13789 q->data, delq->data, NULL,
13796 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13800 /* Dump Constraint Comments --- only works for table constraints */
13801 if (tbinfo && coninfo->separate)
13802 dumpTableConstraintComment(fout, coninfo);
13804 destroyPQExpBuffer(q);
13805 destroyPQExpBuffer(delq);
13809 * dumpTableConstraintComment --- dump a constraint's comment if any
13811 * This is split out because we need the function in two different places
13812 * depending on whether the constraint is dumped as part of CREATE TABLE
13813 * or as a separate ALTER command.
13816 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13818 TableInfo *tbinfo = coninfo->contable;
13819 PQExpBuffer labelq = createPQExpBuffer();
13821 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13822 fmtId(coninfo->dobj.name));
13823 appendPQExpBuffer(labelq, "ON %s",
13824 fmtId(tbinfo->dobj.name));
13825 dumpComment(fout, labelq->data,
13826 tbinfo->dobj.namespace->dobj.name,
13828 coninfo->dobj.catId, 0,
13829 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13831 destroyPQExpBuffer(labelq);
13835 * findLastBuiltInOid -
13836 * find the last built in oid
13838 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13839 * pg_database entry for the current database
13842 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13846 PQExpBuffer query = createPQExpBuffer();
13848 resetPQExpBuffer(query);
13849 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13850 appendStringLiteralAH(query, dbname, fout);
13852 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13853 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13855 destroyPQExpBuffer(query);
13860 * findLastBuiltInOid -
13861 * find the last built in oid
13863 * For 7.0, we do this by assuming that the last thing that initdb does is to
13864 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13865 * initdb won't be changing anymore, it'll do.
13868 findLastBuiltinOid_V70(Archive *fout)
13873 res = ExecuteSqlQueryForSingleRow(fout,
13874 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13875 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13882 * write the declaration (not data) of one user-defined sequence
13885 dumpSequence(Archive *fout, TableInfo *tbinfo)
13896 PQExpBuffer query = createPQExpBuffer();
13897 PQExpBuffer delqry = createPQExpBuffer();
13898 PQExpBuffer labelq = createPQExpBuffer();
13900 /* Make sure we are in proper schema */
13901 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13903 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13904 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13906 if (fout->remoteVersion >= 80400)
13908 appendPQExpBuffer(query,
13909 "SELECT sequence_name, "
13910 "start_value, increment_by, "
13911 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13912 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13914 "END AS max_value, "
13915 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13916 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13918 "END AS min_value, "
13919 "cache_value, is_cycled FROM %s",
13921 fmtId(tbinfo->dobj.name));
13925 appendPQExpBuffer(query,
13926 "SELECT sequence_name, "
13927 "0 AS start_value, increment_by, "
13928 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13929 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13931 "END AS max_value, "
13932 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13933 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13935 "END AS min_value, "
13936 "cache_value, is_cycled FROM %s",
13938 fmtId(tbinfo->dobj.name));
13941 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13943 if (PQntuples(res) != 1)
13945 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13946 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13948 tbinfo->dobj.name, PQntuples(res));
13952 /* Disable this check: it fails if sequence has been renamed */
13954 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13956 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13957 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13962 startv = PQgetvalue(res, 0, 1);
13963 incby = PQgetvalue(res, 0, 2);
13964 if (!PQgetisnull(res, 0, 3))
13965 maxv = PQgetvalue(res, 0, 3);
13966 if (!PQgetisnull(res, 0, 4))
13967 minv = PQgetvalue(res, 0, 4);
13968 cache = PQgetvalue(res, 0, 5);
13969 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13972 * DROP must be fully qualified in case same name appears in pg_catalog
13974 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13975 fmtId(tbinfo->dobj.namespace->dobj.name));
13976 appendPQExpBuffer(delqry, "%s;\n",
13977 fmtId(tbinfo->dobj.name));
13979 resetPQExpBuffer(query);
13981 if (binary_upgrade)
13983 binary_upgrade_set_pg_class_oids(fout, query,
13984 tbinfo->dobj.catId.oid, false);
13985 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13986 tbinfo->dobj.catId.oid);
13989 appendPQExpBuffer(query,
13990 "CREATE SEQUENCE %s\n",
13991 fmtId(tbinfo->dobj.name));
13993 if (fout->remoteVersion >= 80400)
13994 appendPQExpBuffer(query, " START WITH %s\n", startv);
13996 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13999 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
14001 appendPQExpBuffer(query, " NO MINVALUE\n");
14004 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
14006 appendPQExpBuffer(query, " NO MAXVALUE\n");
14008 appendPQExpBuffer(query,
14010 cache, (cycled ? "\n CYCLE" : ""));
14012 appendPQExpBuffer(query, ";\n");
14014 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
14016 /* binary_upgrade: no need to clear TOAST table oid */
14018 if (binary_upgrade)
14019 binary_upgrade_extension_member(query, &tbinfo->dobj,
14022 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
14024 tbinfo->dobj.namespace->dobj.name,
14027 false, "SEQUENCE", SECTION_PRE_DATA,
14028 query->data, delqry->data, NULL,
14033 * If the sequence is owned by a table column, emit the ALTER for it as a
14034 * separate TOC entry immediately following the sequence's own entry. It's
14035 * OK to do this rather than using full sorting logic, because the
14036 * dependency that tells us it's owned will have forced the table to be
14037 * created first. We can't just include the ALTER in the TOC entry
14038 * because it will fail if we haven't reassigned the sequence owner to
14039 * match the table's owner.
14041 * We need not schema-qualify the table reference because both sequence
14042 * and table must be in the same schema.
14044 if (OidIsValid(tbinfo->owning_tab))
14046 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
14048 if (owning_tab && owning_tab->dobj.dump)
14050 resetPQExpBuffer(query);
14051 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
14052 fmtId(tbinfo->dobj.name));
14053 appendPQExpBuffer(query, " OWNED BY %s",
14054 fmtId(owning_tab->dobj.name));
14055 appendPQExpBuffer(query, ".%s;\n",
14056 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
14058 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14060 tbinfo->dobj.namespace->dobj.name,
14063 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
14064 query->data, "", NULL,
14065 &(tbinfo->dobj.dumpId), 1,
14070 /* Dump Sequence Comments and Security Labels */
14071 dumpComment(fout, labelq->data,
14072 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14073 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14074 dumpSecLabel(fout, labelq->data,
14075 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14076 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14080 destroyPQExpBuffer(query);
14081 destroyPQExpBuffer(delqry);
14082 destroyPQExpBuffer(labelq);
14087 * write the data of one user-defined sequence
14090 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
14092 TableInfo *tbinfo = tdinfo->tdtable;
14096 PQExpBuffer query = createPQExpBuffer();
14098 /* Make sure we are in proper schema */
14099 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14101 appendPQExpBuffer(query,
14102 "SELECT last_value, is_called FROM %s",
14103 fmtId(tbinfo->dobj.name));
14105 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14107 if (PQntuples(res) != 1)
14109 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
14110 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
14112 tbinfo->dobj.name, PQntuples(res));
14116 last = PQgetvalue(res, 0, 0);
14117 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
14119 resetPQExpBuffer(query);
14120 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
14121 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
14122 appendPQExpBuffer(query, ", %s, %s);\n",
14123 last, (called ? "true" : "false"));
14125 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14127 tbinfo->dobj.namespace->dobj.name,
14130 false, "SEQUENCE SET", SECTION_DATA,
14131 query->data, "", NULL,
14132 &(tbinfo->dobj.dumpId), 1,
14137 destroyPQExpBuffer(query);
14141 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
14143 TableInfo *tbinfo = tginfo->tgtable;
14145 PQExpBuffer delqry;
14146 PQExpBuffer labelq;
14155 query = createPQExpBuffer();
14156 delqry = createPQExpBuffer();
14157 labelq = createPQExpBuffer();
14160 * DROP must be fully qualified in case same name appears in pg_catalog
14162 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
14163 fmtId(tginfo->dobj.name));
14164 appendPQExpBuffer(delqry, "ON %s.",
14165 fmtId(tbinfo->dobj.namespace->dobj.name));
14166 appendPQExpBuffer(delqry, "%s;\n",
14167 fmtId(tbinfo->dobj.name));
14171 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
14175 if (tginfo->tgisconstraint)
14177 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
14178 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
14182 appendPQExpBuffer(query, "CREATE TRIGGER ");
14183 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
14185 appendPQExpBuffer(query, "\n ");
14188 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
14189 appendPQExpBuffer(query, "BEFORE");
14190 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
14191 appendPQExpBuffer(query, "AFTER");
14192 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
14193 appendPQExpBuffer(query, "INSTEAD OF");
14196 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
14201 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
14203 appendPQExpBuffer(query, " INSERT");
14206 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
14209 appendPQExpBuffer(query, " OR DELETE");
14211 appendPQExpBuffer(query, " DELETE");
14214 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
14217 appendPQExpBuffer(query, " OR UPDATE");
14219 appendPQExpBuffer(query, " UPDATE");
14222 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
14225 appendPQExpBuffer(query, " OR TRUNCATE");
14227 appendPQExpBuffer(query, " TRUNCATE");
14230 appendPQExpBuffer(query, " ON %s\n",
14231 fmtId(tbinfo->dobj.name));
14233 if (tginfo->tgisconstraint)
14235 if (OidIsValid(tginfo->tgconstrrelid))
14237 /* If we are using regclass, name is already quoted */
14238 if (fout->remoteVersion >= 70300)
14239 appendPQExpBuffer(query, " FROM %s\n ",
14240 tginfo->tgconstrrelname);
14242 appendPQExpBuffer(query, " FROM %s\n ",
14243 fmtId(tginfo->tgconstrrelname));
14245 if (!tginfo->tgdeferrable)
14246 appendPQExpBuffer(query, "NOT ");
14247 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
14248 if (tginfo->tginitdeferred)
14249 appendPQExpBuffer(query, "DEFERRED\n");
14251 appendPQExpBuffer(query, "IMMEDIATE\n");
14254 if (TRIGGER_FOR_ROW(tginfo->tgtype))
14255 appendPQExpBuffer(query, " FOR EACH ROW\n ");
14257 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
14259 /* In 7.3, result of regproc is already quoted */
14260 if (fout->remoteVersion >= 70300)
14261 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14264 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14265 fmtId(tginfo->tgfname));
14267 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
14270 for (findx = 0; findx < tginfo->tgnargs; findx++)
14272 /* find the embedded null that terminates this trigger argument */
14273 size_t tlen = strlen(p);
14275 if (p + tlen >= tgargs + lentgargs)
14277 /* hm, not found before end of bytea value... */
14278 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
14281 tbinfo->dobj.name);
14286 appendPQExpBuffer(query, ", ");
14287 appendStringLiteralAH(query, p, fout);
14291 appendPQExpBuffer(query, ");\n");
14294 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
14296 appendPQExpBuffer(query, "\nALTER TABLE %s ",
14297 fmtId(tbinfo->dobj.name));
14298 switch (tginfo->tgenabled)
14302 appendPQExpBuffer(query, "DISABLE");
14305 appendPQExpBuffer(query, "ENABLE ALWAYS");
14308 appendPQExpBuffer(query, "ENABLE REPLICA");
14311 appendPQExpBuffer(query, "ENABLE");
14314 appendPQExpBuffer(query, " TRIGGER %s;\n",
14315 fmtId(tginfo->dobj.name));
14318 appendPQExpBuffer(labelq, "TRIGGER %s ",
14319 fmtId(tginfo->dobj.name));
14320 appendPQExpBuffer(labelq, "ON %s",
14321 fmtId(tbinfo->dobj.name));
14323 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
14325 tbinfo->dobj.namespace->dobj.name,
14327 tbinfo->rolname, false,
14328 "TRIGGER", SECTION_POST_DATA,
14329 query->data, delqry->data, NULL,
14333 dumpComment(fout, labelq->data,
14334 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14335 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
14337 destroyPQExpBuffer(query);
14338 destroyPQExpBuffer(delqry);
14339 destroyPQExpBuffer(labelq);
14343 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
14346 PQExpBuffer labelq;
14348 query = createPQExpBuffer();
14349 labelq = createPQExpBuffer();
14351 appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
14352 appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
14353 appendPQExpBuffer(query, " ON ");
14354 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
14355 appendPQExpBufferStr(query, " ");
14357 if (strcmp("", evtinfo->evttags) != 0)
14359 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
14360 appendPQExpBufferStr(query, evtinfo->evttags);
14361 appendPQExpBufferStr(query, ") ");
14364 appendPQExpBuffer(query, "\n EXECUTE PROCEDURE ");
14365 appendPQExpBufferStr(query, evtinfo->evtfname);
14366 appendPQExpBuffer(query, "();\n");
14368 if (evtinfo->evtenabled != 'O')
14370 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
14371 fmtId(evtinfo->dobj.name));
14372 switch (evtinfo->evtenabled)
14375 appendPQExpBuffer(query, "DISABLE");
14378 appendPQExpBuffer(query, "ENABLE ALWAYS");
14381 appendPQExpBuffer(query, "ENABLE REPLICA");
14384 appendPQExpBuffer(query, "ENABLE");
14387 appendPQExpBuffer(query, ";\n");
14389 appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
14390 fmtId(evtinfo->dobj.name));
14392 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
14393 evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
14394 "EVENT TRIGGER", SECTION_POST_DATA,
14395 query->data, "", NULL, NULL, 0, NULL, NULL);
14397 dumpComment(fout, labelq->data,
14399 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
14401 destroyPQExpBuffer(query);
14402 destroyPQExpBuffer(labelq);
14410 dumpRule(Archive *fout, RuleInfo *rinfo)
14412 TableInfo *tbinfo = rinfo->ruletable;
14415 PQExpBuffer delcmd;
14416 PQExpBuffer labelq;
14419 /* Skip if not to be dumped */
14420 if (!rinfo->dobj.dump || dataOnly)
14424 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
14425 * we do not want to dump it as a separate object.
14427 if (!rinfo->separate)
14431 * Make sure we are in proper schema.
14433 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14435 query = createPQExpBuffer();
14436 cmd = createPQExpBuffer();
14437 delcmd = createPQExpBuffer();
14438 labelq = createPQExpBuffer();
14440 if (fout->remoteVersion >= 70300)
14442 appendPQExpBuffer(query,
14443 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14444 rinfo->dobj.catId.oid);
14448 /* Rule name was unique before 7.3 ... */
14449 appendPQExpBuffer(query,
14450 "SELECT pg_get_ruledef('%s') AS definition",
14454 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14456 if (PQntuples(res) != 1)
14458 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14459 rinfo->dobj.name, tbinfo->dobj.name);
14463 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14466 * Add the command to alter the rules replication firing semantics if it
14467 * differs from the default.
14469 if (rinfo->ev_enabled != 'O')
14471 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14472 switch (rinfo->ev_enabled)
14475 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14476 fmtId(rinfo->dobj.name));
14479 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14480 fmtId(rinfo->dobj.name));
14483 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14484 fmtId(rinfo->dobj.name));
14490 * Apply view's reloptions when its ON SELECT rule is separate.
14492 if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14494 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14495 fmtId(tbinfo->dobj.name),
14496 rinfo->reloptions);
14500 * DROP must be fully qualified in case same name appears in pg_catalog
14502 appendPQExpBuffer(delcmd, "DROP RULE %s ",
14503 fmtId(rinfo->dobj.name));
14504 appendPQExpBuffer(delcmd, "ON %s.",
14505 fmtId(tbinfo->dobj.namespace->dobj.name));
14506 appendPQExpBuffer(delcmd, "%s;\n",
14507 fmtId(tbinfo->dobj.name));
14509 appendPQExpBuffer(labelq, "RULE %s",
14510 fmtId(rinfo->dobj.name));
14511 appendPQExpBuffer(labelq, " ON %s",
14512 fmtId(tbinfo->dobj.name));
14514 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14516 tbinfo->dobj.namespace->dobj.name,
14518 tbinfo->rolname, false,
14519 "RULE", SECTION_POST_DATA,
14520 cmd->data, delcmd->data, NULL,
14524 /* Dump rule comments */
14525 dumpComment(fout, labelq->data,
14526 tbinfo->dobj.namespace->dobj.name,
14528 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14532 destroyPQExpBuffer(query);
14533 destroyPQExpBuffer(cmd);
14534 destroyPQExpBuffer(delcmd);
14535 destroyPQExpBuffer(labelq);
14539 * getExtensionMembership --- obtain extension membership data
14542 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14553 DumpableObject *dobj,
14556 /* Nothing to do if no extensions */
14557 if (numExtensions == 0)
14560 /* Make sure we are in proper schema */
14561 selectSourceSchema(fout, "pg_catalog");
14563 query = createPQExpBuffer();
14565 /* refclassid constraint is redundant but may speed the search */
14566 appendPQExpBuffer(query, "SELECT "
14567 "classid, objid, refclassid, refobjid "
14569 "WHERE refclassid = 'pg_extension'::regclass "
14570 "AND deptype = 'e' "
14573 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14575 ntups = PQntuples(res);
14577 i_classid = PQfnumber(res, "classid");
14578 i_objid = PQfnumber(res, "objid");
14579 i_refclassid = PQfnumber(res, "refclassid");
14580 i_refobjid = PQfnumber(res, "refobjid");
14583 * Since we ordered the SELECT by referenced ID, we can expect that
14584 * multiple entries for the same extension will appear together; this
14585 * saves on searches.
14589 for (i = 0; i < ntups; i++)
14592 CatalogId refobjId;
14594 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14595 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14596 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14597 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14599 if (refdobj == NULL ||
14600 refdobj->catId.tableoid != refobjId.tableoid ||
14601 refdobj->catId.oid != refobjId.oid)
14602 refdobj = findObjectByCatalogId(refobjId);
14605 * Failure to find objects mentioned in pg_depend is not unexpected,
14606 * since for example we don't collect info about TOAST tables.
14608 if (refdobj == NULL)
14611 fprintf(stderr, "no referenced object %u %u\n",
14612 refobjId.tableoid, refobjId.oid);
14617 dobj = findObjectByCatalogId(objId);
14622 fprintf(stderr, "no referencing object %u %u\n",
14623 objId.tableoid, objId.oid);
14628 /* Record dependency so that getDependencies needn't repeat this */
14629 addObjectDependency(dobj, refdobj->dumpId);
14631 dobj->ext_member = true;
14634 * Normally, mark the member object as not to be dumped. But in
14635 * binary upgrades, we still dump the members individually, since the
14636 * idea is to exactly reproduce the database contents rather than
14637 * replace the extension contents with something different.
14639 if (!binary_upgrade)
14640 dobj->dump = false;
14642 dobj->dump = refdobj->dump;
14648 * Now identify extension configuration tables and create TableDataInfo
14649 * objects for them, ensuring their data will be dumped even though the
14650 * tables themselves won't be.
14652 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14653 * user data in a configuration table is treated like schema data. This
14654 * seems appropriate since system data in a config table would get
14655 * reloaded by CREATE EXTENSION.
14657 for (i = 0; i < numExtensions; i++)
14659 ExtensionInfo *curext = &(extinfo[i]);
14660 char *extconfig = curext->extconfig;
14661 char *extcondition = curext->extcondition;
14662 char **extconfigarray = NULL;
14663 char **extconditionarray = NULL;
14665 int nconditionitems;
14667 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14668 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14669 nconfigitems == nconditionitems)
14673 for (j = 0; j < nconfigitems; j++)
14675 TableInfo *configtbl;
14676 Oid configtbloid = atooid(extconfigarray[j]);
14677 bool dumpobj = curext->dobj.dump;
14679 configtbl = findTableByOid(configtbloid);
14680 if (configtbl == NULL)
14684 * Tables of not-to-be-dumped extensions shouldn't be dumped
14685 * unless the table or its schema is explicitly included
14687 if (!curext->dobj.dump)
14689 /* check table explicitly requested */
14690 if (table_include_oids.head != NULL &&
14691 simple_oid_list_member(&table_include_oids,
14695 /* check table's schema explicitly requested */
14696 if (configtbl->dobj.namespace->dobj.dump)
14700 /* check table excluded by an exclusion switch */
14701 if (table_exclude_oids.head != NULL &&
14702 simple_oid_list_member(&table_exclude_oids,
14706 /* check schema excluded by an exclusion switch */
14707 if (simple_oid_list_member(&schema_exclude_oids,
14708 configtbl->dobj.namespace->dobj.catId.oid))
14714 * Note: config tables are dumped without OIDs regardless
14715 * of the --oids setting. This is because row filtering
14716 * conditions aren't compatible with dumping OIDs.
14718 makeTableDataInfo(configtbl, false);
14719 if (configtbl->dataObj != NULL)
14721 if (strlen(extconditionarray[j]) > 0)
14722 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14727 if (extconfigarray)
14728 free(extconfigarray);
14729 if (extconditionarray)
14730 free(extconditionarray);
14733 destroyPQExpBuffer(query);
14737 * getDependencies --- obtain available dependency data
14740 getDependencies(Archive *fout)
14751 DumpableObject *dobj,
14754 /* No dependency info available before 7.3 */
14755 if (fout->remoteVersion < 70300)
14759 write_msg(NULL, "reading dependency data\n");
14761 /* Make sure we are in proper schema */
14762 selectSourceSchema(fout, "pg_catalog");
14764 query = createPQExpBuffer();
14767 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14768 * already processed by getExtensionMembership.
14770 appendPQExpBuffer(query, "SELECT "
14771 "classid, objid, refclassid, refobjid, deptype "
14773 "WHERE deptype != 'p' AND deptype != 'e' "
14776 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14778 ntups = PQntuples(res);
14780 i_classid = PQfnumber(res, "classid");
14781 i_objid = PQfnumber(res, "objid");
14782 i_refclassid = PQfnumber(res, "refclassid");
14783 i_refobjid = PQfnumber(res, "refobjid");
14784 i_deptype = PQfnumber(res, "deptype");
14787 * Since we ordered the SELECT by referencing ID, we can expect that
14788 * multiple entries for the same object will appear together; this saves
14793 for (i = 0; i < ntups; i++)
14796 CatalogId refobjId;
14799 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14800 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14801 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14802 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14803 deptype = *(PQgetvalue(res, i, i_deptype));
14805 if (dobj == NULL ||
14806 dobj->catId.tableoid != objId.tableoid ||
14807 dobj->catId.oid != objId.oid)
14808 dobj = findObjectByCatalogId(objId);
14811 * Failure to find objects mentioned in pg_depend is not unexpected,
14812 * since for example we don't collect info about TOAST tables.
14817 fprintf(stderr, "no referencing object %u %u\n",
14818 objId.tableoid, objId.oid);
14823 refdobj = findObjectByCatalogId(refobjId);
14825 if (refdobj == NULL)
14828 fprintf(stderr, "no referenced object %u %u\n",
14829 refobjId.tableoid, refobjId.oid);
14835 * Ordinarily, table rowtypes have implicit dependencies on their
14836 * tables. However, for a composite type the implicit dependency goes
14837 * the other way in pg_depend; which is the right thing for DROP but
14838 * it doesn't produce the dependency ordering we need. So in that one
14839 * case, we reverse the direction of the dependency.
14841 if (deptype == 'i' &&
14842 dobj->objType == DO_TABLE &&
14843 refdobj->objType == DO_TYPE)
14844 addObjectDependency(refdobj, dobj->dumpId);
14847 addObjectDependency(dobj, refdobj->dumpId);
14852 destroyPQExpBuffer(query);
14857 * createBoundaryObjects - create dummy DumpableObjects to represent
14858 * dump section boundaries.
14860 static DumpableObject *
14861 createBoundaryObjects(void)
14863 DumpableObject *dobjs;
14865 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14867 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14868 dobjs[0].catId = nilCatalogId;
14869 AssignDumpId(dobjs + 0);
14870 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14872 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14873 dobjs[1].catId = nilCatalogId;
14874 AssignDumpId(dobjs + 1);
14875 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14881 * addBoundaryDependencies - add dependencies as needed to enforce the dump
14882 * section boundaries.
14885 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14886 DumpableObject *boundaryObjs)
14888 DumpableObject *preDataBound = boundaryObjs + 0;
14889 DumpableObject *postDataBound = boundaryObjs + 1;
14892 for (i = 0; i < numObjs; i++)
14894 DumpableObject *dobj = dobjs[i];
14897 * The classification of object types here must match the SECTION_xxx
14898 * values assigned during subsequent ArchiveEntry calls!
14900 switch (dobj->objType)
14905 case DO_SHELL_TYPE:
14912 case DO_CONVERSION:
14917 case DO_DUMMY_TYPE:
14920 case DO_TSTEMPLATE:
14923 case DO_FOREIGN_SERVER:
14925 /* Pre-data objects: must come before the pre-data boundary */
14926 addObjectDependency(preDataBound, dobj->dumpId);
14928 case DO_TABLE_DATA:
14930 /* Data objects: must come between the boundaries */
14931 addObjectDependency(dobj, preDataBound->dumpId);
14932 addObjectDependency(postDataBound, dobj->dumpId);
14935 case DO_REFRESH_MATVIEW:
14937 case DO_EVENT_TRIGGER:
14938 case DO_DEFAULT_ACL:
14939 /* Post-data objects: must come after the post-data boundary */
14940 addObjectDependency(dobj, postDataBound->dumpId);
14943 /* Rules are post-data, but only if dumped separately */
14944 if (((RuleInfo *) dobj)->separate)
14945 addObjectDependency(dobj, postDataBound->dumpId);
14947 case DO_CONSTRAINT:
14948 case DO_FK_CONSTRAINT:
14949 /* Constraints are post-data, but only if dumped separately */
14950 if (((ConstraintInfo *) dobj)->separate)
14951 addObjectDependency(dobj, postDataBound->dumpId);
14953 case DO_PRE_DATA_BOUNDARY:
14954 /* nothing to do */
14956 case DO_POST_DATA_BOUNDARY:
14957 /* must come after the pre-data boundary */
14958 addObjectDependency(dobj, preDataBound->dumpId);
14966 * BuildArchiveDependencies - create dependency data for archive TOC entries
14968 * The raw dependency data obtained by getDependencies() is not terribly
14969 * useful in an archive dump, because in many cases there are dependency
14970 * chains linking through objects that don't appear explicitly in the dump.
14971 * For example, a view will depend on its _RETURN rule while the _RETURN rule
14972 * will depend on other objects --- but the rule will not appear as a separate
14973 * object in the dump. We need to adjust the view's dependencies to include
14974 * whatever the rule depends on that is included in the dump.
14976 * Just to make things more complicated, there are also "special" dependencies
14977 * such as the dependency of a TABLE DATA item on its TABLE, which we must
14978 * not rearrange because pg_restore knows that TABLE DATA only depends on
14979 * its table. In these cases we must leave the dependencies strictly as-is
14980 * even if they refer to not-to-be-dumped objects.
14982 * To handle this, the convention is that "special" dependencies are created
14983 * during ArchiveEntry calls, and an archive TOC item that has any such
14984 * entries will not be touched here. Otherwise, we recursively search the
14985 * DumpableObject data structures to build the correct dependencies for each
14986 * archive TOC item.
14989 BuildArchiveDependencies(Archive *fout)
14991 ArchiveHandle *AH = (ArchiveHandle *) fout;
14994 /* Scan all TOC entries in the archive */
14995 for (te = AH->toc->next; te != AH->toc; te = te->next)
14997 DumpableObject *dobj;
14998 DumpId *dependencies;
15002 /* No need to process entries that will not be dumped */
15005 /* Ignore entries that already have "special" dependencies */
15008 /* Otherwise, look up the item's original DumpableObject, if any */
15009 dobj = findObjectByDumpId(te->dumpId);
15012 /* No work if it has no dependencies */
15013 if (dobj->nDeps <= 0)
15015 /* Set up work array */
15017 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
15019 /* Recursively find all dumpable dependencies */
15020 findDumpableDependencies(AH, dobj,
15021 &dependencies, &nDeps, &allocDeps);
15022 /* And save 'em ... */
15025 dependencies = (DumpId *) pg_realloc(dependencies,
15026 nDeps * sizeof(DumpId));
15027 te->dependencies = dependencies;
15031 free(dependencies);
15035 /* Recursive search subroutine for BuildArchiveDependencies */
15037 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
15038 DumpId **dependencies, int *nDeps, int *allocDeps)
15043 * Ignore section boundary objects: if we search through them, we'll
15044 * report lots of bogus dependencies.
15046 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
15047 dobj->objType == DO_POST_DATA_BOUNDARY)
15050 for (i = 0; i < dobj->nDeps; i++)
15052 DumpId depid = dobj->dependencies[i];
15054 if (TocIDRequired(AH, depid) != 0)
15056 /* Object will be dumped, so just reference it as a dependency */
15057 if (*nDeps >= *allocDeps)
15060 *dependencies = (DumpId *) pg_realloc(*dependencies,
15061 *allocDeps * sizeof(DumpId));
15063 (*dependencies)[*nDeps] = depid;
15069 * Object will not be dumped, so recursively consider its deps. We
15070 * rely on the assumption that sortDumpableObjects already broke
15071 * any dependency loops, else we might recurse infinitely.
15073 DumpableObject *otherdobj = findObjectByDumpId(depid);
15076 findDumpableDependencies(AH, otherdobj,
15077 dependencies, nDeps, allocDeps);
15084 * selectSourceSchema - make the specified schema the active search path
15085 * in the source database.
15087 * NB: pg_catalog is explicitly searched after the specified schema;
15088 * so user names are only qualified if they are cross-schema references,
15089 * and system names are only qualified if they conflict with a user name
15090 * in the current schema.
15092 * Whenever the selected schema is not pg_catalog, be careful to qualify
15093 * references to system catalogs and types in our emitted commands!
15095 * This function is called only from selectSourceSchemaOnAH and
15096 * selectSourceSchema.
15099 selectSourceSchema(Archive *fout, const char *schemaName)
15103 /* This is checked by the callers already */
15104 Assert(schemaName != NULL && *schemaName != '\0');
15106 /* Not relevant if fetching from pre-7.3 DB */
15107 if (fout->remoteVersion < 70300)
15110 query = createPQExpBuffer();
15111 appendPQExpBuffer(query, "SET search_path = %s",
15112 fmtId(schemaName));
15113 if (strcmp(schemaName, "pg_catalog") != 0)
15114 appendPQExpBuffer(query, ", pg_catalog");
15116 ExecuteSqlStatement(fout, query->data);
15118 destroyPQExpBuffer(query);
15122 * getFormattedTypeName - retrieve a nicely-formatted type name for the
15125 * NB: in 7.3 and up the result may depend on the currently-selected
15126 * schema; this is why we don't try to cache the names.
15129 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
15137 if ((opts & zeroAsOpaque) != 0)
15138 return pg_strdup(g_opaque_type);
15139 else if ((opts & zeroAsAny) != 0)
15140 return pg_strdup("'any'");
15141 else if ((opts & zeroAsStar) != 0)
15142 return pg_strdup("*");
15143 else if ((opts & zeroAsNone) != 0)
15144 return pg_strdup("NONE");
15147 query = createPQExpBuffer();
15148 if (fout->remoteVersion >= 70300)
15150 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
15153 else if (fout->remoteVersion >= 70100)
15155 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
15160 appendPQExpBuffer(query, "SELECT typname "
15162 "WHERE oid = '%u'::oid",
15166 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15168 if (fout->remoteVersion >= 70100)
15170 /* already quoted */
15171 result = pg_strdup(PQgetvalue(res, 0, 0));
15175 /* may need to quote it */
15176 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
15180 destroyPQExpBuffer(query);
15186 * myFormatType --- local implementation of format_type for use with 7.0.
15189 myFormatType(const char *typname, int32 typmod)
15192 bool isarray = false;
15193 PQExpBuffer buf = createPQExpBuffer();
15195 /* Handle array types */
15196 if (typname[0] == '_')
15202 /* Show lengths on bpchar and varchar */
15203 if (strcmp(typname, "bpchar") == 0)
15205 int len = (typmod - VARHDRSZ);
15207 appendPQExpBuffer(buf, "character");
15209 appendPQExpBuffer(buf, "(%d)",
15210 typmod - VARHDRSZ);
15212 else if (strcmp(typname, "varchar") == 0)
15214 appendPQExpBuffer(buf, "character varying");
15216 appendPQExpBuffer(buf, "(%d)",
15217 typmod - VARHDRSZ);
15219 else if (strcmp(typname, "numeric") == 0)
15221 appendPQExpBuffer(buf, "numeric");
15228 tmp_typmod = typmod - VARHDRSZ;
15229 precision = (tmp_typmod >> 16) & 0xffff;
15230 scale = tmp_typmod & 0xffff;
15231 appendPQExpBuffer(buf, "(%d,%d)",
15237 * char is an internal single-byte data type; Let's make sure we force it
15238 * through with quotes. - thomas 1998-12-13
15240 else if (strcmp(typname, "char") == 0)
15241 appendPQExpBuffer(buf, "\"char\"");
15243 appendPQExpBuffer(buf, "%s", fmtId(typname));
15245 /* Append array qualifier for array types */
15247 appendPQExpBuffer(buf, "[]");
15249 result = pg_strdup(buf->data);
15250 destroyPQExpBuffer(buf);
15256 * Return a column list clause for the given relation.
15258 * Special case: if there are no undropped columns in the relation, return
15259 * "", not an invalid "()" column list.
15261 static const char *
15262 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
15264 int numatts = ti->numatts;
15265 char **attnames = ti->attnames;
15266 bool *attisdropped = ti->attisdropped;
15270 appendPQExpBuffer(buffer, "(");
15272 for (i = 0; i < numatts; i++)
15274 if (attisdropped[i])
15277 appendPQExpBuffer(buffer, ", ");
15278 appendPQExpBuffer(buffer, "%s", fmtId(attnames[i]));
15283 return ""; /* no undropped columns */
15285 appendPQExpBuffer(buffer, ")");
15286 return buffer->data;
15290 * Execute an SQL query and verify that we got exactly one row back.
15293 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
15298 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
15300 /* Expecting a single result only */
15301 ntups = PQntuples(res);
15303 exit_horribly(NULL,
15304 ngettext("query returned %d row instead of one: %s\n",
15305 "query returned %d rows instead of one: %s\n",