1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
14 * Note that pg_dump runs in a transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to run on
18 * SnapshotNow time, ie they look at the currently committed state. So
19 * it is possible to get 'cache lookup failed' error if someone
20 * performs DDL changes while a dump is happening. The window for this
21 * sort of thing is from the acquisition of the transaction snapshot to
22 * getSchemaData() (when pg_dump acquires AccessShareLock on every
23 * table it intends to dump). It isn't very large, but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
33 #include "postgres_fe.h"
44 #include "getopt_long.h"
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_event_trigger.h"
53 #include "catalog/pg_largeobject.h"
54 #include "catalog/pg_largeobject_metadata.h"
55 #include "catalog/pg_proc.h"
56 #include "catalog/pg_trigger.h"
57 #include "catalog/pg_type.h"
58 #include "libpq/libpq-fs.h"
60 #include "pg_backup_archiver.h"
61 #include "pg_backup_db.h"
62 #include "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 scannable, skip this. */
1763 if (!tbinfo->isscannable)
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->isscannable)
1971 tbinfo->isscannable = 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_class_reltoastidxid;
2783 appendPQExpBuffer(upgrade_query,
2784 "SELECT c.reltoastrelid, t.reltoastidxid "
2785 "FROM pg_catalog.pg_class c LEFT JOIN "
2786 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
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_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
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_class_reltoastidxid);
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;
4225 int i_reltablespace;
4227 int i_toastreloptions;
4231 /* Make sure we are in proper schema */
4232 selectSourceSchema(fout, "pg_catalog");
4235 * Find all the tables and table-like objects.
4237 * We include system catalogs, so that we can work if a user table is
4238 * defined to inherit from a system catalog (pretty weird, but...)
4240 * We ignore relations that are not ordinary tables, sequences, views,
4241 * materialized views, composite types, or foreign tables.
4243 * Composite-type table entries won't be dumped as such, but we have to
4244 * make a DumpableObject for them so that we can track dependencies of the
4245 * composite type (pg_depend entries for columns of the composite type
4246 * link to the pg_class entry not the pg_type entry).
4248 * Note: in this phase we should collect only a minimal amount of
4249 * information about each table, basically just enough to decide if it is
4250 * interesting. We must fetch all tables in this phase because otherwise
4251 * we cannot correctly identify inherited columns, owned sequences, etc.
4254 if (fout->remoteVersion >= 90300)
4257 * Left join to pick up dependency info linking sequences to their
4258 * owning column, if any (note this dependency is AUTO as of 8.2)
4260 appendPQExpBuffer(query,
4261 "SELECT c.tableoid, c.oid, c.relname, "
4262 "c.relacl, c.relkind, c.relnamespace, "
4263 "(%s c.relowner) AS rolname, "
4264 "c.relchecks, c.relhastriggers, "
4265 "c.relhasindex, c.relhasrules, c.relhasoids, "
4266 "c.relfrozenxid, tc.oid AS toid, "
4267 "tc.relfrozenxid AS tfrozenxid, "
4268 "c.relpersistence, "
4269 "CASE WHEN c.relkind = '%c' THEN pg_relation_is_scannable(c.oid) ELSE 't'::bool END as isscannable, "
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(c.reloptions, ', ') AS reloptions, "
4276 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4278 "LEFT JOIN pg_depend d ON "
4279 "(c.relkind = '%c' AND "
4280 "d.classid = c.tableoid AND d.objid = c.oid AND "
4281 "d.objsubid = 0 AND "
4282 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4283 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4284 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4289 RELKIND_RELATION, RELKIND_SEQUENCE,
4290 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4291 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4293 else if (fout->remoteVersion >= 90100)
4296 * Left join to pick up dependency info linking sequences to their
4297 * owning column, if any (note this dependency is AUTO as of 8.2)
4299 appendPQExpBuffer(query,
4300 "SELECT c.tableoid, c.oid, c.relname, "
4301 "c.relacl, c.relkind, c.relnamespace, "
4302 "(%s c.relowner) AS rolname, "
4303 "c.relchecks, c.relhastriggers, "
4304 "c.relhasindex, c.relhasrules, c.relhasoids, "
4305 "c.relfrozenxid, tc.oid AS toid, "
4306 "tc.relfrozenxid AS tfrozenxid, "
4307 "c.relpersistence, 't'::bool as isscannable, "
4309 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4310 "d.refobjid AS owning_tab, "
4311 "d.refobjsubid AS owning_col, "
4312 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4313 "array_to_string(c.reloptions, ', ') AS reloptions, "
4314 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4316 "LEFT JOIN pg_depend d ON "
4317 "(c.relkind = '%c' AND "
4318 "d.classid = c.tableoid AND d.objid = c.oid AND "
4319 "d.objsubid = 0 AND "
4320 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4321 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4322 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
4326 RELKIND_RELATION, RELKIND_SEQUENCE,
4327 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4328 RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE);
4330 else if (fout->remoteVersion >= 90000)
4333 * Left join to pick up dependency info linking sequences to their
4334 * owning column, if any (note this dependency is AUTO as of 8.2)
4336 appendPQExpBuffer(query,
4337 "SELECT c.tableoid, c.oid, c.relname, "
4338 "c.relacl, c.relkind, c.relnamespace, "
4339 "(%s c.relowner) AS rolname, "
4340 "c.relchecks, c.relhastriggers, "
4341 "c.relhasindex, c.relhasrules, c.relhasoids, "
4342 "c.relfrozenxid, tc.oid AS toid, "
4343 "tc.relfrozenxid AS tfrozenxid, "
4344 "'p' AS relpersistence, 't'::bool as isscannable, "
4346 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4347 "d.refobjid AS owning_tab, "
4348 "d.refobjsubid AS owning_col, "
4349 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4350 "array_to_string(c.reloptions, ', ') AS reloptions, "
4351 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4353 "LEFT JOIN pg_depend d ON "
4354 "(c.relkind = '%c' AND "
4355 "d.classid = c.tableoid AND d.objid = c.oid AND "
4356 "d.objsubid = 0 AND "
4357 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4358 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4359 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4363 RELKIND_RELATION, RELKIND_SEQUENCE,
4364 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4366 else if (fout->remoteVersion >= 80400)
4369 * Left join to pick up dependency info linking sequences to their
4370 * owning column, if any (note this dependency is AUTO as of 8.2)
4372 appendPQExpBuffer(query,
4373 "SELECT c.tableoid, c.oid, c.relname, "
4374 "c.relacl, c.relkind, c.relnamespace, "
4375 "(%s c.relowner) AS rolname, "
4376 "c.relchecks, c.relhastriggers, "
4377 "c.relhasindex, c.relhasrules, c.relhasoids, "
4378 "c.relfrozenxid, tc.oid AS toid, "
4379 "tc.relfrozenxid AS tfrozenxid, "
4380 "'p' AS relpersistence, 't'::bool as isscannable, "
4382 "NULL AS reloftype, "
4383 "d.refobjid AS owning_tab, "
4384 "d.refobjsubid AS owning_col, "
4385 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4386 "array_to_string(c.reloptions, ', ') AS reloptions, "
4387 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4389 "LEFT JOIN pg_depend d ON "
4390 "(c.relkind = '%c' AND "
4391 "d.classid = c.tableoid AND d.objid = c.oid AND "
4392 "d.objsubid = 0 AND "
4393 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4394 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4395 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4399 RELKIND_RELATION, RELKIND_SEQUENCE,
4400 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4402 else if (fout->remoteVersion >= 80200)
4405 * Left join to pick up dependency info linking sequences to their
4406 * owning column, if any (note this dependency is AUTO as of 8.2)
4408 appendPQExpBuffer(query,
4409 "SELECT c.tableoid, c.oid, c.relname, "
4410 "c.relacl, c.relkind, c.relnamespace, "
4411 "(%s c.relowner) AS rolname, "
4412 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4413 "c.relhasindex, c.relhasrules, c.relhasoids, "
4414 "c.relfrozenxid, tc.oid AS toid, "
4415 "tc.relfrozenxid AS tfrozenxid, "
4416 "'p' AS relpersistence, 't'::bool as isscannable, "
4418 "NULL AS reloftype, "
4419 "d.refobjid AS owning_tab, "
4420 "d.refobjsubid AS owning_col, "
4421 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4422 "array_to_string(c.reloptions, ', ') AS reloptions, "
4423 "NULL AS toast_reloptions "
4425 "LEFT JOIN pg_depend d ON "
4426 "(c.relkind = '%c' AND "
4427 "d.classid = c.tableoid AND d.objid = c.oid AND "
4428 "d.objsubid = 0 AND "
4429 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4430 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4431 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4435 RELKIND_RELATION, RELKIND_SEQUENCE,
4436 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4438 else if (fout->remoteVersion >= 80000)
4441 * Left join to pick up dependency info linking sequences to their
4442 * owning column, if any
4444 appendPQExpBuffer(query,
4445 "SELECT c.tableoid, c.oid, relname, "
4446 "relacl, relkind, relnamespace, "
4447 "(%s relowner) AS rolname, "
4448 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4449 "relhasindex, relhasrules, relhasoids, "
4450 "0 AS relfrozenxid, "
4453 "'p' AS relpersistence, 't'::bool as isscannable, "
4455 "NULL AS reloftype, "
4456 "d.refobjid AS owning_tab, "
4457 "d.refobjsubid AS owning_col, "
4458 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4459 "NULL AS reloptions, "
4460 "NULL AS toast_reloptions "
4462 "LEFT JOIN pg_depend d ON "
4463 "(c.relkind = '%c' AND "
4464 "d.classid = c.tableoid AND d.objid = c.oid AND "
4465 "d.objsubid = 0 AND "
4466 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4467 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4471 RELKIND_RELATION, RELKIND_SEQUENCE,
4472 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4474 else if (fout->remoteVersion >= 70300)
4477 * Left join to pick up dependency info linking sequences to their
4478 * owning column, if any
4480 appendPQExpBuffer(query,
4481 "SELECT c.tableoid, c.oid, relname, "
4482 "relacl, relkind, relnamespace, "
4483 "(%s relowner) AS rolname, "
4484 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4485 "relhasindex, relhasrules, relhasoids, "
4486 "0 AS relfrozenxid, "
4489 "'p' AS relpersistence, 't'::bool as isscannable, "
4491 "NULL AS reloftype, "
4492 "d.refobjid AS owning_tab, "
4493 "d.refobjsubid AS owning_col, "
4494 "NULL AS reltablespace, "
4495 "NULL AS reloptions, "
4496 "NULL AS toast_reloptions "
4498 "LEFT JOIN pg_depend d ON "
4499 "(c.relkind = '%c' AND "
4500 "d.classid = c.tableoid AND d.objid = c.oid AND "
4501 "d.objsubid = 0 AND "
4502 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4503 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4507 RELKIND_RELATION, RELKIND_SEQUENCE,
4508 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4510 else if (fout->remoteVersion >= 70200)
4512 appendPQExpBuffer(query,
4513 "SELECT tableoid, oid, relname, relacl, relkind, "
4514 "0::oid AS relnamespace, "
4515 "(%s relowner) AS rolname, "
4516 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4517 "relhasindex, relhasrules, relhasoids, "
4518 "0 AS relfrozenxid, "
4521 "'p' AS relpersistence, 't'::bool as isscannable, "
4523 "NULL AS reloftype, "
4524 "NULL::oid AS owning_tab, "
4525 "NULL::int4 AS owning_col, "
4526 "NULL AS reltablespace, "
4527 "NULL AS reloptions, "
4528 "NULL AS toast_reloptions "
4530 "WHERE relkind IN ('%c', '%c', '%c') "
4533 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4535 else if (fout->remoteVersion >= 70100)
4537 /* all tables have oids in 7.1 */
4538 appendPQExpBuffer(query,
4539 "SELECT tableoid, oid, relname, relacl, relkind, "
4540 "0::oid AS relnamespace, "
4541 "(%s relowner) AS rolname, "
4542 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4543 "relhasindex, relhasrules, "
4544 "'t'::bool AS relhasoids, "
4545 "0 AS relfrozenxid, "
4548 "'p' AS relpersistence, 't'::bool as isscannable, "
4550 "NULL AS reloftype, "
4551 "NULL::oid AS owning_tab, "
4552 "NULL::int4 AS owning_col, "
4553 "NULL AS reltablespace, "
4554 "NULL AS reloptions, "
4555 "NULL AS toast_reloptions "
4557 "WHERE relkind IN ('%c', '%c', '%c') "
4560 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4565 * Before 7.1, view relkind was not set to 'v', so we must check if we
4566 * have a view by looking for a rule in pg_rewrite.
4568 appendPQExpBuffer(query,
4570 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4571 "oid, relname, relacl, "
4572 "CASE WHEN relhasrules and relkind = 'r' "
4573 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4574 " r.ev_class = c.oid AND r.ev_type = '1') "
4575 "THEN '%c'::\"char\" "
4576 "ELSE relkind END AS relkind,"
4577 "0::oid AS relnamespace, "
4578 "(%s relowner) AS rolname, "
4579 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4580 "relhasindex, relhasrules, "
4581 "'t'::bool AS relhasoids, "
4582 "0 as relfrozenxid, "
4585 "'p' AS relpersistence, 't'::bool as isscannable, "
4587 "NULL AS reloftype, "
4588 "NULL::oid AS owning_tab, "
4589 "NULL::int4 AS owning_col, "
4590 "NULL AS reltablespace, "
4591 "NULL AS reloptions, "
4592 "NULL AS toast_reloptions "
4594 "WHERE relkind IN ('%c', '%c') "
4598 RELKIND_RELATION, RELKIND_SEQUENCE);
4601 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4603 ntups = PQntuples(res);
4608 * Extract data from result and lock dumpable tables. We do the locking
4609 * before anything else, to minimize the window wherein a table could
4610 * disappear under us.
4612 * Note that we have to save info about all tables here, even when dumping
4613 * only one, because we don't yet know which tables might be inheritance
4614 * ancestors of the target table.
4616 tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
4618 i_reltableoid = PQfnumber(res, "tableoid");
4619 i_reloid = PQfnumber(res, "oid");
4620 i_relname = PQfnumber(res, "relname");
4621 i_relnamespace = PQfnumber(res, "relnamespace");
4622 i_relacl = PQfnumber(res, "relacl");
4623 i_relkind = PQfnumber(res, "relkind");
4624 i_rolname = PQfnumber(res, "rolname");
4625 i_relchecks = PQfnumber(res, "relchecks");
4626 i_relhastriggers = PQfnumber(res, "relhastriggers");
4627 i_relhasindex = PQfnumber(res, "relhasindex");
4628 i_relhasrules = PQfnumber(res, "relhasrules");
4629 i_relhasoids = PQfnumber(res, "relhasoids");
4630 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4631 i_toastoid = PQfnumber(res, "toid");
4632 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4633 i_relpersistence = PQfnumber(res, "relpersistence");
4634 i_isscannable = PQfnumber(res, "isscannable");
4635 i_relpages = PQfnumber(res, "relpages");
4636 i_owning_tab = PQfnumber(res, "owning_tab");
4637 i_owning_col = PQfnumber(res, "owning_col");
4638 i_reltablespace = PQfnumber(res, "reltablespace");
4639 i_reloptions = PQfnumber(res, "reloptions");
4640 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4641 i_reloftype = PQfnumber(res, "reloftype");
4643 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4646 * Arrange to fail instead of waiting forever for a table lock.
4648 * NB: this coding assumes that the only queries issued within the
4649 * following loop are LOCK TABLEs; else the timeout may be undesirably
4650 * applied to other things too.
4652 resetPQExpBuffer(query);
4653 appendPQExpBuffer(query, "SET statement_timeout = ");
4654 appendStringLiteralConn(query, lockWaitTimeout, GetConnection(fout));
4655 ExecuteSqlStatement(fout, query->data);
4658 for (i = 0; i < ntups; i++)
4660 tblinfo[i].dobj.objType = DO_TABLE;
4661 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4662 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4663 AssignDumpId(&tblinfo[i].dobj);
4664 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4665 tblinfo[i].dobj.namespace =
4667 atooid(PQgetvalue(res, i, i_relnamespace)),
4668 tblinfo[i].dobj.catId.oid);
4669 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4670 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4671 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4672 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4673 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4674 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4675 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4676 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4677 tblinfo[i].isscannable = (strcmp(PQgetvalue(res, i, i_isscannable), "t") == 0);
4678 tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
4679 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4680 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4681 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4682 if (PQgetisnull(res, i, i_reloftype))
4683 tblinfo[i].reloftype = NULL;
4685 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4686 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4687 if (PQgetisnull(res, i, i_owning_tab))
4689 tblinfo[i].owning_tab = InvalidOid;
4690 tblinfo[i].owning_col = 0;
4694 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4695 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4697 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4698 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4699 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4701 /* other fields were zeroed above */
4704 * Decide whether we want to dump this table.
4706 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4707 tblinfo[i].dobj.dump = false;
4709 selectDumpableTable(&tblinfo[i]);
4710 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4713 * Read-lock target tables to make sure they aren't DROPPED or altered
4714 * in schema before we get around to dumping them.
4716 * Note that we don't explicitly lock parents of the target tables; we
4717 * assume our lock on the child is enough to prevent schema
4718 * alterations to parent tables.
4720 * NOTE: it'd be kinda nice to lock other relations too, not only
4721 * plain tables, but the backend doesn't presently allow that.
4723 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4725 resetPQExpBuffer(query);
4726 appendPQExpBuffer(query,
4727 "LOCK TABLE %s IN ACCESS SHARE MODE",
4728 fmtQualifiedId(fout->remoteVersion,
4729 tblinfo[i].dobj.namespace->dobj.name,
4730 tblinfo[i].dobj.name));
4731 ExecuteSqlStatement(fout, query->data);
4734 /* Emit notice if join for owner failed */
4735 if (strlen(tblinfo[i].rolname) == 0)
4736 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4737 tblinfo[i].dobj.name);
4740 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4742 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4747 destroyPQExpBuffer(query);
4754 * identify owned sequences and mark them as dumpable if owning table is
4756 * We used to do this in getTables(), but it's better to do it after the
4757 * index used by findTableByOid() has been set up.
4760 getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
4765 * Force sequences that are "owned" by table columns to be dumped whenever
4766 * their owning table is being dumped.
4768 for (i = 0; i < numTables; i++)
4770 TableInfo *seqinfo = &tblinfo[i];
4771 TableInfo *owning_tab;
4773 if (!OidIsValid(seqinfo->owning_tab))
4774 continue; /* not an owned sequence */
4775 if (seqinfo->dobj.dump)
4776 continue; /* no need to search */
4777 owning_tab = findTableByOid(seqinfo->owning_tab);
4778 if (owning_tab && owning_tab->dobj.dump)
4780 seqinfo->interesting = true;
4781 seqinfo->dobj.dump = true;
4788 * read all the inheritance information
4789 * from the system catalogs return them in the InhInfo* structure
4791 * numInherits is set to the number of pairs read in
4794 getInherits(Archive *fout, int *numInherits)
4799 PQExpBuffer query = createPQExpBuffer();
4805 /* Make sure we are in proper schema */
4806 selectSourceSchema(fout, "pg_catalog");
4808 /* find all the inheritance information */
4810 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4812 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4814 ntups = PQntuples(res);
4816 *numInherits = ntups;
4818 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4820 i_inhrelid = PQfnumber(res, "inhrelid");
4821 i_inhparent = PQfnumber(res, "inhparent");
4823 for (i = 0; i < ntups; i++)
4825 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4826 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4831 destroyPQExpBuffer(query);
4838 * get information about every index on a dumpable table
4840 * Note: index data is not returned directly to the caller, but it
4841 * does get entered into the DumpableObject tables.
4844 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4848 PQExpBuffer query = createPQExpBuffer();
4851 ConstraintInfo *constrinfo;
4871 for (i = 0; i < numTables; i++)
4873 TableInfo *tbinfo = &tblinfo[i];
4875 /* Only plain tables and materialized views have indexes. */
4876 if (tbinfo->relkind != RELKIND_RELATION &&
4877 tbinfo->relkind != RELKIND_MATVIEW)
4879 if (!tbinfo->hasindex)
4882 /* Ignore indexes of tables not to be dumped */
4883 if (!tbinfo->dobj.dump)
4887 write_msg(NULL, "reading indexes for table \"%s\"\n",
4890 /* Make sure we are in proper schema so indexdef is right */
4891 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4894 * The point of the messy-looking outer join is to find a constraint
4895 * that is related by an internal dependency link to the index. If we
4896 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4897 * assume an index won't have more than one internal dependency.
4899 * As of 9.0 we don't need to look at pg_depend but can check for a
4900 * match to pg_constraint.conindid. The check on conrelid is
4901 * redundant but useful because that column is indexed while conindid
4904 resetPQExpBuffer(query);
4905 if (fout->remoteVersion >= 90000)
4908 * the test on indisready is necessary in 9.2, and harmless in
4909 * earlier/later versions
4911 appendPQExpBuffer(query,
4912 "SELECT t.tableoid, t.oid, "
4913 "t.relname AS indexname, "
4914 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4915 "t.relnatts AS indnkeys, "
4916 "i.indkey, i.indisclustered, "
4918 "c.contype, c.conname, "
4919 "c.condeferrable, c.condeferred, "
4920 "c.tableoid AS contableoid, "
4922 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4923 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4924 "array_to_string(t.reloptions, ', ') AS options "
4925 "FROM pg_catalog.pg_index i "
4926 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4927 "LEFT JOIN pg_catalog.pg_constraint c "
4928 "ON (i.indrelid = c.conrelid AND "
4929 "i.indexrelid = c.conindid AND "
4930 "c.contype IN ('p','u','x')) "
4931 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4932 "AND i.indisvalid AND i.indisready "
4933 "ORDER BY indexname",
4934 tbinfo->dobj.catId.oid);
4936 else if (fout->remoteVersion >= 80200)
4938 appendPQExpBuffer(query,
4939 "SELECT t.tableoid, t.oid, "
4940 "t.relname AS indexname, "
4941 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4942 "t.relnatts AS indnkeys, "
4943 "i.indkey, i.indisclustered, "
4945 "c.contype, c.conname, "
4946 "c.condeferrable, c.condeferred, "
4947 "c.tableoid AS contableoid, "
4950 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4951 "array_to_string(t.reloptions, ', ') AS options "
4952 "FROM pg_catalog.pg_index i "
4953 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4954 "LEFT JOIN pg_catalog.pg_depend d "
4955 "ON (d.classid = t.tableoid "
4956 "AND d.objid = t.oid "
4957 "AND d.deptype = 'i') "
4958 "LEFT JOIN pg_catalog.pg_constraint c "
4959 "ON (d.refclassid = c.tableoid "
4960 "AND d.refobjid = c.oid) "
4961 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4963 "ORDER BY indexname",
4964 tbinfo->dobj.catId.oid);
4966 else if (fout->remoteVersion >= 80000)
4968 appendPQExpBuffer(query,
4969 "SELECT t.tableoid, t.oid, "
4970 "t.relname AS indexname, "
4971 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4972 "t.relnatts AS indnkeys, "
4973 "i.indkey, i.indisclustered, "
4975 "c.contype, c.conname, "
4976 "c.condeferrable, c.condeferred, "
4977 "c.tableoid AS contableoid, "
4980 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4982 "FROM pg_catalog.pg_index i "
4983 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4984 "LEFT JOIN pg_catalog.pg_depend d "
4985 "ON (d.classid = t.tableoid "
4986 "AND d.objid = t.oid "
4987 "AND d.deptype = 'i') "
4988 "LEFT JOIN pg_catalog.pg_constraint c "
4989 "ON (d.refclassid = c.tableoid "
4990 "AND d.refobjid = c.oid) "
4991 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4992 "ORDER BY indexname",
4993 tbinfo->dobj.catId.oid);
4995 else if (fout->remoteVersion >= 70300)
4997 appendPQExpBuffer(query,
4998 "SELECT t.tableoid, t.oid, "
4999 "t.relname AS indexname, "
5000 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
5001 "t.relnatts AS indnkeys, "
5002 "i.indkey, i.indisclustered, "
5004 "c.contype, c.conname, "
5005 "c.condeferrable, c.condeferred, "
5006 "c.tableoid AS contableoid, "
5009 "NULL AS tablespace, "
5011 "FROM pg_catalog.pg_index i "
5012 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
5013 "LEFT JOIN pg_catalog.pg_depend d "
5014 "ON (d.classid = t.tableoid "
5015 "AND d.objid = t.oid "
5016 "AND d.deptype = 'i') "
5017 "LEFT JOIN pg_catalog.pg_constraint c "
5018 "ON (d.refclassid = c.tableoid "
5019 "AND d.refobjid = c.oid) "
5020 "WHERE i.indrelid = '%u'::pg_catalog.oid "
5021 "ORDER BY indexname",
5022 tbinfo->dobj.catId.oid);
5024 else if (fout->remoteVersion >= 70100)
5026 appendPQExpBuffer(query,
5027 "SELECT t.tableoid, t.oid, "
5028 "t.relname AS indexname, "
5029 "pg_get_indexdef(i.indexrelid) AS indexdef, "
5030 "t.relnatts AS indnkeys, "
5031 "i.indkey, false AS indisclustered, "
5033 "CASE WHEN i.indisprimary THEN 'p'::char "
5034 "ELSE '0'::char END AS contype, "
5035 "t.relname AS conname, "
5036 "false AS condeferrable, "
5037 "false AS condeferred, "
5038 "0::oid AS contableoid, "
5041 "NULL AS tablespace, "
5043 "FROM pg_index i, pg_class t "
5044 "WHERE t.oid = i.indexrelid "
5045 "AND i.indrelid = '%u'::oid "
5046 "ORDER BY indexname",
5047 tbinfo->dobj.catId.oid);
5051 appendPQExpBuffer(query,
5053 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
5055 "t.relname AS indexname, "
5056 "pg_get_indexdef(i.indexrelid) AS indexdef, "
5057 "t.relnatts AS indnkeys, "
5058 "i.indkey, false AS indisclustered, "
5060 "CASE WHEN i.indisprimary THEN 'p'::char "
5061 "ELSE '0'::char END AS contype, "
5062 "t.relname AS conname, "
5063 "false AS condeferrable, "
5064 "false AS condeferred, "
5065 "0::oid AS contableoid, "
5068 "NULL AS tablespace, "
5070 "FROM pg_index i, pg_class t "
5071 "WHERE t.oid = i.indexrelid "
5072 "AND i.indrelid = '%u'::oid "
5073 "ORDER BY indexname",
5074 tbinfo->dobj.catId.oid);
5077 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5079 ntups = PQntuples(res);
5081 i_tableoid = PQfnumber(res, "tableoid");
5082 i_oid = PQfnumber(res, "oid");
5083 i_indexname = PQfnumber(res, "indexname");
5084 i_indexdef = PQfnumber(res, "indexdef");
5085 i_indnkeys = PQfnumber(res, "indnkeys");
5086 i_indkey = PQfnumber(res, "indkey");
5087 i_indisclustered = PQfnumber(res, "indisclustered");
5088 i_relpages = PQfnumber(res, "relpages");
5089 i_contype = PQfnumber(res, "contype");
5090 i_conname = PQfnumber(res, "conname");
5091 i_condeferrable = PQfnumber(res, "condeferrable");
5092 i_condeferred = PQfnumber(res, "condeferred");
5093 i_contableoid = PQfnumber(res, "contableoid");
5094 i_conoid = PQfnumber(res, "conoid");
5095 i_condef = PQfnumber(res, "condef");
5096 i_tablespace = PQfnumber(res, "tablespace");
5097 i_options = PQfnumber(res, "options");
5099 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
5100 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5102 for (j = 0; j < ntups; j++)
5106 indxinfo[j].dobj.objType = DO_INDEX;
5107 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5108 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5109 AssignDumpId(&indxinfo[j].dobj);
5110 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
5111 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5112 indxinfo[j].indextable = tbinfo;
5113 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
5114 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
5115 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
5116 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
5119 * In pre-7.4 releases, indkeys may contain more entries than
5120 * indnkeys says (since indnkeys will be 1 for a functional
5121 * index). We don't actually care about this case since we don't
5122 * examine indkeys except for indexes associated with PRIMARY and
5123 * UNIQUE constraints, which are never functional indexes. But we
5124 * have to allocate enough space to keep parseOidArray from
5127 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
5128 parseOidArray(PQgetvalue(res, j, i_indkey),
5129 indxinfo[j].indkeys, INDEX_MAX_KEYS);
5130 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
5131 indxinfo[j].relpages = atoi(PQgetvalue(res, j, i_relpages));
5132 contype = *(PQgetvalue(res, j, i_contype));
5134 if (contype == 'p' || contype == 'u' || contype == 'x')
5137 * If we found a constraint matching the index, create an
5140 * In a pre-7.3 database, we take this path iff the index was
5141 * marked indisprimary.
5143 constrinfo[j].dobj.objType = DO_CONSTRAINT;
5144 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5145 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5146 AssignDumpId(&constrinfo[j].dobj);
5147 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5148 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5149 constrinfo[j].contable = tbinfo;
5150 constrinfo[j].condomain = NULL;
5151 constrinfo[j].contype = contype;
5153 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5155 constrinfo[j].condef = NULL;
5156 constrinfo[j].confrelid = InvalidOid;
5157 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
5158 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
5159 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
5160 constrinfo[j].conislocal = true;
5161 constrinfo[j].separate = true;
5163 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
5165 /* If pre-7.3 DB, better make sure table comes first */
5166 addObjectDependency(&constrinfo[j].dobj,
5167 tbinfo->dobj.dumpId);
5171 /* Plain secondary index */
5172 indxinfo[j].indexconstraint = 0;
5179 destroyPQExpBuffer(query);
5185 * Get info about constraints on dumpable tables.
5187 * Currently handles foreign keys only.
5188 * Unique and primary key constraints are handled with indexes,
5189 * while check constraints are processed in getTableAttrs().
5192 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
5196 ConstraintInfo *constrinfo;
5206 /* pg_constraint was created in 7.3, so nothing to do if older */
5207 if (fout->remoteVersion < 70300)
5210 query = createPQExpBuffer();
5212 for (i = 0; i < numTables; i++)
5214 TableInfo *tbinfo = &tblinfo[i];
5216 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5220 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
5224 * select table schema to ensure constraint expr is qualified if
5227 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5229 resetPQExpBuffer(query);
5230 appendPQExpBuffer(query,
5231 "SELECT tableoid, oid, conname, confrelid, "
5232 "pg_catalog.pg_get_constraintdef(oid) AS condef "
5233 "FROM pg_catalog.pg_constraint "
5234 "WHERE conrelid = '%u'::pg_catalog.oid "
5235 "AND contype = 'f'",
5236 tbinfo->dobj.catId.oid);
5237 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5239 ntups = PQntuples(res);
5241 i_contableoid = PQfnumber(res, "tableoid");
5242 i_conoid = PQfnumber(res, "oid");
5243 i_conname = PQfnumber(res, "conname");
5244 i_confrelid = PQfnumber(res, "confrelid");
5245 i_condef = PQfnumber(res, "condef");
5247 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5249 for (j = 0; j < ntups; j++)
5251 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
5252 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
5253 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
5254 AssignDumpId(&constrinfo[j].dobj);
5255 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
5256 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
5257 constrinfo[j].contable = tbinfo;
5258 constrinfo[j].condomain = NULL;
5259 constrinfo[j].contype = 'f';
5260 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
5261 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
5262 constrinfo[j].conindex = 0;
5263 constrinfo[j].condeferrable = false;
5264 constrinfo[j].condeferred = false;
5265 constrinfo[j].conislocal = true;
5266 constrinfo[j].separate = true;
5272 destroyPQExpBuffer(query);
5276 * getDomainConstraints
5278 * Get info about constraints on a domain.
5281 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
5284 ConstraintInfo *constrinfo;
5293 /* pg_constraint was created in 7.3, so nothing to do if older */
5294 if (fout->remoteVersion < 70300)
5298 * select appropriate schema to ensure names in constraint are properly
5301 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
5303 query = createPQExpBuffer();
5305 if (fout->remoteVersion >= 90100)
5306 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5307 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5309 "FROM pg_catalog.pg_constraint "
5310 "WHERE contypid = '%u'::pg_catalog.oid "
5312 tyinfo->dobj.catId.oid);
5314 else if (fout->remoteVersion >= 70400)
5315 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5316 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5317 "true as convalidated "
5318 "FROM pg_catalog.pg_constraint "
5319 "WHERE contypid = '%u'::pg_catalog.oid "
5321 tyinfo->dobj.catId.oid);
5323 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
5324 "'CHECK (' || consrc || ')' AS consrc, "
5325 "true as convalidated "
5326 "FROM pg_catalog.pg_constraint "
5327 "WHERE contypid = '%u'::pg_catalog.oid "
5329 tyinfo->dobj.catId.oid);
5331 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5333 ntups = PQntuples(res);
5335 i_tableoid = PQfnumber(res, "tableoid");
5336 i_oid = PQfnumber(res, "oid");
5337 i_conname = PQfnumber(res, "conname");
5338 i_consrc = PQfnumber(res, "consrc");
5340 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5342 tyinfo->nDomChecks = ntups;
5343 tyinfo->domChecks = constrinfo;
5345 for (i = 0; i < ntups; i++)
5347 bool validated = PQgetvalue(res, i, 4)[0] == 't';
5349 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5350 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5351 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5352 AssignDumpId(&constrinfo[i].dobj);
5353 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5354 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5355 constrinfo[i].contable = NULL;
5356 constrinfo[i].condomain = tyinfo;
5357 constrinfo[i].contype = 'c';
5358 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5359 constrinfo[i].confrelid = InvalidOid;
5360 constrinfo[i].conindex = 0;
5361 constrinfo[i].condeferrable = false;
5362 constrinfo[i].condeferred = false;
5363 constrinfo[i].conislocal = true;
5365 constrinfo[i].separate = !validated;
5368 * Make the domain depend on the constraint, ensuring it won't be
5369 * output till any constraint dependencies are OK. If the constraint
5370 * has not been validated, it's going to be dumped after the domain
5371 * anyway, so this doesn't matter.
5374 addObjectDependency(&tyinfo->dobj,
5375 constrinfo[i].dobj.dumpId);
5380 destroyPQExpBuffer(query);
5385 * get basic information about every rule in the system
5387 * numRules is set to the number of rules read in
5390 getRules(Archive *fout, int *numRules)
5395 PQExpBuffer query = createPQExpBuffer();
5405 /* Make sure we are in proper schema */
5406 selectSourceSchema(fout, "pg_catalog");
5408 if (fout->remoteVersion >= 80300)
5410 appendPQExpBuffer(query, "SELECT "
5411 "tableoid, oid, rulename, "
5412 "ev_class AS ruletable, ev_type, is_instead, "
5417 else if (fout->remoteVersion >= 70100)
5419 appendPQExpBuffer(query, "SELECT "
5420 "tableoid, oid, rulename, "
5421 "ev_class AS ruletable, ev_type, is_instead, "
5422 "'O'::char AS ev_enabled "
5428 appendPQExpBuffer(query, "SELECT "
5429 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5431 "ev_class AS ruletable, ev_type, is_instead, "
5432 "'O'::char AS ev_enabled "
5437 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5439 ntups = PQntuples(res);
5443 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5445 i_tableoid = PQfnumber(res, "tableoid");
5446 i_oid = PQfnumber(res, "oid");
5447 i_rulename = PQfnumber(res, "rulename");
5448 i_ruletable = PQfnumber(res, "ruletable");
5449 i_ev_type = PQfnumber(res, "ev_type");
5450 i_is_instead = PQfnumber(res, "is_instead");
5451 i_ev_enabled = PQfnumber(res, "ev_enabled");
5453 for (i = 0; i < ntups; i++)
5457 ruleinfo[i].dobj.objType = DO_RULE;
5458 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5459 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5460 AssignDumpId(&ruleinfo[i].dobj);
5461 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5462 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5463 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5464 if (ruleinfo[i].ruletable == NULL)
5465 exit_horribly(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5466 ruletableoid, ruleinfo[i].dobj.catId.oid);
5467 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5468 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5469 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5470 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5471 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5472 if (ruleinfo[i].ruletable)
5475 * If the table is a view or materialized view, force its ON
5476 * SELECT rule to be sorted before the view itself --- this
5477 * ensures that any dependencies for the rule affect the table's
5478 * positioning. Other rules are forced to appear after their
5481 if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
5482 ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
5483 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5485 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5486 ruleinfo[i].dobj.dumpId);
5487 /* We'll merge the rule into CREATE VIEW, if possible */
5488 ruleinfo[i].separate = false;
5492 addObjectDependency(&ruleinfo[i].dobj,
5493 ruleinfo[i].ruletable->dobj.dumpId);
5494 ruleinfo[i].separate = true;
5498 ruleinfo[i].separate = true;
5501 * If we're forced to break a dependency loop by dumping a view as a
5502 * table and separate _RETURN rule, we'll move the view's reloptions
5503 * to the rule. (This is necessary because tables and views have
5504 * different valid reloptions, so we can't apply the options until the
5505 * backend knows it's a view.) Otherwise the rule's reloptions stay
5508 ruleinfo[i].reloptions = NULL;
5513 destroyPQExpBuffer(query);
5520 * get information about every trigger on a dumpable table
5522 * Note: trigger data is not returned directly to the caller, but it
5523 * does get entered into the DumpableObject tables.
5526 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5530 PQExpBuffer query = createPQExpBuffer();
5532 TriggerInfo *tginfo;
5550 for (i = 0; i < numTables; i++)
5552 TableInfo *tbinfo = &tblinfo[i];
5554 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5558 write_msg(NULL, "reading triggers for table \"%s\"\n",
5562 * select table schema to ensure regproc name is qualified if needed
5564 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5566 resetPQExpBuffer(query);
5567 if (fout->remoteVersion >= 90000)
5570 * NB: think not to use pretty=true in pg_get_triggerdef. It
5571 * could result in non-forward-compatible dumps of WHEN clauses
5572 * due to under-parenthesization.
5574 appendPQExpBuffer(query,
5576 "tgfoid::pg_catalog.regproc AS tgfname, "
5577 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5578 "tgenabled, tableoid, oid "
5579 "FROM pg_catalog.pg_trigger t "
5580 "WHERE tgrelid = '%u'::pg_catalog.oid "
5581 "AND NOT tgisinternal",
5582 tbinfo->dobj.catId.oid);
5584 else if (fout->remoteVersion >= 80300)
5587 * We ignore triggers that are tied to a foreign-key constraint
5589 appendPQExpBuffer(query,
5591 "tgfoid::pg_catalog.regproc AS tgfname, "
5592 "tgtype, tgnargs, tgargs, tgenabled, "
5593 "tgisconstraint, tgconstrname, tgdeferrable, "
5594 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5595 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5596 "FROM pg_catalog.pg_trigger t "
5597 "WHERE tgrelid = '%u'::pg_catalog.oid "
5598 "AND tgconstraint = 0",
5599 tbinfo->dobj.catId.oid);
5601 else if (fout->remoteVersion >= 70300)
5604 * We ignore triggers that are tied to a foreign-key constraint,
5605 * but in these versions we have to grovel through pg_constraint
5608 appendPQExpBuffer(query,
5610 "tgfoid::pg_catalog.regproc AS tgfname, "
5611 "tgtype, tgnargs, tgargs, tgenabled, "
5612 "tgisconstraint, tgconstrname, tgdeferrable, "
5613 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5614 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5615 "FROM pg_catalog.pg_trigger t "
5616 "WHERE tgrelid = '%u'::pg_catalog.oid "
5617 "AND (NOT tgisconstraint "
5619 " (SELECT 1 FROM pg_catalog.pg_depend d "
5620 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5621 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5622 tbinfo->dobj.catId.oid);
5624 else if (fout->remoteVersion >= 70100)
5626 appendPQExpBuffer(query,
5627 "SELECT tgname, tgfoid::regproc AS tgfname, "
5628 "tgtype, tgnargs, tgargs, tgenabled, "
5629 "tgisconstraint, tgconstrname, tgdeferrable, "
5630 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5631 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5632 " AS tgconstrrelname "
5634 "WHERE tgrelid = '%u'::oid",
5635 tbinfo->dobj.catId.oid);
5639 appendPQExpBuffer(query,
5640 "SELECT tgname, tgfoid::regproc AS tgfname, "
5641 "tgtype, tgnargs, tgargs, tgenabled, "
5642 "tgisconstraint, tgconstrname, tgdeferrable, "
5643 "tgconstrrelid, tginitdeferred, "
5644 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5646 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5647 " AS tgconstrrelname "
5649 "WHERE tgrelid = '%u'::oid",
5650 tbinfo->dobj.catId.oid);
5652 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5654 ntups = PQntuples(res);
5656 i_tableoid = PQfnumber(res, "tableoid");
5657 i_oid = PQfnumber(res, "oid");
5658 i_tgname = PQfnumber(res, "tgname");
5659 i_tgfname = PQfnumber(res, "tgfname");
5660 i_tgtype = PQfnumber(res, "tgtype");
5661 i_tgnargs = PQfnumber(res, "tgnargs");
5662 i_tgargs = PQfnumber(res, "tgargs");
5663 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5664 i_tgconstrname = PQfnumber(res, "tgconstrname");
5665 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5666 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5667 i_tgenabled = PQfnumber(res, "tgenabled");
5668 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5669 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5670 i_tgdef = PQfnumber(res, "tgdef");
5672 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5674 for (j = 0; j < ntups; j++)
5676 tginfo[j].dobj.objType = DO_TRIGGER;
5677 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5678 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5679 AssignDumpId(&tginfo[j].dobj);
5680 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5681 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5682 tginfo[j].tgtable = tbinfo;
5683 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5686 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5688 /* remaining fields are not valid if we have tgdef */
5689 tginfo[j].tgfname = NULL;
5690 tginfo[j].tgtype = 0;
5691 tginfo[j].tgnargs = 0;
5692 tginfo[j].tgargs = NULL;
5693 tginfo[j].tgisconstraint = false;
5694 tginfo[j].tgdeferrable = false;
5695 tginfo[j].tginitdeferred = false;
5696 tginfo[j].tgconstrname = NULL;
5697 tginfo[j].tgconstrrelid = InvalidOid;
5698 tginfo[j].tgconstrrelname = NULL;
5702 tginfo[j].tgdef = NULL;
5704 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5705 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5706 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5707 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5708 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5709 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5710 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5712 if (tginfo[j].tgisconstraint)
5714 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5715 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5716 if (OidIsValid(tginfo[j].tgconstrrelid))
5718 if (PQgetisnull(res, j, i_tgconstrrelname))
5719 exit_horribly(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5720 tginfo[j].dobj.name,
5722 tginfo[j].tgconstrrelid);
5723 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5726 tginfo[j].tgconstrrelname = NULL;
5730 tginfo[j].tgconstrname = NULL;
5731 tginfo[j].tgconstrrelid = InvalidOid;
5732 tginfo[j].tgconstrrelname = NULL;
5740 destroyPQExpBuffer(query);
5745 * get information about event triggers
5748 getEventTriggers(Archive *fout, int *numEventTriggers)
5751 PQExpBuffer query = createPQExpBuffer();
5753 EventTriggerInfo *evtinfo;
5764 /* Before 9.3, there are no event triggers */
5765 if (fout->remoteVersion < 90300)
5767 *numEventTriggers = 0;
5771 /* Make sure we are in proper schema */
5772 selectSourceSchema(fout, "pg_catalog");
5774 appendPQExpBuffer(query,
5775 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
5776 "evtevent, (%s evtowner) AS evtowner, "
5777 "array_to_string(array("
5778 "select quote_literal(x) "
5779 " from unnest(evttags) as t(x)), ', ') as evttags, "
5780 "e.evtfoid::regproc as evtfname "
5781 "FROM pg_event_trigger e "
5785 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5787 ntups = PQntuples(res);
5789 *numEventTriggers = ntups;
5791 evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
5793 i_tableoid = PQfnumber(res, "tableoid");
5794 i_oid = PQfnumber(res, "oid");
5795 i_evtname = PQfnumber(res, "evtname");
5796 i_evtevent = PQfnumber(res, "evtevent");
5797 i_evtowner = PQfnumber(res, "evtowner");
5798 i_evttags = PQfnumber(res, "evttags");
5799 i_evtfname = PQfnumber(res, "evtfname");
5800 i_evtenabled = PQfnumber(res, "evtenabled");
5802 for (i = 0; i < ntups; i++)
5804 evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
5805 evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5806 evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5807 AssignDumpId(&evtinfo[i].dobj);
5808 evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
5809 evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
5810 evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
5811 evtinfo[i].evtowner = pg_strdup(PQgetvalue(res, i, i_evtowner));
5812 evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
5813 evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
5814 evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
5819 destroyPQExpBuffer(query);
5826 * get basic information about every procedural language in the system
5828 * numProcLangs is set to the number of langs read in
5830 * NB: this must run after getFuncs() because we assume we can do
5834 getProcLangs(Archive *fout, int *numProcLangs)
5839 PQExpBuffer query = createPQExpBuffer();
5840 ProcLangInfo *planginfo;
5845 int i_lanplcallfoid;
5851 /* Make sure we are in proper schema */
5852 selectSourceSchema(fout, "pg_catalog");
5854 if (fout->remoteVersion >= 90000)
5856 /* pg_language has a laninline column */
5857 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5858 "lanname, lanpltrusted, lanplcallfoid, "
5859 "laninline, lanvalidator, lanacl, "
5860 "(%s lanowner) AS lanowner "
5866 else if (fout->remoteVersion >= 80300)
5868 /* pg_language has a lanowner column */
5869 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5870 "lanname, lanpltrusted, lanplcallfoid, "
5871 "lanvalidator, lanacl, "
5872 "(%s lanowner) AS lanowner "
5878 else if (fout->remoteVersion >= 80100)
5880 /* Languages are owned by the bootstrap superuser, OID 10 */
5881 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5882 "(%s '10') AS lanowner "
5888 else if (fout->remoteVersion >= 70400)
5890 /* Languages are owned by the bootstrap superuser, sysid 1 */
5891 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5892 "(%s '1') AS lanowner "
5898 else if (fout->remoteVersion >= 70100)
5900 /* No clear notion of an owner at all before 7.4 ... */
5901 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5907 appendPQExpBuffer(query, "SELECT "
5908 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5909 "oid, * FROM pg_language "
5914 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5916 ntups = PQntuples(res);
5918 *numProcLangs = ntups;
5920 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5922 i_tableoid = PQfnumber(res, "tableoid");
5923 i_oid = PQfnumber(res, "oid");
5924 i_lanname = PQfnumber(res, "lanname");
5925 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5926 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5927 /* these may fail and return -1: */
5928 i_laninline = PQfnumber(res, "laninline");
5929 i_lanvalidator = PQfnumber(res, "lanvalidator");
5930 i_lanacl = PQfnumber(res, "lanacl");
5931 i_lanowner = PQfnumber(res, "lanowner");
5933 for (i = 0; i < ntups; i++)
5935 planginfo[i].dobj.objType = DO_PROCLANG;
5936 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5937 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5938 AssignDumpId(&planginfo[i].dobj);
5940 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5941 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5942 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5943 if (i_laninline >= 0)
5944 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5946 planginfo[i].laninline = InvalidOid;
5947 if (i_lanvalidator >= 0)
5948 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5950 planginfo[i].lanvalidator = InvalidOid;
5952 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5954 planginfo[i].lanacl = pg_strdup("{=U}");
5955 if (i_lanowner >= 0)
5956 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5958 planginfo[i].lanowner = pg_strdup("");
5960 if (fout->remoteVersion < 70300)
5963 * We need to make a dependency to ensure the function will be
5964 * dumped first. (In 7.3 and later the regular dependency
5965 * mechanism will handle this for us.)
5967 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5970 addObjectDependency(&planginfo[i].dobj,
5971 funcInfo->dobj.dumpId);
5977 destroyPQExpBuffer(query);
5984 * get basic information about every cast in the system
5986 * numCasts is set to the number of casts read in
5989 getCasts(Archive *fout, int *numCasts)
5994 PQExpBuffer query = createPQExpBuffer();
6004 /* Make sure we are in proper schema */
6005 selectSourceSchema(fout, "pg_catalog");
6007 if (fout->remoteVersion >= 80400)
6009 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6010 "castsource, casttarget, castfunc, castcontext, "
6012 "FROM pg_cast ORDER BY 3,4");
6014 else if (fout->remoteVersion >= 70300)
6016 appendPQExpBuffer(query, "SELECT tableoid, oid, "
6017 "castsource, casttarget, castfunc, castcontext, "
6018 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
6019 "FROM pg_cast ORDER BY 3,4");
6023 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
6024 "t1.oid AS castsource, t2.oid AS casttarget, "
6025 "p.oid AS castfunc, 'e' AS castcontext, "
6026 "'f' AS castmethod "
6027 "FROM pg_type t1, pg_type t2, pg_proc p "
6028 "WHERE p.pronargs = 1 AND "
6029 "p.proargtypes[0] = t1.oid AND "
6030 "p.prorettype = t2.oid AND p.proname = t2.typname "
6034 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6036 ntups = PQntuples(res);
6040 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
6042 i_tableoid = PQfnumber(res, "tableoid");
6043 i_oid = PQfnumber(res, "oid");
6044 i_castsource = PQfnumber(res, "castsource");
6045 i_casttarget = PQfnumber(res, "casttarget");
6046 i_castfunc = PQfnumber(res, "castfunc");
6047 i_castcontext = PQfnumber(res, "castcontext");
6048 i_castmethod = PQfnumber(res, "castmethod");
6050 for (i = 0; i < ntups; i++)
6052 PQExpBufferData namebuf;
6053 TypeInfo *sTypeInfo;
6054 TypeInfo *tTypeInfo;
6056 castinfo[i].dobj.objType = DO_CAST;
6057 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6058 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6059 AssignDumpId(&castinfo[i].dobj);
6060 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
6061 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
6062 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
6063 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
6064 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
6067 * Try to name cast as concatenation of typnames. This is only used
6068 * for purposes of sorting. If we fail to find either type, the name
6069 * will be an empty string.
6071 initPQExpBuffer(&namebuf);
6072 sTypeInfo = findTypeByOid(castinfo[i].castsource);
6073 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
6074 if (sTypeInfo && tTypeInfo)
6075 appendPQExpBuffer(&namebuf, "%s %s",
6076 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
6077 castinfo[i].dobj.name = namebuf.data;
6079 if (OidIsValid(castinfo[i].castfunc))
6082 * We need to make a dependency to ensure the function will be
6083 * dumped first. (In 7.3 and later the regular dependency
6084 * mechanism will handle this for us.)
6088 funcInfo = findFuncByOid(castinfo[i].castfunc);
6090 addObjectDependency(&castinfo[i].dobj,
6091 funcInfo->dobj.dumpId);
6097 destroyPQExpBuffer(query);
6104 * for each interesting table, read info about its attributes
6105 * (names, types, default values, CHECK constraints, etc)
6107 * This is implemented in a very inefficient way right now, looping
6108 * through the tblinfo and doing a join per table to find the attrs and their
6109 * types. However, because we want type names and so forth to be named
6110 * relative to the schema of each table, we couldn't do it in just one
6111 * query. (Maybe one query per schema?)
6116 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
6120 PQExpBuffer q = createPQExpBuffer();
6125 int i_attstattarget;
6136 int i_attfdwoptions;
6141 for (i = 0; i < numTables; i++)
6143 TableInfo *tbinfo = &tblinfo[i];
6145 /* Don't bother to collect info for sequences */
6146 if (tbinfo->relkind == RELKIND_SEQUENCE)
6149 /* Don't bother with uninteresting tables, either */
6150 if (!tbinfo->interesting)
6154 * Make sure we are in proper schema for this table; this allows
6155 * correct retrieval of formatted type names and default exprs
6157 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
6159 /* find all the user attributes and their types */
6162 * we must read the attribute names in attribute number order! because
6163 * we will use the attnum to index into the attnames array later. We
6164 * actually ask to order by "attrelid, attnum" because (at least up to
6165 * 7.3) the planner is not smart enough to realize it needn't re-sort
6166 * the output of an indexscan on pg_attribute_relid_attnum_index.
6169 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
6172 resetPQExpBuffer(q);
6174 if (fout->remoteVersion >= 90200)
6177 * attfdwoptions is new in 9.2.
6179 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6180 "a.attstattarget, a.attstorage, t.typstorage, "
6181 "a.attnotnull, a.atthasdef, a.attisdropped, "
6182 "a.attlen, a.attalign, a.attislocal, "
6183 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6184 "array_to_string(a.attoptions, ', ') AS attoptions, "
6185 "CASE WHEN a.attcollation <> t.typcollation "
6186 "THEN a.attcollation ELSE 0 END AS attcollation, "
6187 "pg_catalog.array_to_string(ARRAY("
6188 "SELECT pg_catalog.quote_ident(option_name) || "
6189 "' ' || pg_catalog.quote_literal(option_value) "
6190 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
6191 "ORDER BY option_name"
6192 "), E',\n ') AS attfdwoptions "
6193 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6194 "ON a.atttypid = t.oid "
6195 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6196 "AND a.attnum > 0::pg_catalog.int2 "
6197 "ORDER BY a.attrelid, a.attnum",
6198 tbinfo->dobj.catId.oid);
6200 else if (fout->remoteVersion >= 90100)
6203 * attcollation is new in 9.1. Since we only want to dump COLLATE
6204 * clauses for attributes whose collation is different from their
6205 * type's default, we use a CASE here to suppress uninteresting
6206 * attcollations cheaply.
6208 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6209 "a.attstattarget, a.attstorage, t.typstorage, "
6210 "a.attnotnull, a.atthasdef, a.attisdropped, "
6211 "a.attlen, a.attalign, a.attislocal, "
6212 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6213 "array_to_string(a.attoptions, ', ') AS attoptions, "
6214 "CASE WHEN a.attcollation <> t.typcollation "
6215 "THEN a.attcollation ELSE 0 END AS attcollation, "
6216 "NULL AS attfdwoptions "
6217 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6218 "ON a.atttypid = t.oid "
6219 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6220 "AND a.attnum > 0::pg_catalog.int2 "
6221 "ORDER BY a.attrelid, a.attnum",
6222 tbinfo->dobj.catId.oid);
6224 else if (fout->remoteVersion >= 90000)
6226 /* attoptions is new in 9.0 */
6227 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6228 "a.attstattarget, a.attstorage, t.typstorage, "
6229 "a.attnotnull, a.atthasdef, a.attisdropped, "
6230 "a.attlen, a.attalign, a.attislocal, "
6231 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6232 "array_to_string(a.attoptions, ', ') AS attoptions, "
6233 "0 AS attcollation, "
6234 "NULL AS attfdwoptions "
6235 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6236 "ON a.atttypid = t.oid "
6237 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6238 "AND a.attnum > 0::pg_catalog.int2 "
6239 "ORDER BY a.attrelid, a.attnum",
6240 tbinfo->dobj.catId.oid);
6242 else if (fout->remoteVersion >= 70300)
6244 /* need left join here to not fail on dropped columns ... */
6245 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6246 "a.attstattarget, a.attstorage, t.typstorage, "
6247 "a.attnotnull, a.atthasdef, a.attisdropped, "
6248 "a.attlen, a.attalign, a.attislocal, "
6249 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
6250 "'' AS attoptions, 0 AS attcollation, "
6251 "NULL AS attfdwoptions "
6252 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
6253 "ON a.atttypid = t.oid "
6254 "WHERE a.attrelid = '%u'::pg_catalog.oid "
6255 "AND a.attnum > 0::pg_catalog.int2 "
6256 "ORDER BY a.attrelid, a.attnum",
6257 tbinfo->dobj.catId.oid);
6259 else if (fout->remoteVersion >= 70100)
6262 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
6263 * we don't dump it because we can't tell whether it's been
6264 * explicitly set or was just a default.
6266 * attislocal doesn't exist before 7.3, either; in older databases
6267 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
6269 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
6270 "-1 AS attstattarget, a.attstorage, "
6271 "t.typstorage, a.attnotnull, a.atthasdef, "
6272 "false AS attisdropped, a.attlen, "
6273 "a.attalign, true AS attislocal, "
6274 "format_type(t.oid,a.atttypmod) AS atttypname, "
6275 "'' AS attoptions, 0 AS attcollation, "
6276 "NULL AS attfdwoptions "
6277 "FROM pg_attribute a LEFT JOIN pg_type t "
6278 "ON a.atttypid = t.oid "
6279 "WHERE a.attrelid = '%u'::oid "
6280 "AND a.attnum > 0::int2 "
6281 "ORDER BY a.attrelid, a.attnum",
6282 tbinfo->dobj.catId.oid);
6286 /* format_type not available before 7.1 */
6287 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
6288 "-1 AS attstattarget, "
6289 "attstorage, attstorage AS typstorage, "
6290 "attnotnull, atthasdef, false AS attisdropped, "
6291 "attlen, attalign, "
6292 "true AS attislocal, "
6293 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
6294 "'' AS attoptions, 0 AS attcollation, "
6295 "NULL AS attfdwoptions "
6296 "FROM pg_attribute a "
6297 "WHERE attrelid = '%u'::oid "
6298 "AND attnum > 0::int2 "
6299 "ORDER BY attrelid, attnum",
6300 tbinfo->dobj.catId.oid);
6303 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6305 ntups = PQntuples(res);
6307 i_attnum = PQfnumber(res, "attnum");
6308 i_attname = PQfnumber(res, "attname");
6309 i_atttypname = PQfnumber(res, "atttypname");
6310 i_atttypmod = PQfnumber(res, "atttypmod");
6311 i_attstattarget = PQfnumber(res, "attstattarget");
6312 i_attstorage = PQfnumber(res, "attstorage");
6313 i_typstorage = PQfnumber(res, "typstorage");
6314 i_attnotnull = PQfnumber(res, "attnotnull");
6315 i_atthasdef = PQfnumber(res, "atthasdef");
6316 i_attisdropped = PQfnumber(res, "attisdropped");
6317 i_attlen = PQfnumber(res, "attlen");
6318 i_attalign = PQfnumber(res, "attalign");
6319 i_attislocal = PQfnumber(res, "attislocal");
6320 i_attoptions = PQfnumber(res, "attoptions");
6321 i_attcollation = PQfnumber(res, "attcollation");
6322 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
6324 tbinfo->numatts = ntups;
6325 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
6326 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
6327 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
6328 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
6329 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
6330 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
6331 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
6332 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
6333 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
6334 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
6335 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
6336 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
6337 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
6338 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
6339 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
6340 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
6341 hasdefaults = false;
6343 for (j = 0; j < ntups; j++)
6345 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
6347 "invalid column numbering in table \"%s\"\n",
6349 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
6350 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
6351 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
6352 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
6353 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
6354 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
6355 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
6356 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
6357 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
6358 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
6359 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
6360 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
6361 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
6362 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
6363 tbinfo->attrdefs[j] = NULL; /* fix below */
6364 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
6366 /* these flags will be set in flagInhAttrs() */
6367 tbinfo->inhNotNull[j] = false;
6373 * Get info about column defaults
6377 AttrDefInfo *attrdefs;
6381 write_msg(NULL, "finding default expressions of table \"%s\"\n",
6384 resetPQExpBuffer(q);
6385 if (fout->remoteVersion >= 70300)
6387 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
6388 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
6389 "FROM pg_catalog.pg_attrdef "
6390 "WHERE adrelid = '%u'::pg_catalog.oid",
6391 tbinfo->dobj.catId.oid);
6393 else if (fout->remoteVersion >= 70200)
6395 /* 7.2 did not have OIDs in pg_attrdef */
6396 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
6397 "pg_get_expr(adbin, adrelid) AS adsrc "
6399 "WHERE adrelid = '%u'::oid",
6400 tbinfo->dobj.catId.oid);
6402 else if (fout->remoteVersion >= 70100)
6404 /* no pg_get_expr, so must rely on adsrc */
6405 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
6407 "WHERE adrelid = '%u'::oid",
6408 tbinfo->dobj.catId.oid);
6412 /* no pg_get_expr, no tableoid either */
6413 appendPQExpBuffer(q, "SELECT "
6414 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
6415 "oid, adnum, adsrc "
6417 "WHERE adrelid = '%u'::oid",
6418 tbinfo->dobj.catId.oid);
6420 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6422 numDefaults = PQntuples(res);
6423 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
6425 for (j = 0; j < numDefaults; j++)
6429 adnum = atoi(PQgetvalue(res, j, 2));
6431 if (adnum <= 0 || adnum > ntups)
6433 "invalid adnum value %d for table \"%s\"\n",
6434 adnum, tbinfo->dobj.name);
6437 * dropped columns shouldn't have defaults, but just in case,
6440 if (tbinfo->attisdropped[adnum - 1])
6443 attrdefs[j].dobj.objType = DO_ATTRDEF;
6444 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6445 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6446 AssignDumpId(&attrdefs[j].dobj);
6447 attrdefs[j].adtable = tbinfo;
6448 attrdefs[j].adnum = adnum;
6449 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6451 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6452 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6454 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6457 * Defaults on a VIEW must always be dumped as separate ALTER
6458 * TABLE commands. Defaults on regular tables are dumped as
6459 * part of the CREATE TABLE if possible, which it won't be if
6460 * the column is not going to be emitted explicitly.
6462 if (tbinfo->relkind == RELKIND_VIEW)
6464 attrdefs[j].separate = true;
6465 /* needed in case pre-7.3 DB: */
6466 addObjectDependency(&attrdefs[j].dobj,
6467 tbinfo->dobj.dumpId);
6469 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6471 /* column will be suppressed, print default separately */
6472 attrdefs[j].separate = true;
6473 /* needed in case pre-7.3 DB: */
6474 addObjectDependency(&attrdefs[j].dobj,
6475 tbinfo->dobj.dumpId);
6479 attrdefs[j].separate = false;
6482 * Mark the default as needing to appear before the table,
6483 * so that any dependencies it has must be emitted before
6484 * the CREATE TABLE. If this is not possible, we'll
6485 * change to "separate" mode while sorting dependencies.
6487 addObjectDependency(&tbinfo->dobj,
6488 attrdefs[j].dobj.dumpId);
6491 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6497 * Get info about table CHECK constraints
6499 if (tbinfo->ncheck > 0)
6501 ConstraintInfo *constrs;
6505 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6508 resetPQExpBuffer(q);
6509 if (fout->remoteVersion >= 90200)
6512 * convalidated is new in 9.2 (actually, it is there in 9.1,
6513 * but it wasn't ever false for check constraints until 9.2).
6515 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6516 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6517 "conislocal, convalidated "
6518 "FROM pg_catalog.pg_constraint "
6519 "WHERE conrelid = '%u'::pg_catalog.oid "
6520 " AND contype = 'c' "
6522 tbinfo->dobj.catId.oid);
6524 else if (fout->remoteVersion >= 80400)
6526 /* conislocal is new in 8.4 */
6527 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6528 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6529 "conislocal, true AS convalidated "
6530 "FROM pg_catalog.pg_constraint "
6531 "WHERE conrelid = '%u'::pg_catalog.oid "
6532 " AND contype = 'c' "
6534 tbinfo->dobj.catId.oid);
6536 else if (fout->remoteVersion >= 70400)
6538 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6539 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6540 "true AS conislocal, true AS convalidated "
6541 "FROM pg_catalog.pg_constraint "
6542 "WHERE conrelid = '%u'::pg_catalog.oid "
6543 " AND contype = 'c' "
6545 tbinfo->dobj.catId.oid);
6547 else if (fout->remoteVersion >= 70300)
6549 /* no pg_get_constraintdef, must use consrc */
6550 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6551 "'CHECK (' || consrc || ')' AS consrc, "
6552 "true AS conislocal, true AS convalidated "
6553 "FROM pg_catalog.pg_constraint "
6554 "WHERE conrelid = '%u'::pg_catalog.oid "
6555 " AND contype = 'c' "
6557 tbinfo->dobj.catId.oid);
6559 else if (fout->remoteVersion >= 70200)
6561 /* 7.2 did not have OIDs in pg_relcheck */
6562 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6563 "rcname AS conname, "
6564 "'CHECK (' || rcsrc || ')' AS consrc, "
6565 "true AS conislocal, true AS convalidated "
6567 "WHERE rcrelid = '%u'::oid "
6569 tbinfo->dobj.catId.oid);
6571 else if (fout->remoteVersion >= 70100)
6573 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6574 "rcname AS conname, "
6575 "'CHECK (' || rcsrc || ')' AS consrc, "
6576 "true AS conislocal, true AS convalidated "
6578 "WHERE rcrelid = '%u'::oid "
6580 tbinfo->dobj.catId.oid);
6584 /* no tableoid in 7.0 */
6585 appendPQExpBuffer(q, "SELECT "
6586 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6587 "oid, rcname AS conname, "
6588 "'CHECK (' || rcsrc || ')' AS consrc, "
6589 "true AS conislocal, true AS convalidated "
6591 "WHERE rcrelid = '%u'::oid "
6593 tbinfo->dobj.catId.oid);
6595 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6597 numConstrs = PQntuples(res);
6598 if (numConstrs != tbinfo->ncheck)
6600 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6601 "expected %d check constraints on table \"%s\" but found %d\n",
6603 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6604 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6608 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6609 tbinfo->checkexprs = constrs;
6611 for (j = 0; j < numConstrs; j++)
6613 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6615 constrs[j].dobj.objType = DO_CONSTRAINT;
6616 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6617 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6618 AssignDumpId(&constrs[j].dobj);
6619 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6620 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6621 constrs[j].contable = tbinfo;
6622 constrs[j].condomain = NULL;
6623 constrs[j].contype = 'c';
6624 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6625 constrs[j].confrelid = InvalidOid;
6626 constrs[j].conindex = 0;
6627 constrs[j].condeferrable = false;
6628 constrs[j].condeferred = false;
6629 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6632 * An unvalidated constraint needs to be dumped separately, so
6633 * that potentially-violating existing data is loaded before
6636 constrs[j].separate = !validated;
6638 constrs[j].dobj.dump = tbinfo->dobj.dump;
6641 * Mark the constraint as needing to appear before the table
6642 * --- this is so that any other dependencies of the
6643 * constraint will be emitted before we try to create the
6644 * table. If the constraint is to be dumped separately, it
6645 * will be dumped after data is loaded anyway, so don't do it.
6646 * (There's an automatic dependency in the opposite direction
6647 * anyway, so don't need to add one manually here.)
6649 if (!constrs[j].separate)
6650 addObjectDependency(&tbinfo->dobj,
6651 constrs[j].dobj.dumpId);
6654 * If the constraint is inherited, this will be detected later
6655 * (in pre-8.4 databases). We also detect later if the
6656 * constraint must be split out from the table definition.
6663 destroyPQExpBuffer(q);
6667 * Test whether a column should be printed as part of table's CREATE TABLE.
6668 * Column number is zero-based.
6670 * Normally this is always true, but it's false for dropped columns, as well
6671 * as those that were inherited without any local definition. (If we print
6672 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6673 * However, in binary_upgrade mode, we must print all such columns anyway and
6674 * fix the attislocal/attisdropped state later, so as to keep control of the
6675 * physical column order.
6677 * This function exists because there are scattered nonobvious places that
6678 * must be kept in sync with this decision.
6681 shouldPrintColumn(TableInfo *tbinfo, int colno)
6685 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6691 * read all text search parsers in the system catalogs and return them
6692 * in the TSParserInfo* structure
6694 * numTSParsers is set to the number of parsers read in
6697 getTSParsers(Archive *fout, int *numTSParsers)
6703 TSParserInfo *prsinfo;
6714 /* Before 8.3, there is no built-in text search support */
6715 if (fout->remoteVersion < 80300)
6721 query = createPQExpBuffer();
6724 * find all text search objects, including builtin ones; we filter out
6725 * system-defined objects at dump-out time.
6728 /* Make sure we are in proper schema */
6729 selectSourceSchema(fout, "pg_catalog");
6731 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6732 "prsstart::oid, prstoken::oid, "
6733 "prsend::oid, prsheadline::oid, prslextype::oid "
6734 "FROM pg_ts_parser");
6736 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6738 ntups = PQntuples(res);
6739 *numTSParsers = ntups;
6741 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6743 i_tableoid = PQfnumber(res, "tableoid");
6744 i_oid = PQfnumber(res, "oid");
6745 i_prsname = PQfnumber(res, "prsname");
6746 i_prsnamespace = PQfnumber(res, "prsnamespace");
6747 i_prsstart = PQfnumber(res, "prsstart");
6748 i_prstoken = PQfnumber(res, "prstoken");
6749 i_prsend = PQfnumber(res, "prsend");
6750 i_prsheadline = PQfnumber(res, "prsheadline");
6751 i_prslextype = PQfnumber(res, "prslextype");
6753 for (i = 0; i < ntups; i++)
6755 prsinfo[i].dobj.objType = DO_TSPARSER;
6756 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6757 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6758 AssignDumpId(&prsinfo[i].dobj);
6759 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6760 prsinfo[i].dobj.namespace =
6762 atooid(PQgetvalue(res, i, i_prsnamespace)),
6763 prsinfo[i].dobj.catId.oid);
6764 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6765 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6766 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6767 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6768 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6770 /* Decide whether we want to dump it */
6771 selectDumpableObject(&(prsinfo[i].dobj));
6776 destroyPQExpBuffer(query);
6782 * getTSDictionaries:
6783 * read all text search dictionaries in the system catalogs and return them
6784 * in the TSDictInfo* structure
6786 * numTSDicts is set to the number of dictionaries read in
6789 getTSDictionaries(Archive *fout, int *numTSDicts)
6795 TSDictInfo *dictinfo;
6799 int i_dictnamespace;
6802 int i_dictinitoption;
6804 /* Before 8.3, there is no built-in text search support */
6805 if (fout->remoteVersion < 80300)
6811 query = createPQExpBuffer();
6813 /* Make sure we are in proper schema */
6814 selectSourceSchema(fout, "pg_catalog");
6816 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6817 "dictnamespace, (%s dictowner) AS rolname, "
6818 "dicttemplate, dictinitoption "
6822 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6824 ntups = PQntuples(res);
6825 *numTSDicts = ntups;
6827 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6829 i_tableoid = PQfnumber(res, "tableoid");
6830 i_oid = PQfnumber(res, "oid");
6831 i_dictname = PQfnumber(res, "dictname");
6832 i_dictnamespace = PQfnumber(res, "dictnamespace");
6833 i_rolname = PQfnumber(res, "rolname");
6834 i_dictinitoption = PQfnumber(res, "dictinitoption");
6835 i_dicttemplate = PQfnumber(res, "dicttemplate");
6837 for (i = 0; i < ntups; i++)
6839 dictinfo[i].dobj.objType = DO_TSDICT;
6840 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6841 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6842 AssignDumpId(&dictinfo[i].dobj);
6843 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6844 dictinfo[i].dobj.namespace =
6846 atooid(PQgetvalue(res, i, i_dictnamespace)),
6847 dictinfo[i].dobj.catId.oid);
6848 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6849 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6850 if (PQgetisnull(res, i, i_dictinitoption))
6851 dictinfo[i].dictinitoption = NULL;
6853 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6855 /* Decide whether we want to dump it */
6856 selectDumpableObject(&(dictinfo[i].dobj));
6861 destroyPQExpBuffer(query);
6868 * read all text search templates in the system catalogs and return them
6869 * in the TSTemplateInfo* structure
6871 * numTSTemplates is set to the number of templates read in
6874 getTSTemplates(Archive *fout, int *numTSTemplates)
6880 TSTemplateInfo *tmplinfo;
6884 int i_tmplnamespace;
6888 /* Before 8.3, there is no built-in text search support */
6889 if (fout->remoteVersion < 80300)
6891 *numTSTemplates = 0;
6895 query = createPQExpBuffer();
6897 /* Make sure we are in proper schema */
6898 selectSourceSchema(fout, "pg_catalog");
6900 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6901 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6902 "FROM pg_ts_template");
6904 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6906 ntups = PQntuples(res);
6907 *numTSTemplates = ntups;
6909 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6911 i_tableoid = PQfnumber(res, "tableoid");
6912 i_oid = PQfnumber(res, "oid");
6913 i_tmplname = PQfnumber(res, "tmplname");
6914 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6915 i_tmplinit = PQfnumber(res, "tmplinit");
6916 i_tmpllexize = PQfnumber(res, "tmpllexize");
6918 for (i = 0; i < ntups; i++)
6920 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6921 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6922 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6923 AssignDumpId(&tmplinfo[i].dobj);
6924 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6925 tmplinfo[i].dobj.namespace =
6927 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6928 tmplinfo[i].dobj.catId.oid);
6929 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6930 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6932 /* Decide whether we want to dump it */
6933 selectDumpableObject(&(tmplinfo[i].dobj));
6938 destroyPQExpBuffer(query);
6944 * getTSConfigurations:
6945 * read all text search configurations in the system catalogs and return
6946 * them in the TSConfigInfo* structure
6948 * numTSConfigs is set to the number of configurations read in
6951 getTSConfigurations(Archive *fout, int *numTSConfigs)
6957 TSConfigInfo *cfginfo;
6965 /* Before 8.3, there is no built-in text search support */
6966 if (fout->remoteVersion < 80300)
6972 query = createPQExpBuffer();
6974 /* Make sure we are in proper schema */
6975 selectSourceSchema(fout, "pg_catalog");
6977 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6978 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6979 "FROM pg_ts_config",
6982 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6984 ntups = PQntuples(res);
6985 *numTSConfigs = ntups;
6987 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6989 i_tableoid = PQfnumber(res, "tableoid");
6990 i_oid = PQfnumber(res, "oid");
6991 i_cfgname = PQfnumber(res, "cfgname");
6992 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6993 i_rolname = PQfnumber(res, "rolname");
6994 i_cfgparser = PQfnumber(res, "cfgparser");
6996 for (i = 0; i < ntups; i++)
6998 cfginfo[i].dobj.objType = DO_TSCONFIG;
6999 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7000 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7001 AssignDumpId(&cfginfo[i].dobj);
7002 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
7003 cfginfo[i].dobj.namespace =
7005 atooid(PQgetvalue(res, i, i_cfgnamespace)),
7006 cfginfo[i].dobj.catId.oid);
7007 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7008 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
7010 /* Decide whether we want to dump it */
7011 selectDumpableObject(&(cfginfo[i].dobj));
7016 destroyPQExpBuffer(query);
7022 * getForeignDataWrappers:
7023 * read all foreign-data wrappers in the system catalogs and return
7024 * them in the FdwInfo* structure
7026 * numForeignDataWrappers is set to the number of fdws read in
7029 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
7034 PQExpBuffer query = createPQExpBuffer();
7045 /* Before 8.4, there are no foreign-data wrappers */
7046 if (fout->remoteVersion < 80400)
7048 *numForeignDataWrappers = 0;
7052 /* Make sure we are in proper schema */
7053 selectSourceSchema(fout, "pg_catalog");
7055 if (fout->remoteVersion >= 90100)
7057 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7058 "(%s fdwowner) AS rolname, "
7059 "fdwhandler::pg_catalog.regproc, "
7060 "fdwvalidator::pg_catalog.regproc, fdwacl, "
7061 "array_to_string(ARRAY("
7062 "SELECT quote_ident(option_name) || ' ' || "
7063 "quote_literal(option_value) "
7064 "FROM pg_options_to_table(fdwoptions) "
7065 "ORDER BY option_name"
7066 "), E',\n ') AS fdwoptions "
7067 "FROM pg_foreign_data_wrapper",
7072 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
7073 "(%s fdwowner) AS rolname, "
7074 "'-' AS fdwhandler, "
7075 "fdwvalidator::pg_catalog.regproc, fdwacl, "
7076 "array_to_string(ARRAY("
7077 "SELECT quote_ident(option_name) || ' ' || "
7078 "quote_literal(option_value) "
7079 "FROM pg_options_to_table(fdwoptions) "
7080 "ORDER BY option_name"
7081 "), E',\n ') AS fdwoptions "
7082 "FROM pg_foreign_data_wrapper",
7086 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7088 ntups = PQntuples(res);
7089 *numForeignDataWrappers = ntups;
7091 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
7093 i_tableoid = PQfnumber(res, "tableoid");
7094 i_oid = PQfnumber(res, "oid");
7095 i_fdwname = PQfnumber(res, "fdwname");
7096 i_rolname = PQfnumber(res, "rolname");
7097 i_fdwhandler = PQfnumber(res, "fdwhandler");
7098 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
7099 i_fdwacl = PQfnumber(res, "fdwacl");
7100 i_fdwoptions = PQfnumber(res, "fdwoptions");
7102 for (i = 0; i < ntups; i++)
7104 fdwinfo[i].dobj.objType = DO_FDW;
7105 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7106 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7107 AssignDumpId(&fdwinfo[i].dobj);
7108 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
7109 fdwinfo[i].dobj.namespace = NULL;
7110 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7111 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
7112 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
7113 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
7114 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
7116 /* Decide whether we want to dump it */
7117 selectDumpableObject(&(fdwinfo[i].dobj));
7122 destroyPQExpBuffer(query);
7128 * getForeignServers:
7129 * read all foreign servers in the system catalogs and return
7130 * them in the ForeignServerInfo * structure
7132 * numForeignServers is set to the number of servers read in
7135 getForeignServers(Archive *fout, int *numForeignServers)
7140 PQExpBuffer query = createPQExpBuffer();
7141 ForeignServerInfo *srvinfo;
7152 /* Before 8.4, there are no foreign servers */
7153 if (fout->remoteVersion < 80400)
7155 *numForeignServers = 0;
7159 /* Make sure we are in proper schema */
7160 selectSourceSchema(fout, "pg_catalog");
7162 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
7163 "(%s srvowner) AS rolname, "
7164 "srvfdw, srvtype, srvversion, srvacl,"
7165 "array_to_string(ARRAY("
7166 "SELECT quote_ident(option_name) || ' ' || "
7167 "quote_literal(option_value) "
7168 "FROM pg_options_to_table(srvoptions) "
7169 "ORDER BY option_name"
7170 "), E',\n ') AS srvoptions "
7171 "FROM pg_foreign_server",
7174 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7176 ntups = PQntuples(res);
7177 *numForeignServers = ntups;
7179 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
7181 i_tableoid = PQfnumber(res, "tableoid");
7182 i_oid = PQfnumber(res, "oid");
7183 i_srvname = PQfnumber(res, "srvname");
7184 i_rolname = PQfnumber(res, "rolname");
7185 i_srvfdw = PQfnumber(res, "srvfdw");
7186 i_srvtype = PQfnumber(res, "srvtype");
7187 i_srvversion = PQfnumber(res, "srvversion");
7188 i_srvacl = PQfnumber(res, "srvacl");
7189 i_srvoptions = PQfnumber(res, "srvoptions");
7191 for (i = 0; i < ntups; i++)
7193 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
7194 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7195 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7196 AssignDumpId(&srvinfo[i].dobj);
7197 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
7198 srvinfo[i].dobj.namespace = NULL;
7199 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
7200 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
7201 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
7202 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
7203 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
7204 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
7206 /* Decide whether we want to dump it */
7207 selectDumpableObject(&(srvinfo[i].dobj));
7212 destroyPQExpBuffer(query);
7219 * read all default ACL information in the system catalogs and return
7220 * them in the DefaultACLInfo structure
7222 * numDefaultACLs is set to the number of ACLs read in
7225 getDefaultACLs(Archive *fout, int *numDefaultACLs)
7227 DefaultACLInfo *daclinfo;
7233 int i_defaclnamespace;
7234 int i_defaclobjtype;
7239 if (fout->remoteVersion < 90000)
7241 *numDefaultACLs = 0;
7245 query = createPQExpBuffer();
7247 /* Make sure we are in proper schema */
7248 selectSourceSchema(fout, "pg_catalog");
7250 appendPQExpBuffer(query, "SELECT oid, tableoid, "
7251 "(%s defaclrole) AS defaclrole, "
7255 "FROM pg_default_acl",
7258 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7260 ntups = PQntuples(res);
7261 *numDefaultACLs = ntups;
7263 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
7265 i_oid = PQfnumber(res, "oid");
7266 i_tableoid = PQfnumber(res, "tableoid");
7267 i_defaclrole = PQfnumber(res, "defaclrole");
7268 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
7269 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
7270 i_defaclacl = PQfnumber(res, "defaclacl");
7272 for (i = 0; i < ntups; i++)
7274 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
7276 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
7277 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7278 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7279 AssignDumpId(&daclinfo[i].dobj);
7280 /* cheesy ... is it worth coming up with a better object name? */
7281 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
7283 if (nspid != InvalidOid)
7284 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
7285 daclinfo[i].dobj.catId.oid);
7287 daclinfo[i].dobj.namespace = NULL;
7289 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
7290 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
7291 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
7293 /* Decide whether we want to dump it */
7294 selectDumpableDefaultACL(&(daclinfo[i]));
7299 destroyPQExpBuffer(query);
7307 * This routine is used to dump any comments associated with the
7308 * object handed to this routine. The routine takes a constant character
7309 * string for the target part of the comment-creation command, plus
7310 * the namespace and owner of the object (for labeling the ArchiveEntry),
7311 * plus catalog ID and subid which are the lookup key for pg_description,
7312 * plus the dump ID for the object (for setting a dependency).
7313 * If a matching pg_description entry is found, it is dumped.
7315 * Note: although this routine takes a dumpId for dependency purposes,
7316 * that purpose is just to mark the dependency in the emitted dump file
7317 * for possible future use by pg_restore. We do NOT use it for determining
7318 * ordering of the comment in the dump file, because this routine is called
7319 * after dependency sorting occurs. This routine should be called just after
7320 * calling ArchiveEntry() for the specified object.
7323 dumpComment(Archive *fout, const char *target,
7324 const char *namespace, const char *owner,
7325 CatalogId catalogId, int subid, DumpId dumpId)
7327 CommentItem *comments;
7330 /* Comments are schema not data ... except blob comments are data */
7331 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
7342 /* Search for comments associated with catalogId, using table */
7343 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
7346 /* Is there one matching the subid? */
7347 while (ncomments > 0)
7349 if (comments->objsubid == subid)
7355 /* If a comment exists, build COMMENT ON statement */
7358 PQExpBuffer query = createPQExpBuffer();
7360 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
7361 appendStringLiteralAH(query, comments->descr, fout);
7362 appendPQExpBuffer(query, ";\n");
7365 * We mark comments as SECTION_NONE because they really belong in the
7366 * same section as their parent, whether that is pre-data or
7369 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7370 target, namespace, NULL, owner,
7371 false, "COMMENT", SECTION_NONE,
7372 query->data, "", NULL,
7376 destroyPQExpBuffer(query);
7381 * dumpTableComment --
7383 * As above, but dump comments for both the specified table (or view)
7387 dumpTableComment(Archive *fout, TableInfo *tbinfo,
7388 const char *reltypename)
7390 CommentItem *comments;
7395 /* Comments are SCHEMA not data */
7399 /* Search for comments associated with relation, using table */
7400 ncomments = findComments(fout,
7401 tbinfo->dobj.catId.tableoid,
7402 tbinfo->dobj.catId.oid,
7405 /* If comments exist, build COMMENT ON statements */
7409 query = createPQExpBuffer();
7410 target = createPQExpBuffer();
7412 while (ncomments > 0)
7414 const char *descr = comments->descr;
7415 int objsubid = comments->objsubid;
7419 resetPQExpBuffer(target);
7420 appendPQExpBuffer(target, "%s %s", reltypename,
7421 fmtId(tbinfo->dobj.name));
7423 resetPQExpBuffer(query);
7424 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7425 appendStringLiteralAH(query, descr, fout);
7426 appendPQExpBuffer(query, ";\n");
7428 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7430 tbinfo->dobj.namespace->dobj.name,
7431 NULL, tbinfo->rolname,
7432 false, "COMMENT", SECTION_NONE,
7433 query->data, "", NULL,
7434 &(tbinfo->dobj.dumpId), 1,
7437 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7439 resetPQExpBuffer(target);
7440 appendPQExpBuffer(target, "COLUMN %s.",
7441 fmtId(tbinfo->dobj.name));
7442 appendPQExpBuffer(target, "%s",
7443 fmtId(tbinfo->attnames[objsubid - 1]));
7445 resetPQExpBuffer(query);
7446 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7447 appendStringLiteralAH(query, descr, fout);
7448 appendPQExpBuffer(query, ";\n");
7450 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7452 tbinfo->dobj.namespace->dobj.name,
7453 NULL, tbinfo->rolname,
7454 false, "COMMENT", SECTION_NONE,
7455 query->data, "", NULL,
7456 &(tbinfo->dobj.dumpId), 1,
7464 destroyPQExpBuffer(query);
7465 destroyPQExpBuffer(target);
7471 * Find the comment(s), if any, associated with the given object. All the
7472 * objsubid values associated with the given classoid/objoid are found with
7476 findComments(Archive *fout, Oid classoid, Oid objoid,
7477 CommentItem **items)
7479 /* static storage for table of comments */
7480 static CommentItem *comments = NULL;
7481 static int ncomments = -1;
7483 CommentItem *middle = NULL;
7488 /* Get comments if we didn't already */
7490 ncomments = collectComments(fout, &comments);
7493 * Pre-7.2, pg_description does not contain classoid, so collectComments
7494 * just stores a zero. If there's a collision on object OID, well, you
7495 * get duplicate comments.
7497 if (fout->remoteVersion < 70200)
7501 * Do binary search to find some item matching the object.
7504 high = &comments[ncomments - 1];
7507 middle = low + (high - low) / 2;
7509 if (classoid < middle->classoid)
7511 else if (classoid > middle->classoid)
7513 else if (objoid < middle->objoid)
7515 else if (objoid > middle->objoid)
7518 break; /* found a match */
7521 if (low > high) /* no matches */
7528 * Now determine how many items match the object. The search loop
7529 * invariant still holds: only items between low and high inclusive could
7533 while (middle > low)
7535 if (classoid != middle[-1].classoid ||
7536 objoid != middle[-1].objoid)
7545 while (middle <= high)
7547 if (classoid != middle->classoid ||
7548 objoid != middle->objoid)
7558 * collectComments --
7560 * Construct a table of all comments available for database objects.
7561 * We used to do per-object queries for the comments, but it's much faster
7562 * to pull them all over at once, and on most databases the memory cost
7565 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7568 collectComments(Archive *fout, CommentItem **items)
7578 CommentItem *comments;
7581 * Note we do NOT change source schema here; preserve the caller's
7585 query = createPQExpBuffer();
7587 if (fout->remoteVersion >= 70300)
7589 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7590 "FROM pg_catalog.pg_description "
7591 "ORDER BY classoid, objoid, objsubid");
7593 else if (fout->remoteVersion >= 70200)
7595 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7596 "FROM pg_description "
7597 "ORDER BY classoid, objoid, objsubid");
7601 /* Note: this will fail to find attribute comments in pre-7.2... */
7602 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7603 "FROM pg_description "
7607 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7609 /* Construct lookup table containing OIDs in numeric form */
7611 i_description = PQfnumber(res, "description");
7612 i_classoid = PQfnumber(res, "classoid");
7613 i_objoid = PQfnumber(res, "objoid");
7614 i_objsubid = PQfnumber(res, "objsubid");
7616 ntups = PQntuples(res);
7618 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7620 for (i = 0; i < ntups; i++)
7622 comments[i].descr = PQgetvalue(res, i, i_description);
7623 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7624 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7625 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7628 /* Do NOT free the PGresult since we are keeping pointers into it */
7629 destroyPQExpBuffer(query);
7636 * dumpDumpableObject
7638 * This routine and its subsidiaries are responsible for creating
7639 * ArchiveEntries (TOC objects) for each object to be dumped.
7642 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7644 switch (dobj->objType)
7647 dumpNamespace(fout, (NamespaceInfo *) dobj);
7650 dumpExtension(fout, (ExtensionInfo *) dobj);
7653 dumpType(fout, (TypeInfo *) dobj);
7656 dumpShellType(fout, (ShellTypeInfo *) dobj);
7659 dumpFunc(fout, (FuncInfo *) dobj);
7662 dumpAgg(fout, (AggInfo *) dobj);
7665 dumpOpr(fout, (OprInfo *) dobj);
7668 dumpOpclass(fout, (OpclassInfo *) dobj);
7671 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7674 dumpCollation(fout, (CollInfo *) dobj);
7677 dumpConversion(fout, (ConvInfo *) dobj);
7680 dumpTable(fout, (TableInfo *) dobj);
7683 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7686 dumpIndex(fout, (IndxInfo *) dobj);
7688 case DO_REFRESH_MATVIEW:
7689 refreshMatViewData(fout, (TableDataInfo *) dobj);
7692 dumpRule(fout, (RuleInfo *) dobj);
7695 dumpTrigger(fout, (TriggerInfo *) dobj);
7697 case DO_EVENT_TRIGGER:
7698 dumpEventTrigger(fout, (EventTriggerInfo *) dobj);
7701 dumpConstraint(fout, (ConstraintInfo *) dobj);
7703 case DO_FK_CONSTRAINT:
7704 dumpConstraint(fout, (ConstraintInfo *) dobj);
7707 dumpProcLang(fout, (ProcLangInfo *) dobj);
7710 dumpCast(fout, (CastInfo *) dobj);
7713 if (((TableDataInfo *) dobj)->tdtable->relkind == RELKIND_SEQUENCE)
7714 dumpSequenceData(fout, (TableDataInfo *) dobj);
7716 dumpTableData(fout, (TableDataInfo *) dobj);
7719 /* table rowtypes and array types are never dumped separately */
7722 dumpTSParser(fout, (TSParserInfo *) dobj);
7725 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7728 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7731 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7734 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7736 case DO_FOREIGN_SERVER:
7737 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7739 case DO_DEFAULT_ACL:
7740 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7743 dumpBlob(fout, (BlobInfo *) dobj);
7746 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7747 dobj->name, NULL, NULL, "",
7748 false, "BLOBS", SECTION_DATA,
7753 case DO_PRE_DATA_BOUNDARY:
7754 case DO_POST_DATA_BOUNDARY:
7755 /* never dumped, nothing to do */
7762 * writes out to fout the queries to recreate a user-defined namespace
7765 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7772 /* Skip if not to be dumped */
7773 if (!nspinfo->dobj.dump || dataOnly)
7776 /* don't dump dummy namespace from pre-7.3 source */
7777 if (strlen(nspinfo->dobj.name) == 0)
7780 q = createPQExpBuffer();
7781 delq = createPQExpBuffer();
7782 labelq = createPQExpBuffer();
7784 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7786 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7788 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7790 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7793 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7795 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7799 false, "SCHEMA", SECTION_PRE_DATA,
7800 q->data, delq->data, NULL,
7804 /* Dump Schema Comments and Security Labels */
7805 dumpComment(fout, labelq->data,
7806 NULL, nspinfo->rolname,
7807 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7808 dumpSecLabel(fout, labelq->data,
7809 NULL, nspinfo->rolname,
7810 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7812 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7813 qnspname, NULL, nspinfo->dobj.name, NULL,
7814 nspinfo->rolname, nspinfo->nspacl);
7818 destroyPQExpBuffer(q);
7819 destroyPQExpBuffer(delq);
7820 destroyPQExpBuffer(labelq);
7825 * writes out to fout the queries to recreate an extension
7828 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7835 /* Skip if not to be dumped */
7836 if (!extinfo->dobj.dump || dataOnly)
7839 q = createPQExpBuffer();
7840 delq = createPQExpBuffer();
7841 labelq = createPQExpBuffer();
7843 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7845 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7847 if (!binary_upgrade)
7850 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7851 * problem if the extension already exists in the target database;
7852 * this is essential for installed-by-default extensions such as
7855 * In binary-upgrade mode, that doesn't work well, so instead we skip
7856 * built-in extensions based on their OIDs; see
7857 * selectDumpableExtension.
7859 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7860 qextname, fmtId(extinfo->namespace));
7867 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7870 * We unconditionally create the extension, so we must drop it if it
7871 * exists. This could happen if the user deleted 'plpgsql' and then
7872 * readded it, causing its oid to be greater than FirstNormalObjectId.
7873 * The FirstNormalObjectId test was kept to avoid repeatedly dropping
7874 * and recreating extensions like 'plpgsql'.
7876 appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
7878 appendPQExpBuffer(q,
7879 "SELECT binary_upgrade.create_empty_extension(");
7880 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7881 appendPQExpBuffer(q, ", ");
7882 appendStringLiteralAH(q, extinfo->namespace, fout);
7883 appendPQExpBuffer(q, ", ");
7884 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7885 appendStringLiteralAH(q, extinfo->extversion, fout);
7886 appendPQExpBuffer(q, ", ");
7889 * Note that we're pushing extconfig (an OID array) back into
7890 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7891 * preserved in binary upgrade.
7893 if (strlen(extinfo->extconfig) > 2)
7894 appendStringLiteralAH(q, extinfo->extconfig, fout);
7896 appendPQExpBuffer(q, "NULL");
7897 appendPQExpBuffer(q, ", ");
7898 if (strlen(extinfo->extcondition) > 2)
7899 appendStringLiteralAH(q, extinfo->extcondition, fout);
7901 appendPQExpBuffer(q, "NULL");
7902 appendPQExpBuffer(q, ", ");
7903 appendPQExpBuffer(q, "ARRAY[");
7905 for (i = 0; i < extinfo->dobj.nDeps; i++)
7907 DumpableObject *extobj;
7909 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7910 if (extobj && extobj->objType == DO_EXTENSION)
7913 appendPQExpBuffer(q, ",");
7914 appendStringLiteralAH(q, extobj->name, fout);
7917 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7918 appendPQExpBuffer(q, ");\n");
7921 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7923 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7927 false, "EXTENSION", SECTION_PRE_DATA,
7928 q->data, delq->data, NULL,
7932 /* Dump Extension Comments and Security Labels */
7933 dumpComment(fout, labelq->data,
7935 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7936 dumpSecLabel(fout, labelq->data,
7938 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7942 destroyPQExpBuffer(q);
7943 destroyPQExpBuffer(delq);
7944 destroyPQExpBuffer(labelq);
7949 * writes out to fout the queries to recreate a user-defined type
7952 dumpType(Archive *fout, TypeInfo *tyinfo)
7954 /* Skip if not to be dumped */
7955 if (!tyinfo->dobj.dump || dataOnly)
7958 /* Dump out in proper style */
7959 if (tyinfo->typtype == TYPTYPE_BASE)
7960 dumpBaseType(fout, tyinfo);
7961 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7962 dumpDomain(fout, tyinfo);
7963 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7964 dumpCompositeType(fout, tyinfo);
7965 else if (tyinfo->typtype == TYPTYPE_ENUM)
7966 dumpEnumType(fout, tyinfo);
7967 else if (tyinfo->typtype == TYPTYPE_RANGE)
7968 dumpRangeType(fout, tyinfo);
7970 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7976 * writes out to fout the queries to recreate a user-defined enum type
7979 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7981 PQExpBuffer q = createPQExpBuffer();
7982 PQExpBuffer delq = createPQExpBuffer();
7983 PQExpBuffer labelq = createPQExpBuffer();
7984 PQExpBuffer query = createPQExpBuffer();
7992 /* Set proper schema search path */
7993 selectSourceSchema(fout, "pg_catalog");
7995 if (fout->remoteVersion >= 90100)
7996 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7997 "FROM pg_catalog.pg_enum "
7998 "WHERE enumtypid = '%u'"
7999 "ORDER BY enumsortorder",
8000 tyinfo->dobj.catId.oid);
8002 appendPQExpBuffer(query, "SELECT oid, enumlabel "
8003 "FROM pg_catalog.pg_enum "
8004 "WHERE enumtypid = '%u'"
8006 tyinfo->dobj.catId.oid);
8008 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8010 num = PQntuples(res);
8012 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8015 * DROP must be fully qualified in case same name appears in pg_catalog.
8016 * CASCADE shouldn't be required here as for normal types since the I/O
8017 * functions are generic and do not get dropped.
8019 appendPQExpBuffer(delq, "DROP TYPE %s.",
8020 fmtId(tyinfo->dobj.namespace->dobj.name));
8021 appendPQExpBuffer(delq, "%s;\n",
8025 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8026 tyinfo->dobj.catId.oid);
8028 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
8031 if (!binary_upgrade)
8033 /* Labels with server-assigned oids */
8034 for (i = 0; i < num; i++)
8036 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8038 appendPQExpBuffer(q, ",");
8039 appendPQExpBuffer(q, "\n ");
8040 appendStringLiteralAH(q, label, fout);
8044 appendPQExpBuffer(q, "\n);\n");
8048 /* Labels with dump-assigned (preserved) oids */
8049 for (i = 0; i < num; i++)
8051 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
8052 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
8055 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
8056 appendPQExpBuffer(q,
8057 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
8059 appendPQExpBuffer(q, "ALTER TYPE %s.",
8060 fmtId(tyinfo->dobj.namespace->dobj.name));
8061 appendPQExpBuffer(q, "%s ADD VALUE ",
8063 appendStringLiteralAH(q, label, fout);
8064 appendPQExpBuffer(q, ";\n\n");
8068 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8071 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8073 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8075 tyinfo->dobj.namespace->dobj.name,
8077 tyinfo->rolname, false,
8078 "TYPE", SECTION_PRE_DATA,
8079 q->data, delq->data, NULL,
8083 /* Dump Type Comments and Security Labels */
8084 dumpComment(fout, labelq->data,
8085 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8086 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8087 dumpSecLabel(fout, labelq->data,
8088 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8089 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8091 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8092 qtypname, NULL, tyinfo->dobj.name,
8093 tyinfo->dobj.namespace->dobj.name,
8094 tyinfo->rolname, tyinfo->typacl);
8097 destroyPQExpBuffer(q);
8098 destroyPQExpBuffer(delq);
8099 destroyPQExpBuffer(labelq);
8100 destroyPQExpBuffer(query);
8105 * writes out to fout the queries to recreate a user-defined range type
8108 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
8110 PQExpBuffer q = createPQExpBuffer();
8111 PQExpBuffer delq = createPQExpBuffer();
8112 PQExpBuffer labelq = createPQExpBuffer();
8113 PQExpBuffer query = createPQExpBuffer();
8120 * select appropriate schema to ensure names in CREATE are properly
8123 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8125 appendPQExpBuffer(query,
8126 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
8127 "opc.opcname AS opcname, "
8128 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
8129 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
8131 "CASE WHEN rngcollation = st.typcollation THEN 0 "
8132 " ELSE rngcollation END AS collation, "
8133 "rngcanonical, rngsubdiff "
8134 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
8135 " pg_catalog.pg_opclass opc "
8136 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
8138 tyinfo->dobj.catId.oid);
8140 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8142 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8145 * DROP must be fully qualified in case same name appears in pg_catalog.
8146 * CASCADE shouldn't be required here as for normal types since the I/O
8147 * functions are generic and do not get dropped.
8149 appendPQExpBuffer(delq, "DROP TYPE %s.",
8150 fmtId(tyinfo->dobj.namespace->dobj.name));
8151 appendPQExpBuffer(delq, "%s;\n",
8155 binary_upgrade_set_type_oids_by_type_oid(fout,
8156 q, tyinfo->dobj.catId.oid);
8158 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
8161 appendPQExpBuffer(q, "\n subtype = %s",
8162 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
8164 /* print subtype_opclass only if not default for subtype */
8165 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
8167 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
8168 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
8170 /* always schema-qualify, don't try to be smart */
8171 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
8173 appendPQExpBuffer(q, "%s", fmtId(opcname));
8176 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
8177 if (OidIsValid(collationOid))
8179 CollInfo *coll = findCollationByOid(collationOid);
8183 /* always schema-qualify, don't try to be smart */
8184 appendPQExpBuffer(q, ",\n collation = %s.",
8185 fmtId(coll->dobj.namespace->dobj.name));
8186 appendPQExpBuffer(q, "%s",
8187 fmtId(coll->dobj.name));
8191 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
8192 if (strcmp(procname, "-") != 0)
8193 appendPQExpBuffer(q, ",\n canonical = %s", procname);
8195 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
8196 if (strcmp(procname, "-") != 0)
8197 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
8199 appendPQExpBuffer(q, "\n);\n");
8201 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8204 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8206 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8208 tyinfo->dobj.namespace->dobj.name,
8210 tyinfo->rolname, false,
8211 "TYPE", SECTION_PRE_DATA,
8212 q->data, delq->data, NULL,
8216 /* Dump Type Comments and Security Labels */
8217 dumpComment(fout, labelq->data,
8218 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8219 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8220 dumpSecLabel(fout, labelq->data,
8221 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8222 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8224 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8225 qtypname, NULL, tyinfo->dobj.name,
8226 tyinfo->dobj.namespace->dobj.name,
8227 tyinfo->rolname, tyinfo->typacl);
8230 destroyPQExpBuffer(q);
8231 destroyPQExpBuffer(delq);
8232 destroyPQExpBuffer(labelq);
8233 destroyPQExpBuffer(query);
8238 * writes out to fout the queries to recreate a user-defined base type
8241 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
8243 PQExpBuffer q = createPQExpBuffer();
8244 PQExpBuffer delq = createPQExpBuffer();
8245 PQExpBuffer labelq = createPQExpBuffer();
8246 PQExpBuffer query = createPQExpBuffer();
8263 char *typispreferred;
8268 char *typcollatable;
8270 bool typdefault_is_literal = false;
8272 /* Set proper schema search path so regproc references list correctly */
8273 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8275 /* Fetch type-specific details */
8276 if (fout->remoteVersion >= 90100)
8278 appendPQExpBuffer(query, "SELECT typlen, "
8279 "typinput, typoutput, typreceive, typsend, "
8280 "typmodin, typmodout, typanalyze, "
8281 "typreceive::pg_catalog.oid AS typreceiveoid, "
8282 "typsend::pg_catalog.oid AS typsendoid, "
8283 "typmodin::pg_catalog.oid AS typmodinoid, "
8284 "typmodout::pg_catalog.oid AS typmodoutoid, "
8285 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8286 "typcategory, typispreferred, "
8287 "typdelim, typbyval, typalign, typstorage, "
8288 "(typcollation <> 0) AS typcollatable, "
8289 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8290 "FROM pg_catalog.pg_type "
8291 "WHERE oid = '%u'::pg_catalog.oid",
8292 tyinfo->dobj.catId.oid);
8294 else if (fout->remoteVersion >= 80400)
8296 appendPQExpBuffer(query, "SELECT typlen, "
8297 "typinput, typoutput, typreceive, typsend, "
8298 "typmodin, typmodout, typanalyze, "
8299 "typreceive::pg_catalog.oid AS typreceiveoid, "
8300 "typsend::pg_catalog.oid AS typsendoid, "
8301 "typmodin::pg_catalog.oid AS typmodinoid, "
8302 "typmodout::pg_catalog.oid AS typmodoutoid, "
8303 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8304 "typcategory, typispreferred, "
8305 "typdelim, typbyval, typalign, typstorage, "
8306 "false AS typcollatable, "
8307 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
8308 "FROM pg_catalog.pg_type "
8309 "WHERE oid = '%u'::pg_catalog.oid",
8310 tyinfo->dobj.catId.oid);
8312 else if (fout->remoteVersion >= 80300)
8314 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
8315 appendPQExpBuffer(query, "SELECT typlen, "
8316 "typinput, typoutput, typreceive, typsend, "
8317 "typmodin, typmodout, typanalyze, "
8318 "typreceive::pg_catalog.oid AS typreceiveoid, "
8319 "typsend::pg_catalog.oid AS typsendoid, "
8320 "typmodin::pg_catalog.oid AS typmodinoid, "
8321 "typmodout::pg_catalog.oid AS typmodoutoid, "
8322 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8323 "'U' AS typcategory, false AS typispreferred, "
8324 "typdelim, typbyval, typalign, typstorage, "
8325 "false AS typcollatable, "
8326 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8327 "FROM pg_catalog.pg_type "
8328 "WHERE oid = '%u'::pg_catalog.oid",
8329 tyinfo->dobj.catId.oid);
8331 else if (fout->remoteVersion >= 80000)
8333 appendPQExpBuffer(query, "SELECT typlen, "
8334 "typinput, typoutput, typreceive, typsend, "
8335 "'-' AS typmodin, '-' AS typmodout, "
8337 "typreceive::pg_catalog.oid AS typreceiveoid, "
8338 "typsend::pg_catalog.oid AS typsendoid, "
8339 "0 AS typmodinoid, 0 AS typmodoutoid, "
8340 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
8341 "'U' AS typcategory, false AS typispreferred, "
8342 "typdelim, typbyval, typalign, typstorage, "
8343 "false AS typcollatable, "
8344 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8345 "FROM pg_catalog.pg_type "
8346 "WHERE oid = '%u'::pg_catalog.oid",
8347 tyinfo->dobj.catId.oid);
8349 else if (fout->remoteVersion >= 70400)
8351 appendPQExpBuffer(query, "SELECT typlen, "
8352 "typinput, typoutput, typreceive, typsend, "
8353 "'-' AS typmodin, '-' AS typmodout, "
8354 "'-' AS typanalyze, "
8355 "typreceive::pg_catalog.oid AS typreceiveoid, "
8356 "typsend::pg_catalog.oid AS typsendoid, "
8357 "0 AS typmodinoid, 0 AS typmodoutoid, "
8358 "0 AS typanalyzeoid, "
8359 "'U' AS typcategory, false AS typispreferred, "
8360 "typdelim, typbyval, typalign, typstorage, "
8361 "false AS typcollatable, "
8362 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8363 "FROM pg_catalog.pg_type "
8364 "WHERE oid = '%u'::pg_catalog.oid",
8365 tyinfo->dobj.catId.oid);
8367 else if (fout->remoteVersion >= 70300)
8369 appendPQExpBuffer(query, "SELECT typlen, "
8370 "typinput, typoutput, "
8371 "'-' AS typreceive, '-' AS typsend, "
8372 "'-' AS typmodin, '-' AS typmodout, "
8373 "'-' AS typanalyze, "
8374 "0 AS typreceiveoid, 0 AS typsendoid, "
8375 "0 AS typmodinoid, 0 AS typmodoutoid, "
8376 "0 AS typanalyzeoid, "
8377 "'U' AS typcategory, false AS typispreferred, "
8378 "typdelim, typbyval, typalign, typstorage, "
8379 "false AS typcollatable, "
8380 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
8381 "FROM pg_catalog.pg_type "
8382 "WHERE oid = '%u'::pg_catalog.oid",
8383 tyinfo->dobj.catId.oid);
8385 else if (fout->remoteVersion >= 70200)
8388 * Note: although pre-7.3 catalogs contain typreceive and typsend,
8389 * ignore them because they are not right.
8391 appendPQExpBuffer(query, "SELECT typlen, "
8392 "typinput, typoutput, "
8393 "'-' AS typreceive, '-' AS typsend, "
8394 "'-' AS typmodin, '-' AS typmodout, "
8395 "'-' AS typanalyze, "
8396 "0 AS typreceiveoid, 0 AS typsendoid, "
8397 "0 AS typmodinoid, 0 AS typmodoutoid, "
8398 "0 AS typanalyzeoid, "
8399 "'U' AS typcategory, false AS typispreferred, "
8400 "typdelim, typbyval, typalign, typstorage, "
8401 "false AS typcollatable, "
8402 "NULL AS typdefaultbin, typdefault "
8404 "WHERE oid = '%u'::oid",
8405 tyinfo->dobj.catId.oid);
8407 else if (fout->remoteVersion >= 70100)
8410 * Ignore pre-7.2 typdefault; the field exists but has an unusable
8413 appendPQExpBuffer(query, "SELECT typlen, "
8414 "typinput, typoutput, "
8415 "'-' AS typreceive, '-' AS typsend, "
8416 "'-' AS typmodin, '-' AS typmodout, "
8417 "'-' AS typanalyze, "
8418 "0 AS typreceiveoid, 0 AS typsendoid, "
8419 "0 AS typmodinoid, 0 AS typmodoutoid, "
8420 "0 AS typanalyzeoid, "
8421 "'U' AS typcategory, false AS typispreferred, "
8422 "typdelim, typbyval, typalign, typstorage, "
8423 "false AS typcollatable, "
8424 "NULL AS typdefaultbin, NULL AS typdefault "
8426 "WHERE oid = '%u'::oid",
8427 tyinfo->dobj.catId.oid);
8431 appendPQExpBuffer(query, "SELECT typlen, "
8432 "typinput, typoutput, "
8433 "'-' AS typreceive, '-' AS typsend, "
8434 "'-' AS typmodin, '-' AS typmodout, "
8435 "'-' AS typanalyze, "
8436 "0 AS typreceiveoid, 0 AS typsendoid, "
8437 "0 AS typmodinoid, 0 AS typmodoutoid, "
8438 "0 AS typanalyzeoid, "
8439 "'U' AS typcategory, false AS typispreferred, "
8440 "typdelim, typbyval, typalign, "
8441 "'p'::char AS typstorage, "
8442 "false AS typcollatable, "
8443 "NULL AS typdefaultbin, NULL AS typdefault "
8445 "WHERE oid = '%u'::oid",
8446 tyinfo->dobj.catId.oid);
8449 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8451 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8452 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8453 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8454 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8455 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8456 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8457 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8458 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8459 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8460 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8461 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8462 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8463 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8464 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8465 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8466 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8467 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8468 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8469 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8470 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8471 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8472 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8473 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8475 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8476 typdefault_is_literal = true; /* it needs quotes */
8481 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8484 * DROP must be fully qualified in case same name appears in pg_catalog.
8485 * The reason we include CASCADE is that the circular dependency between
8486 * the type and its I/O functions makes it impossible to drop the type any
8489 appendPQExpBuffer(delq, "DROP TYPE %s.",
8490 fmtId(tyinfo->dobj.namespace->dobj.name));
8491 appendPQExpBuffer(delq, "%s CASCADE;\n",
8494 /* We might already have a shell type, but setting pg_type_oid is harmless */
8496 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8497 tyinfo->dobj.catId.oid);
8499 appendPQExpBuffer(q,
8500 "CREATE TYPE %s (\n"
8501 " INTERNALLENGTH = %s",
8503 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8505 if (fout->remoteVersion >= 70300)
8507 /* regproc result is correctly quoted as of 7.3 */
8508 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8509 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8510 if (OidIsValid(typreceiveoid))
8511 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8512 if (OidIsValid(typsendoid))
8513 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8514 if (OidIsValid(typmodinoid))
8515 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8516 if (OidIsValid(typmodoutoid))
8517 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8518 if (OidIsValid(typanalyzeoid))
8519 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8523 /* regproc delivers an unquoted name before 7.3 */
8524 /* cannot combine these because fmtId uses static result area */
8525 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8526 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8527 /* receive/send/typmodin/typmodout/analyze need not be printed */
8530 if (strcmp(typcollatable, "t") == 0)
8531 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8533 if (typdefault != NULL)
8535 appendPQExpBuffer(q, ",\n DEFAULT = ");
8536 if (typdefault_is_literal)
8537 appendStringLiteralAH(q, typdefault, fout);
8539 appendPQExpBufferStr(q, typdefault);
8542 if (OidIsValid(tyinfo->typelem))
8546 /* reselect schema in case changed by function dump */
8547 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8548 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8549 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8553 if (strcmp(typcategory, "U") != 0)
8555 appendPQExpBuffer(q, ",\n CATEGORY = ");
8556 appendStringLiteralAH(q, typcategory, fout);
8559 if (strcmp(typispreferred, "t") == 0)
8560 appendPQExpBuffer(q, ",\n PREFERRED = true");
8562 if (typdelim && strcmp(typdelim, ",") != 0)
8564 appendPQExpBuffer(q, ",\n DELIMITER = ");
8565 appendStringLiteralAH(q, typdelim, fout);
8568 if (strcmp(typalign, "c") == 0)
8569 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8570 else if (strcmp(typalign, "s") == 0)
8571 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8572 else if (strcmp(typalign, "i") == 0)
8573 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8574 else if (strcmp(typalign, "d") == 0)
8575 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8577 if (strcmp(typstorage, "p") == 0)
8578 appendPQExpBuffer(q, ",\n STORAGE = plain");
8579 else if (strcmp(typstorage, "e") == 0)
8580 appendPQExpBuffer(q, ",\n STORAGE = external");
8581 else if (strcmp(typstorage, "x") == 0)
8582 appendPQExpBuffer(q, ",\n STORAGE = extended");
8583 else if (strcmp(typstorage, "m") == 0)
8584 appendPQExpBuffer(q, ",\n STORAGE = main");
8586 if (strcmp(typbyval, "t") == 0)
8587 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8589 appendPQExpBuffer(q, "\n);\n");
8591 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8594 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8596 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8598 tyinfo->dobj.namespace->dobj.name,
8600 tyinfo->rolname, false,
8601 "TYPE", SECTION_PRE_DATA,
8602 q->data, delq->data, NULL,
8606 /* Dump Type Comments and Security Labels */
8607 dumpComment(fout, labelq->data,
8608 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8609 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8610 dumpSecLabel(fout, labelq->data,
8611 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8612 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8614 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8615 qtypname, NULL, tyinfo->dobj.name,
8616 tyinfo->dobj.namespace->dobj.name,
8617 tyinfo->rolname, tyinfo->typacl);
8620 destroyPQExpBuffer(q);
8621 destroyPQExpBuffer(delq);
8622 destroyPQExpBuffer(labelq);
8623 destroyPQExpBuffer(query);
8628 * writes out to fout the queries to recreate a user-defined domain
8631 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8633 PQExpBuffer q = createPQExpBuffer();
8634 PQExpBuffer delq = createPQExpBuffer();
8635 PQExpBuffer labelq = createPQExpBuffer();
8636 PQExpBuffer query = createPQExpBuffer();
8644 bool typdefault_is_literal = false;
8646 /* Set proper schema search path so type references list correctly */
8647 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8649 /* Fetch domain specific details */
8650 if (fout->remoteVersion >= 90100)
8652 /* typcollation is new in 9.1 */
8653 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8654 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8655 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8657 "CASE WHEN t.typcollation <> u.typcollation "
8658 "THEN t.typcollation ELSE 0 END AS typcollation "
8659 "FROM pg_catalog.pg_type t "
8660 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8661 "WHERE t.oid = '%u'::pg_catalog.oid",
8662 tyinfo->dobj.catId.oid);
8666 /* We assume here that remoteVersion must be at least 70300 */
8667 appendPQExpBuffer(query, "SELECT typnotnull, "
8668 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8669 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8670 "typdefault, 0 AS typcollation "
8671 "FROM pg_catalog.pg_type "
8672 "WHERE oid = '%u'::pg_catalog.oid",
8673 tyinfo->dobj.catId.oid);
8676 res = ExecuteSqlQueryForSingleRow(fout, query->data);
8678 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8679 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8680 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8681 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8682 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8684 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8685 typdefault_is_literal = true; /* it needs quotes */
8689 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8692 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8693 tyinfo->dobj.catId.oid);
8695 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8697 appendPQExpBuffer(q,
8698 "CREATE DOMAIN %s AS %s",
8702 /* Print collation only if different from base type's collation */
8703 if (OidIsValid(typcollation))
8707 coll = findCollationByOid(typcollation);
8710 /* always schema-qualify, don't try to be smart */
8711 appendPQExpBuffer(q, " COLLATE %s.",
8712 fmtId(coll->dobj.namespace->dobj.name));
8713 appendPQExpBuffer(q, "%s",
8714 fmtId(coll->dobj.name));
8718 if (typnotnull[0] == 't')
8719 appendPQExpBuffer(q, " NOT NULL");
8721 if (typdefault != NULL)
8723 appendPQExpBuffer(q, " DEFAULT ");
8724 if (typdefault_is_literal)
8725 appendStringLiteralAH(q, typdefault, fout);
8727 appendPQExpBufferStr(q, typdefault);
8733 * Add any CHECK constraints for the domain
8735 for (i = 0; i < tyinfo->nDomChecks; i++)
8737 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8739 if (!domcheck->separate)
8740 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8741 fmtId(domcheck->dobj.name), domcheck->condef);
8744 appendPQExpBuffer(q, ";\n");
8747 * DROP must be fully qualified in case same name appears in pg_catalog
8749 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8750 fmtId(tyinfo->dobj.namespace->dobj.name));
8751 appendPQExpBuffer(delq, "%s;\n",
8754 appendPQExpBuffer(labelq, "DOMAIN %s", qtypname);
8757 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8759 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8761 tyinfo->dobj.namespace->dobj.name,
8763 tyinfo->rolname, false,
8764 "DOMAIN", SECTION_PRE_DATA,
8765 q->data, delq->data, NULL,
8769 /* Dump Domain Comments and Security Labels */
8770 dumpComment(fout, labelq->data,
8771 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8772 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8773 dumpSecLabel(fout, labelq->data,
8774 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8775 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8777 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8778 qtypname, NULL, tyinfo->dobj.name,
8779 tyinfo->dobj.namespace->dobj.name,
8780 tyinfo->rolname, tyinfo->typacl);
8782 destroyPQExpBuffer(q);
8783 destroyPQExpBuffer(delq);
8784 destroyPQExpBuffer(labelq);
8785 destroyPQExpBuffer(query);
8790 * writes out to fout the queries to recreate a user-defined stand-alone
8794 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8796 PQExpBuffer q = createPQExpBuffer();
8797 PQExpBuffer dropped = createPQExpBuffer();
8798 PQExpBuffer delq = createPQExpBuffer();
8799 PQExpBuffer labelq = createPQExpBuffer();
8800 PQExpBuffer query = createPQExpBuffer();
8814 /* Set proper schema search path so type references list correctly */
8815 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8817 /* Fetch type specific details */
8818 if (fout->remoteVersion >= 90100)
8821 * attcollation is new in 9.1. Since we only want to dump COLLATE
8822 * clauses for attributes whose collation is different from their
8823 * type's default, we use a CASE here to suppress uninteresting
8824 * attcollations cheaply. atttypid will be 0 for dropped columns;
8825 * collation does not matter for those.
8827 appendPQExpBuffer(query, "SELECT a.attname, "
8828 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8829 "a.attlen, a.attalign, a.attisdropped, "
8830 "CASE WHEN a.attcollation <> at.typcollation "
8831 "THEN a.attcollation ELSE 0 END AS attcollation, "
8833 "FROM pg_catalog.pg_type ct "
8834 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8835 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8836 "WHERE ct.oid = '%u'::pg_catalog.oid "
8837 "ORDER BY a.attnum ",
8838 tyinfo->dobj.catId.oid);
8843 * We assume here that remoteVersion must be at least 70300. Since
8844 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8847 appendPQExpBuffer(query, "SELECT a.attname, "
8848 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8849 "a.attlen, a.attalign, a.attisdropped, "
8850 "0 AS attcollation, "
8852 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8853 "WHERE ct.oid = '%u'::pg_catalog.oid "
8854 "AND a.attrelid = ct.typrelid "
8855 "ORDER BY a.attnum ",
8856 tyinfo->dobj.catId.oid);
8859 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8861 ntups = PQntuples(res);
8863 i_attname = PQfnumber(res, "attname");
8864 i_atttypdefn = PQfnumber(res, "atttypdefn");
8865 i_attlen = PQfnumber(res, "attlen");
8866 i_attalign = PQfnumber(res, "attalign");
8867 i_attisdropped = PQfnumber(res, "attisdropped");
8868 i_attcollation = PQfnumber(res, "attcollation");
8869 i_typrelid = PQfnumber(res, "typrelid");
8873 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8875 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8876 tyinfo->dobj.catId.oid);
8877 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8880 qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
8882 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8886 for (i = 0; i < ntups; i++)
8895 attname = PQgetvalue(res, i, i_attname);
8896 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8897 attlen = PQgetvalue(res, i, i_attlen);
8898 attalign = PQgetvalue(res, i, i_attalign);
8899 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8900 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8902 if (attisdropped && !binary_upgrade)
8905 /* Format properly if not first attr */
8906 if (actual_atts++ > 0)
8907 appendPQExpBuffer(q, ",");
8908 appendPQExpBuffer(q, "\n\t");
8912 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8914 /* Add collation if not default for the column type */
8915 if (OidIsValid(attcollation))
8919 coll = findCollationByOid(attcollation);
8922 /* always schema-qualify, don't try to be smart */
8923 appendPQExpBuffer(q, " COLLATE %s.",
8924 fmtId(coll->dobj.namespace->dobj.name));
8925 appendPQExpBuffer(q, "%s",
8926 fmtId(coll->dobj.name));
8933 * This is a dropped attribute and we're in binary_upgrade mode.
8934 * Insert a placeholder for it in the CREATE TYPE command, and set
8935 * length and alignment with direct UPDATE to the catalogs
8936 * afterwards. See similar code in dumpTableSchema().
8938 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8940 /* stash separately for insertion after the CREATE TYPE */
8941 appendPQExpBuffer(dropped,
8942 "\n-- For binary upgrade, recreate dropped column.\n");
8943 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8945 "attalign = '%s', attbyval = false\n"
8946 "WHERE attname = ", attlen, attalign);
8947 appendStringLiteralAH(dropped, attname, fout);
8948 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8949 appendStringLiteralAH(dropped, qtypname, fout);
8950 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8952 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8954 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8958 appendPQExpBuffer(q, "\n);\n");
8959 appendPQExpBufferStr(q, dropped->data);
8962 * DROP must be fully qualified in case same name appears in pg_catalog
8964 appendPQExpBuffer(delq, "DROP TYPE %s.",
8965 fmtId(tyinfo->dobj.namespace->dobj.name));
8966 appendPQExpBuffer(delq, "%s;\n",
8969 appendPQExpBuffer(labelq, "TYPE %s", qtypname);
8972 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8974 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8976 tyinfo->dobj.namespace->dobj.name,
8978 tyinfo->rolname, false,
8979 "TYPE", SECTION_PRE_DATA,
8980 q->data, delq->data, NULL,
8985 /* Dump Type Comments and Security Labels */
8986 dumpComment(fout, labelq->data,
8987 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8988 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8989 dumpSecLabel(fout, labelq->data,
8990 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8991 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8993 dumpACL(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId, "TYPE",
8994 qtypname, NULL, tyinfo->dobj.name,
8995 tyinfo->dobj.namespace->dobj.name,
8996 tyinfo->rolname, tyinfo->typacl);
8999 destroyPQExpBuffer(q);
9000 destroyPQExpBuffer(dropped);
9001 destroyPQExpBuffer(delq);
9002 destroyPQExpBuffer(labelq);
9003 destroyPQExpBuffer(query);
9005 /* Dump any per-column comments */
9006 dumpCompositeTypeColComments(fout, tyinfo);
9010 * dumpCompositeTypeColComments
9011 * writes out to fout the queries to recreate comments on the columns of
9012 * a user-defined stand-alone composite type
9015 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
9017 CommentItem *comments;
9028 query = createPQExpBuffer();
9030 /* We assume here that remoteVersion must be at least 70300 */
9031 appendPQExpBuffer(query,
9032 "SELECT c.tableoid, a.attname, a.attnum "
9033 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
9034 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
9035 " AND NOT a.attisdropped "
9036 "ORDER BY a.attnum ",
9039 /* Fetch column attnames */
9040 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9042 ntups = PQntuples(res);
9046 destroyPQExpBuffer(query);
9050 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
9052 /* Search for comments associated with type's pg_class OID */
9053 ncomments = findComments(fout,
9058 /* If no comments exist, we're done */
9062 destroyPQExpBuffer(query);
9066 /* Build COMMENT ON statements */
9067 target = createPQExpBuffer();
9069 i_attnum = PQfnumber(res, "attnum");
9070 i_attname = PQfnumber(res, "attname");
9071 while (ncomments > 0)
9073 const char *attname;
9076 for (i = 0; i < ntups; i++)
9078 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
9080 attname = PQgetvalue(res, i, i_attname);
9084 if (attname) /* just in case we don't find it */
9086 const char *descr = comments->descr;
9088 resetPQExpBuffer(target);
9089 appendPQExpBuffer(target, "COLUMN %s.",
9090 fmtId(tyinfo->dobj.name));
9091 appendPQExpBuffer(target, "%s",
9094 resetPQExpBuffer(query);
9095 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
9096 appendStringLiteralAH(query, descr, fout);
9097 appendPQExpBuffer(query, ";\n");
9099 ArchiveEntry(fout, nilCatalogId, createDumpId(),
9101 tyinfo->dobj.namespace->dobj.name,
9102 NULL, tyinfo->rolname,
9103 false, "COMMENT", SECTION_NONE,
9104 query->data, "", NULL,
9105 &(tyinfo->dobj.dumpId), 1,
9114 destroyPQExpBuffer(query);
9115 destroyPQExpBuffer(target);
9120 * writes out to fout the queries to create a shell type
9122 * We dump a shell definition in advance of the I/O functions for the type.
9125 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
9129 /* Skip if not to be dumped */
9130 if (!stinfo->dobj.dump || dataOnly)
9133 q = createPQExpBuffer();
9136 * Note the lack of a DROP command for the shell type; any required DROP
9137 * is driven off the base type entry, instead. This interacts with
9138 * _printTocEntry()'s use of the presence of a DROP command to decide
9139 * whether an entry needs an ALTER OWNER command. We don't want to alter
9140 * the shell type's owner immediately on creation; that should happen only
9141 * after it's filled in, otherwise the backend complains.
9145 binary_upgrade_set_type_oids_by_type_oid(fout, q,
9146 stinfo->baseType->dobj.catId.oid);
9148 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
9149 fmtId(stinfo->dobj.name));
9151 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
9153 stinfo->dobj.namespace->dobj.name,
9155 stinfo->baseType->rolname, false,
9156 "SHELL TYPE", SECTION_PRE_DATA,
9161 destroyPQExpBuffer(q);
9165 * Determine whether we want to dump definitions for procedural languages.
9166 * Since the languages themselves don't have schemas, we can't rely on
9167 * the normal schema-based selection mechanism. We choose to dump them
9168 * whenever neither --schema nor --table was given. (Before 8.1, we used
9169 * the dump flag of the PL's call handler function, but in 8.1 this will
9170 * probably always be false since call handlers are created in pg_catalog.)
9172 * For some backwards compatibility with the older behavior, we forcibly
9173 * dump a PL if its handler function (and validator if any) are in a
9174 * dumpable namespace. That case is not checked here.
9176 * Also, if the PL belongs to an extension, we do not use this heuristic.
9177 * That case isn't checked here either.
9180 shouldDumpProcLangs(void)
9182 if (!include_everything)
9184 /* And they're schema not data */
9192 * writes out to fout the queries to recreate a user-defined
9193 * procedural language
9196 dumpProcLang(Archive *fout, ProcLangInfo *plang)
9205 FuncInfo *inlineInfo = NULL;
9206 FuncInfo *validatorInfo = NULL;
9208 /* Skip if not to be dumped */
9209 if (!plang->dobj.dump || dataOnly)
9213 * Try to find the support function(s). It is not an error if we don't
9214 * find them --- if the functions are in the pg_catalog schema, as is
9215 * standard in 8.1 and up, then we won't have loaded them. (In this case
9216 * we will emit a parameterless CREATE LANGUAGE command, which will
9217 * require PL template knowledge in the backend to reload.)
9220 funcInfo = findFuncByOid(plang->lanplcallfoid);
9221 if (funcInfo != NULL && !funcInfo->dobj.dump)
9222 funcInfo = NULL; /* treat not-dumped same as not-found */
9224 if (OidIsValid(plang->laninline))
9226 inlineInfo = findFuncByOid(plang->laninline);
9227 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
9231 if (OidIsValid(plang->lanvalidator))
9233 validatorInfo = findFuncByOid(plang->lanvalidator);
9234 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
9235 validatorInfo = NULL;
9239 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
9240 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
9243 * However, for a language that belongs to an extension, we must not use
9244 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
9245 * told to (via dobj.dump). Generally the support functions will belong
9246 * to the same extension and so have the same dump flags ... if they
9247 * don't, this might not work terribly nicely.
9249 useParams = (funcInfo != NULL &&
9250 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
9251 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
9253 if (!plang->dobj.ext_member)
9255 if (!useParams && !shouldDumpProcLangs())
9259 defqry = createPQExpBuffer();
9260 delqry = createPQExpBuffer();
9261 labelq = createPQExpBuffer();
9263 qlanname = pg_strdup(fmtId(plang->dobj.name));
9266 * If dumping a HANDLER clause, treat the language as being in the handler
9267 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
9268 * it doesn't really have a schema.
9271 lanschema = funcInfo->dobj.namespace->dobj.name;
9275 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
9280 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
9281 plang->lanpltrusted ? "TRUSTED " : "",
9283 appendPQExpBuffer(defqry, " HANDLER %s",
9284 fmtId(funcInfo->dobj.name));
9285 if (OidIsValid(plang->laninline))
9287 appendPQExpBuffer(defqry, " INLINE ");
9288 /* Cope with possibility that inline is in different schema */
9289 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
9290 appendPQExpBuffer(defqry, "%s.",
9291 fmtId(inlineInfo->dobj.namespace->dobj.name));
9292 appendPQExpBuffer(defqry, "%s",
9293 fmtId(inlineInfo->dobj.name));
9295 if (OidIsValid(plang->lanvalidator))
9297 appendPQExpBuffer(defqry, " VALIDATOR ");
9298 /* Cope with possibility that validator is in different schema */
9299 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
9300 appendPQExpBuffer(defqry, "%s.",
9301 fmtId(validatorInfo->dobj.namespace->dobj.name));
9302 appendPQExpBuffer(defqry, "%s",
9303 fmtId(validatorInfo->dobj.name));
9309 * If not dumping parameters, then use CREATE OR REPLACE so that the
9310 * command will not fail if the language is preinstalled in the target
9311 * database. We restrict the use of REPLACE to this case so as to
9312 * eliminate the risk of replacing a language with incompatible
9313 * parameter settings: this command will only succeed at all if there
9314 * is a pg_pltemplate entry, and if there is one, the existing entry
9315 * must match it too.
9317 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
9320 appendPQExpBuffer(defqry, ";\n");
9322 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
9325 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
9327 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
9329 lanschema, NULL, plang->lanowner,
9330 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
9331 defqry->data, delqry->data, NULL,
9335 /* Dump Proc Lang Comments and Security Labels */
9336 dumpComment(fout, labelq->data,
9338 plang->dobj.catId, 0, plang->dobj.dumpId);
9339 dumpSecLabel(fout, labelq->data,
9341 plang->dobj.catId, 0, plang->dobj.dumpId);
9343 if (plang->lanpltrusted)
9344 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
9345 qlanname, NULL, plang->dobj.name,
9347 plang->lanowner, plang->lanacl);
9351 destroyPQExpBuffer(defqry);
9352 destroyPQExpBuffer(delqry);
9353 destroyPQExpBuffer(labelq);
9357 * format_function_arguments: generate function name and argument list
9359 * This is used when we can rely on pg_get_function_arguments to format
9360 * the argument list.
9363 format_function_arguments(FuncInfo *finfo, char *funcargs)
9367 initPQExpBuffer(&fn);
9368 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
9373 * format_function_arguments_old: generate function name and argument list
9375 * The argument type names are qualified if needed. The function name
9376 * is never qualified.
9378 * This is used only with pre-8.4 servers, so we aren't expecting to see
9379 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
9381 * Any or all of allargtypes, argmodes, argnames may be NULL.
9384 format_function_arguments_old(Archive *fout,
9385 FuncInfo *finfo, int nallargs,
9393 initPQExpBuffer(&fn);
9394 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9395 for (j = 0; j < nallargs; j++)
9399 const char *argmode;
9400 const char *argname;
9402 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
9403 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
9407 switch (argmodes[j][0])
9412 case PROARGMODE_OUT:
9415 case PROARGMODE_INOUT:
9419 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
9427 argname = argnames ? argnames[j] : (char *) NULL;
9428 if (argname && argname[0] == '\0')
9431 appendPQExpBuffer(&fn, "%s%s%s%s%s",
9432 (j > 0) ? ", " : "",
9434 argname ? fmtId(argname) : "",
9439 appendPQExpBuffer(&fn, ")");
9444 * format_function_signature: generate function name and argument list
9446 * This is like format_function_arguments_old except that only a minimal
9447 * list of input argument types is generated; this is sufficient to
9448 * reference the function, but not to define it.
9450 * If honor_quotes is false then the function name is never quoted.
9451 * This is appropriate for use in TOC tags, but not in SQL commands.
9454 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9459 initPQExpBuffer(&fn);
9461 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9463 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9464 for (j = 0; j < finfo->nargs; j++)
9468 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9471 appendPQExpBuffer(&fn, "%s%s",
9472 (j > 0) ? ", " : "",
9476 appendPQExpBuffer(&fn, ")");
9483 * dump out one function
9486 dumpFunc(Archive *fout, FuncInfo *finfo)
9494 char *funcsig; /* identity signature */
9495 char *funcfullsig; /* full signature */
9503 char *proallargtypes;
9517 char **allargtypes = NULL;
9518 char **argmodes = NULL;
9519 char **argnames = NULL;
9520 char **configitems = NULL;
9521 int nconfigitems = 0;
9524 /* Skip if not to be dumped */
9525 if (!finfo->dobj.dump || dataOnly)
9528 query = createPQExpBuffer();
9529 q = createPQExpBuffer();
9530 delqry = createPQExpBuffer();
9531 labelq = createPQExpBuffer();
9532 asPart = createPQExpBuffer();
9534 /* Set proper schema search path so type references list correctly */
9535 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9537 /* Fetch function-specific details */
9538 if (fout->remoteVersion >= 90200)
9541 * proleakproof was added at v9.2
9543 appendPQExpBuffer(query,
9544 "SELECT proretset, prosrc, probin, "
9545 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9546 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9547 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9548 "proiswindow, provolatile, proisstrict, prosecdef, "
9549 "proleakproof, proconfig, procost, prorows, "
9550 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9551 "FROM pg_catalog.pg_proc "
9552 "WHERE oid = '%u'::pg_catalog.oid",
9553 finfo->dobj.catId.oid);
9555 else if (fout->remoteVersion >= 80400)
9558 * In 8.4 and up we rely on pg_get_function_arguments and
9559 * pg_get_function_result instead of examining proallargtypes etc.
9561 appendPQExpBuffer(query,
9562 "SELECT proretset, prosrc, probin, "
9563 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9564 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9565 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9566 "proiswindow, provolatile, proisstrict, prosecdef, "
9567 "false AS proleakproof, "
9568 " proconfig, procost, prorows, "
9569 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9570 "FROM pg_catalog.pg_proc "
9571 "WHERE oid = '%u'::pg_catalog.oid",
9572 finfo->dobj.catId.oid);
9574 else if (fout->remoteVersion >= 80300)
9576 appendPQExpBuffer(query,
9577 "SELECT proretset, prosrc, probin, "
9578 "proallargtypes, proargmodes, proargnames, "
9579 "false AS proiswindow, "
9580 "provolatile, proisstrict, prosecdef, "
9581 "false AS proleakproof, "
9582 "proconfig, procost, prorows, "
9583 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9584 "FROM pg_catalog.pg_proc "
9585 "WHERE oid = '%u'::pg_catalog.oid",
9586 finfo->dobj.catId.oid);
9588 else if (fout->remoteVersion >= 80100)
9590 appendPQExpBuffer(query,
9591 "SELECT proretset, prosrc, probin, "
9592 "proallargtypes, proargmodes, proargnames, "
9593 "false AS proiswindow, "
9594 "provolatile, proisstrict, prosecdef, "
9595 "false AS proleakproof, "
9596 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9597 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9598 "FROM pg_catalog.pg_proc "
9599 "WHERE oid = '%u'::pg_catalog.oid",
9600 finfo->dobj.catId.oid);
9602 else if (fout->remoteVersion >= 80000)
9604 appendPQExpBuffer(query,
9605 "SELECT proretset, prosrc, probin, "
9606 "null AS proallargtypes, "
9607 "null AS proargmodes, "
9609 "false AS proiswindow, "
9610 "provolatile, proisstrict, prosecdef, "
9611 "false AS proleakproof, "
9612 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9613 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9614 "FROM pg_catalog.pg_proc "
9615 "WHERE oid = '%u'::pg_catalog.oid",
9616 finfo->dobj.catId.oid);
9618 else if (fout->remoteVersion >= 70300)
9620 appendPQExpBuffer(query,
9621 "SELECT proretset, prosrc, probin, "
9622 "null AS proallargtypes, "
9623 "null AS proargmodes, "
9624 "null AS proargnames, "
9625 "false AS proiswindow, "
9626 "provolatile, proisstrict, prosecdef, "
9627 "false AS proleakproof, "
9628 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9629 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9630 "FROM pg_catalog.pg_proc "
9631 "WHERE oid = '%u'::pg_catalog.oid",
9632 finfo->dobj.catId.oid);
9634 else if (fout->remoteVersion >= 70100)
9636 appendPQExpBuffer(query,
9637 "SELECT proretset, prosrc, probin, "
9638 "null AS proallargtypes, "
9639 "null AS proargmodes, "
9640 "null AS proargnames, "
9641 "false AS proiswindow, "
9642 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9644 "false AS prosecdef, "
9645 "false AS proleakproof, "
9646 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9647 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9649 "WHERE oid = '%u'::oid",
9650 finfo->dobj.catId.oid);
9654 appendPQExpBuffer(query,
9655 "SELECT proretset, prosrc, probin, "
9656 "null AS proallargtypes, "
9657 "null AS proargmodes, "
9658 "null AS proargnames, "
9659 "false AS proiswindow, "
9660 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9661 "false AS proisstrict, "
9662 "false AS prosecdef, "
9663 "false AS proleakproof, "
9664 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9665 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9667 "WHERE oid = '%u'::oid",
9668 finfo->dobj.catId.oid);
9671 res = ExecuteSqlQueryForSingleRow(fout, query->data);
9673 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9674 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9675 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9676 if (fout->remoteVersion >= 80400)
9678 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9679 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9680 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9681 proallargtypes = proargmodes = proargnames = NULL;
9685 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9686 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9687 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9688 funcargs = funciargs = funcresult = NULL;
9690 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9691 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9692 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9693 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9694 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9695 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9696 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9697 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9698 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9701 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9702 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9703 * versions would set it to "-". There are no known cases in which prosrc
9704 * is unused, so the tests below for "-" are probably useless.
9706 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9708 appendPQExpBuffer(asPart, "AS ");
9709 appendStringLiteralAH(asPart, probin, fout);
9710 if (strcmp(prosrc, "-") != 0)
9712 appendPQExpBuffer(asPart, ", ");
9715 * where we have bin, use dollar quoting if allowed and src
9716 * contains quote or backslash; else use regular quoting.
9718 if (disable_dollar_quoting ||
9719 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9720 appendStringLiteralAH(asPart, prosrc, fout);
9722 appendStringLiteralDQ(asPart, prosrc, NULL);
9727 if (strcmp(prosrc, "-") != 0)
9729 appendPQExpBuffer(asPart, "AS ");
9730 /* with no bin, dollar quote src unconditionally if allowed */
9731 if (disable_dollar_quoting)
9732 appendStringLiteralAH(asPart, prosrc, fout);
9734 appendStringLiteralDQ(asPart, prosrc, NULL);
9738 nallargs = finfo->nargs; /* unless we learn different from allargs */
9740 if (proallargtypes && *proallargtypes)
9744 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9745 nitems < finfo->nargs)
9747 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9756 if (proargmodes && *proargmodes)
9760 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9763 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9770 if (proargnames && *proargnames)
9774 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9777 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9784 if (proconfig && *proconfig)
9786 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9788 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9798 /* 8.4 or later; we rely on server-side code for most of the work */
9799 funcfullsig = format_function_arguments(finfo, funcargs);
9800 funcsig = format_function_arguments(finfo, funciargs);
9804 /* pre-8.4, do it ourselves */
9805 funcsig = format_function_arguments_old(fout,
9806 finfo, nallargs, allargtypes,
9807 argmodes, argnames);
9808 funcfullsig = funcsig;
9811 funcsig_tag = format_function_signature(fout, finfo, false);
9814 * DROP must be fully qualified in case same name appears in pg_catalog
9816 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9817 fmtId(finfo->dobj.namespace->dobj.name),
9820 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9822 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9825 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9827 appendPQExpBuffer(q, "RETURNS %s%s",
9828 (proretset[0] == 't') ? "SETOF " : "",
9833 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9835 if (proiswindow[0] == 't')
9836 appendPQExpBuffer(q, " WINDOW");
9838 if (provolatile[0] != PROVOLATILE_VOLATILE)
9840 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9841 appendPQExpBuffer(q, " IMMUTABLE");
9842 else if (provolatile[0] == PROVOLATILE_STABLE)
9843 appendPQExpBuffer(q, " STABLE");
9844 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9845 exit_horribly(NULL, "unrecognized provolatile value for function \"%s\"\n",
9849 if (proisstrict[0] == 't')
9850 appendPQExpBuffer(q, " STRICT");
9852 if (prosecdef[0] == 't')
9853 appendPQExpBuffer(q, " SECURITY DEFINER");
9855 if (proleakproof[0] == 't')
9856 appendPQExpBuffer(q, " LEAKPROOF");
9859 * COST and ROWS are emitted only if present and not default, so as not to
9860 * break backwards-compatibility of the dump without need. Keep this code
9861 * in sync with the defaults in functioncmds.c.
9863 if (strcmp(procost, "0") != 0)
9865 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9867 /* default cost is 1 */
9868 if (strcmp(procost, "1") != 0)
9869 appendPQExpBuffer(q, " COST %s", procost);
9873 /* default cost is 100 */
9874 if (strcmp(procost, "100") != 0)
9875 appendPQExpBuffer(q, " COST %s", procost);
9878 if (proretset[0] == 't' &&
9879 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9880 appendPQExpBuffer(q, " ROWS %s", prorows);
9882 for (i = 0; i < nconfigitems; i++)
9884 /* we feel free to scribble on configitems[] here */
9885 char *configitem = configitems[i];
9888 pos = strchr(configitem, '=');
9892 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9895 * Some GUC variable names are 'LIST' type and hence must not be
9898 if (pg_strcasecmp(configitem, "DateStyle") == 0
9899 || pg_strcasecmp(configitem, "search_path") == 0)
9900 appendPQExpBuffer(q, "%s", pos);
9902 appendStringLiteralAH(q, pos, fout);
9905 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9907 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9910 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9912 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9914 finfo->dobj.namespace->dobj.name,
9916 finfo->rolname, false,
9917 "FUNCTION", SECTION_PRE_DATA,
9918 q->data, delqry->data, NULL,
9922 /* Dump Function Comments and Security Labels */
9923 dumpComment(fout, labelq->data,
9924 finfo->dobj.namespace->dobj.name, finfo->rolname,
9925 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9926 dumpSecLabel(fout, labelq->data,
9927 finfo->dobj.namespace->dobj.name, finfo->rolname,
9928 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9930 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9931 funcsig, NULL, funcsig_tag,
9932 finfo->dobj.namespace->dobj.name,
9933 finfo->rolname, finfo->proacl);
9937 destroyPQExpBuffer(query);
9938 destroyPQExpBuffer(q);
9939 destroyPQExpBuffer(delqry);
9940 destroyPQExpBuffer(labelq);
9941 destroyPQExpBuffer(asPart);
9956 * Dump a user-defined cast
9959 dumpCast(Archive *fout, CastInfo *cast)
9964 FuncInfo *funcInfo = NULL;
9966 /* Skip if not to be dumped */
9967 if (!cast->dobj.dump || dataOnly)
9970 /* Cannot dump if we don't have the cast function's info */
9971 if (OidIsValid(cast->castfunc))
9973 funcInfo = findFuncByOid(cast->castfunc);
9974 if (funcInfo == NULL)
9979 * As per discussion we dump casts if one or more of the underlying
9980 * objects (the conversion function and the two data types) are not
9981 * builtin AND if all of the non-builtin objects are included in the dump.
9982 * Builtin meaning, the namespace name does not start with "pg_".
9984 * However, for a cast that belongs to an extension, we must not use this
9985 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9987 if (!cast->dobj.ext_member)
9989 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9990 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9992 if (sourceInfo == NULL || targetInfo == NULL)
9996 * Skip this cast if all objects are from pg_
9998 if ((funcInfo == NULL ||
9999 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
10000 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
10001 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
10005 * Skip cast if function isn't from pg_ and is not to be dumped.
10008 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10009 !funcInfo->dobj.dump)
10013 * Same for the source type
10015 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10016 !sourceInfo->dobj.dump)
10020 * and the target type.
10022 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
10023 !targetInfo->dobj.dump)
10027 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
10028 selectSourceSchema(fout, "pg_catalog");
10030 defqry = createPQExpBuffer();
10031 delqry = createPQExpBuffer();
10032 labelq = createPQExpBuffer();
10034 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
10035 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10036 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10038 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
10039 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10040 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10042 switch (cast->castmethod)
10044 case COERCION_METHOD_BINARY:
10045 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
10047 case COERCION_METHOD_INOUT:
10048 appendPQExpBuffer(defqry, "WITH INOUT");
10050 case COERCION_METHOD_FUNCTION:
10053 char *fsig = format_function_signature(fout, funcInfo, true);
10056 * Always qualify the function name, in case it is not in
10057 * pg_catalog schema (format_function_signature won't qualify
10060 appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
10061 fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
10065 write_msg(NULL, "WARNING: bogus value in pg_cast.castfunc or pg_cast.castmethod field\n");
10068 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
10071 if (cast->castcontext == 'a')
10072 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
10073 else if (cast->castcontext == 'i')
10074 appendPQExpBuffer(defqry, " AS IMPLICIT");
10075 appendPQExpBuffer(defqry, ";\n");
10077 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
10078 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
10079 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
10081 if (binary_upgrade)
10082 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
10084 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
10086 "pg_catalog", NULL, "",
10087 false, "CAST", SECTION_PRE_DATA,
10088 defqry->data, delqry->data, NULL,
10092 /* Dump Cast Comments */
10093 dumpComment(fout, labelq->data,
10095 cast->dobj.catId, 0, cast->dobj.dumpId);
10097 destroyPQExpBuffer(defqry);
10098 destroyPQExpBuffer(delqry);
10099 destroyPQExpBuffer(labelq);
10104 * write out a single operator definition
10107 dumpOpr(Archive *fout, OprInfo *oprinfo)
10112 PQExpBuffer labelq;
10114 PQExpBuffer details;
10138 /* Skip if not to be dumped */
10139 if (!oprinfo->dobj.dump || dataOnly)
10143 * some operators are invalid because they were the result of user
10144 * defining operators before commutators exist
10146 if (!OidIsValid(oprinfo->oprcode))
10149 query = createPQExpBuffer();
10150 q = createPQExpBuffer();
10151 delq = createPQExpBuffer();
10152 labelq = createPQExpBuffer();
10153 oprid = createPQExpBuffer();
10154 details = createPQExpBuffer();
10156 /* Make sure we are in proper schema so regoperator works correctly */
10157 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
10159 if (fout->remoteVersion >= 80300)
10161 appendPQExpBuffer(query, "SELECT oprkind, "
10162 "oprcode::pg_catalog.regprocedure, "
10163 "oprleft::pg_catalog.regtype, "
10164 "oprright::pg_catalog.regtype, "
10165 "oprcom::pg_catalog.regoperator, "
10166 "oprnegate::pg_catalog.regoperator, "
10167 "oprrest::pg_catalog.regprocedure, "
10168 "oprjoin::pg_catalog.regprocedure, "
10169 "oprcanmerge, oprcanhash "
10170 "FROM pg_catalog.pg_operator "
10171 "WHERE oid = '%u'::pg_catalog.oid",
10172 oprinfo->dobj.catId.oid);
10174 else if (fout->remoteVersion >= 70300)
10176 appendPQExpBuffer(query, "SELECT oprkind, "
10177 "oprcode::pg_catalog.regprocedure, "
10178 "oprleft::pg_catalog.regtype, "
10179 "oprright::pg_catalog.regtype, "
10180 "oprcom::pg_catalog.regoperator, "
10181 "oprnegate::pg_catalog.regoperator, "
10182 "oprrest::pg_catalog.regprocedure, "
10183 "oprjoin::pg_catalog.regprocedure, "
10184 "(oprlsortop != 0) AS oprcanmerge, "
10186 "FROM pg_catalog.pg_operator "
10187 "WHERE oid = '%u'::pg_catalog.oid",
10188 oprinfo->dobj.catId.oid);
10190 else if (fout->remoteVersion >= 70100)
10192 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10193 "CASE WHEN oprleft = 0 THEN '-' "
10194 "ELSE format_type(oprleft, NULL) END AS oprleft, "
10195 "CASE WHEN oprright = 0 THEN '-' "
10196 "ELSE format_type(oprright, NULL) END AS oprright, "
10197 "oprcom, oprnegate, oprrest, oprjoin, "
10198 "(oprlsortop != 0) AS oprcanmerge, "
10200 "FROM pg_operator "
10201 "WHERE oid = '%u'::oid",
10202 oprinfo->dobj.catId.oid);
10206 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
10207 "CASE WHEN oprleft = 0 THEN '-'::name "
10208 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
10209 "CASE WHEN oprright = 0 THEN '-'::name "
10210 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
10211 "oprcom, oprnegate, oprrest, oprjoin, "
10212 "(oprlsortop != 0) AS oprcanmerge, "
10214 "FROM pg_operator "
10215 "WHERE oid = '%u'::oid",
10216 oprinfo->dobj.catId.oid);
10219 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10221 i_oprkind = PQfnumber(res, "oprkind");
10222 i_oprcode = PQfnumber(res, "oprcode");
10223 i_oprleft = PQfnumber(res, "oprleft");
10224 i_oprright = PQfnumber(res, "oprright");
10225 i_oprcom = PQfnumber(res, "oprcom");
10226 i_oprnegate = PQfnumber(res, "oprnegate");
10227 i_oprrest = PQfnumber(res, "oprrest");
10228 i_oprjoin = PQfnumber(res, "oprjoin");
10229 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
10230 i_oprcanhash = PQfnumber(res, "oprcanhash");
10232 oprkind = PQgetvalue(res, 0, i_oprkind);
10233 oprcode = PQgetvalue(res, 0, i_oprcode);
10234 oprleft = PQgetvalue(res, 0, i_oprleft);
10235 oprright = PQgetvalue(res, 0, i_oprright);
10236 oprcom = PQgetvalue(res, 0, i_oprcom);
10237 oprnegate = PQgetvalue(res, 0, i_oprnegate);
10238 oprrest = PQgetvalue(res, 0, i_oprrest);
10239 oprjoin = PQgetvalue(res, 0, i_oprjoin);
10240 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
10241 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
10243 appendPQExpBuffer(details, " PROCEDURE = %s",
10244 convertRegProcReference(fout, oprcode));
10246 appendPQExpBuffer(oprid, "%s (",
10247 oprinfo->dobj.name);
10250 * right unary means there's a left arg and left unary means there's a
10253 if (strcmp(oprkind, "r") == 0 ||
10254 strcmp(oprkind, "b") == 0)
10256 if (fout->remoteVersion >= 70100)
10259 name = fmtId(oprleft);
10260 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
10261 appendPQExpBuffer(oprid, "%s", name);
10264 appendPQExpBuffer(oprid, "NONE");
10266 if (strcmp(oprkind, "l") == 0 ||
10267 strcmp(oprkind, "b") == 0)
10269 if (fout->remoteVersion >= 70100)
10272 name = fmtId(oprright);
10273 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
10274 appendPQExpBuffer(oprid, ", %s)", name);
10277 appendPQExpBuffer(oprid, ", NONE)");
10279 name = convertOperatorReference(fout, oprcom);
10281 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
10283 name = convertOperatorReference(fout, oprnegate);
10285 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
10287 if (strcmp(oprcanmerge, "t") == 0)
10288 appendPQExpBuffer(details, ",\n MERGES");
10290 if (strcmp(oprcanhash, "t") == 0)
10291 appendPQExpBuffer(details, ",\n HASHES");
10293 name = convertRegProcReference(fout, oprrest);
10295 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
10297 name = convertRegProcReference(fout, oprjoin);
10299 appendPQExpBuffer(details, ",\n JOIN = %s", name);
10302 * DROP must be fully qualified in case same name appears in pg_catalog
10304 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
10305 fmtId(oprinfo->dobj.namespace->dobj.name),
10308 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
10309 oprinfo->dobj.name, details->data);
10311 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
10313 if (binary_upgrade)
10314 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
10316 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
10317 oprinfo->dobj.name,
10318 oprinfo->dobj.namespace->dobj.name,
10321 false, "OPERATOR", SECTION_PRE_DATA,
10322 q->data, delq->data, NULL,
10326 /* Dump Operator Comments */
10327 dumpComment(fout, labelq->data,
10328 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
10329 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
10333 destroyPQExpBuffer(query);
10334 destroyPQExpBuffer(q);
10335 destroyPQExpBuffer(delq);
10336 destroyPQExpBuffer(labelq);
10337 destroyPQExpBuffer(oprid);
10338 destroyPQExpBuffer(details);
10342 * Convert a function reference obtained from pg_operator
10344 * Returns what to print, or NULL if function references is InvalidOid
10346 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
10347 * argument-types part. In prior versions, the input is a REGPROC display.
10349 static const char *
10350 convertRegProcReference(Archive *fout, const char *proc)
10352 /* In all cases "-" means a null reference */
10353 if (strcmp(proc, "-") == 0)
10356 if (fout->remoteVersion >= 70300)
10362 name = pg_strdup(proc);
10363 /* find non-double-quoted left paren */
10365 for (paren = name; *paren; paren++)
10367 if (*paren == '(' && !inquote)
10373 inquote = !inquote;
10378 /* REGPROC before 7.3 does not quote its result */
10379 return fmtId(proc);
10383 * Convert an operator cross-reference obtained from pg_operator
10385 * Returns what to print, or NULL to print nothing
10387 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
10388 * argument-types part, and add OPERATOR() decoration if the name is
10389 * schema-qualified. In older versions, the input is just a numeric OID,
10390 * which we search our operator list for.
10392 static const char *
10393 convertOperatorReference(Archive *fout, const char *opr)
10397 /* In all cases "0" means a null reference */
10398 if (strcmp(opr, "0") == 0)
10401 if (fout->remoteVersion >= 70300)
10409 name = pg_strdup(opr);
10410 /* find non-double-quoted left paren, and check for non-quoted dot */
10413 for (ptr = name; *ptr; ptr++)
10416 inquote = !inquote;
10417 else if (*ptr == '.' && !inquote)
10419 else if (*ptr == '(' && !inquote)
10425 /* If not schema-qualified, don't need to add OPERATOR() */
10428 oname = pg_malloc(strlen(name) + 11);
10429 sprintf(oname, "OPERATOR(%s)", name);
10434 oprInfo = findOprByOid(atooid(opr));
10435 if (oprInfo == NULL)
10437 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10441 return oprInfo->dobj.name;
10445 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10447 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10448 * argument lists of these functions are predetermined. Note that the
10449 * caller should ensure we are in the proper schema, because the results
10450 * are search path dependent!
10452 static const char *
10453 convertTSFunction(Archive *fout, Oid funcOid)
10459 snprintf(query, sizeof(query),
10460 "SELECT '%u'::pg_catalog.regproc", funcOid);
10461 res = ExecuteSqlQueryForSingleRow(fout, query);
10463 result = pg_strdup(PQgetvalue(res, 0, 0));
10473 * write out a single operator class definition
10476 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10481 PQExpBuffer labelq;
10488 int i_opcfamilyname;
10489 int i_opcfamilynsp;
10491 int i_amopstrategy;
10492 int i_amopreqcheck;
10495 int i_sortfamilynsp;
10498 int i_amproclefttype;
10499 int i_amprocrighttype;
10504 char *opcfamilyname;
10505 char *opcfamilynsp;
10507 char *amopstrategy;
10508 char *amopreqcheck;
10511 char *sortfamilynsp;
10514 char *amproclefttype;
10515 char *amprocrighttype;
10519 /* Skip if not to be dumped */
10520 if (!opcinfo->dobj.dump || dataOnly)
10524 * XXX currently we do not implement dumping of operator classes from
10525 * pre-7.3 databases. This could be done but it seems not worth the
10528 if (fout->remoteVersion < 70300)
10531 query = createPQExpBuffer();
10532 q = createPQExpBuffer();
10533 delq = createPQExpBuffer();
10534 labelq = createPQExpBuffer();
10536 /* Make sure we are in proper schema so regoperator works correctly */
10537 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10539 /* Get additional fields from the pg_opclass row */
10540 if (fout->remoteVersion >= 80300)
10542 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10543 "opckeytype::pg_catalog.regtype, "
10544 "opcdefault, opcfamily, "
10545 "opfname AS opcfamilyname, "
10546 "nspname AS opcfamilynsp, "
10547 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10548 "FROM pg_catalog.pg_opclass c "
10549 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10550 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10551 "WHERE c.oid = '%u'::pg_catalog.oid",
10552 opcinfo->dobj.catId.oid);
10556 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10557 "opckeytype::pg_catalog.regtype, "
10558 "opcdefault, NULL AS opcfamily, "
10559 "NULL AS opcfamilyname, "
10560 "NULL AS opcfamilynsp, "
10561 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10562 "FROM pg_catalog.pg_opclass "
10563 "WHERE oid = '%u'::pg_catalog.oid",
10564 opcinfo->dobj.catId.oid);
10567 res = ExecuteSqlQueryForSingleRow(fout, query->data);
10569 i_opcintype = PQfnumber(res, "opcintype");
10570 i_opckeytype = PQfnumber(res, "opckeytype");
10571 i_opcdefault = PQfnumber(res, "opcdefault");
10572 i_opcfamily = PQfnumber(res, "opcfamily");
10573 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10574 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10575 i_amname = PQfnumber(res, "amname");
10577 opcintype = PQgetvalue(res, 0, i_opcintype);
10578 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10579 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10580 /* opcfamily will still be needed after we PQclear res */
10581 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10582 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10583 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10584 /* amname will still be needed after we PQclear res */
10585 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10588 * DROP must be fully qualified in case same name appears in pg_catalog
10590 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10591 fmtId(opcinfo->dobj.namespace->dobj.name));
10592 appendPQExpBuffer(delq, ".%s",
10593 fmtId(opcinfo->dobj.name));
10594 appendPQExpBuffer(delq, " USING %s;\n",
10597 /* Build the fixed portion of the CREATE command */
10598 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10599 fmtId(opcinfo->dobj.name));
10600 if (strcmp(opcdefault, "t") == 0)
10601 appendPQExpBuffer(q, "DEFAULT ");
10602 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10605 if (strlen(opcfamilyname) > 0 &&
10606 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10607 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10609 appendPQExpBuffer(q, " FAMILY ");
10610 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10611 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10612 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10614 appendPQExpBuffer(q, " AS\n ");
10618 if (strcmp(opckeytype, "-") != 0)
10620 appendPQExpBuffer(q, "STORAGE %s",
10628 * Now fetch and print the OPERATOR entries (pg_amop rows).
10630 * Print only those opfamily members that are tied to the opclass by
10631 * pg_depend entries.
10633 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10634 * older server's opclass in which it is used. This is to avoid
10635 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10636 * older server and then reload into that old version. This can go away
10637 * once 8.3 is so old as to not be of interest to anyone.
10639 resetPQExpBuffer(query);
10641 if (fout->remoteVersion >= 90100)
10643 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10644 "amopopr::pg_catalog.regoperator, "
10645 "opfname AS sortfamily, "
10646 "nspname AS sortfamilynsp "
10647 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10648 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10649 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10650 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10651 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10652 "AND refobjid = '%u'::pg_catalog.oid "
10653 "AND amopfamily = '%s'::pg_catalog.oid "
10654 "ORDER BY amopstrategy",
10655 opcinfo->dobj.catId.oid,
10658 else if (fout->remoteVersion >= 80400)
10660 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10661 "amopopr::pg_catalog.regoperator, "
10662 "NULL AS sortfamily, "
10663 "NULL AS sortfamilynsp "
10664 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10665 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10666 "AND refobjid = '%u'::pg_catalog.oid "
10667 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10668 "AND objid = ao.oid "
10669 "ORDER BY amopstrategy",
10670 opcinfo->dobj.catId.oid);
10672 else if (fout->remoteVersion >= 80300)
10674 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10675 "amopopr::pg_catalog.regoperator, "
10676 "NULL AS sortfamily, "
10677 "NULL AS sortfamilynsp "
10678 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10679 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10680 "AND refobjid = '%u'::pg_catalog.oid "
10681 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10682 "AND objid = ao.oid "
10683 "ORDER BY amopstrategy",
10684 opcinfo->dobj.catId.oid);
10689 * Here, we print all entries since there are no opfamilies and hence
10690 * no loose operators to worry about.
10692 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10693 "amopopr::pg_catalog.regoperator, "
10694 "NULL AS sortfamily, "
10695 "NULL AS sortfamilynsp "
10696 "FROM pg_catalog.pg_amop "
10697 "WHERE amopclaid = '%u'::pg_catalog.oid "
10698 "ORDER BY amopstrategy",
10699 opcinfo->dobj.catId.oid);
10702 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10704 ntups = PQntuples(res);
10706 i_amopstrategy = PQfnumber(res, "amopstrategy");
10707 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10708 i_amopopr = PQfnumber(res, "amopopr");
10709 i_sortfamily = PQfnumber(res, "sortfamily");
10710 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10712 for (i = 0; i < ntups; i++)
10714 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10715 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10716 amopopr = PQgetvalue(res, i, i_amopopr);
10717 sortfamily = PQgetvalue(res, i, i_sortfamily);
10718 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10721 appendPQExpBuffer(q, " ,\n ");
10723 appendPQExpBuffer(q, "OPERATOR %s %s",
10724 amopstrategy, amopopr);
10726 if (strlen(sortfamily) > 0)
10728 appendPQExpBuffer(q, " FOR ORDER BY ");
10729 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10730 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10731 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10734 if (strcmp(amopreqcheck, "t") == 0)
10735 appendPQExpBuffer(q, " RECHECK");
10743 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10745 * Print only those opfamily members that are tied to the opclass by
10746 * pg_depend entries.
10748 * We print the amproclefttype/amprocrighttype even though in most cases
10749 * the backend could deduce the right values, because of the corner case
10750 * of a btree sort support function for a cross-type comparison. That's
10751 * only allowed in 9.2 and later, but for simplicity print them in all
10752 * versions that have the columns.
10754 resetPQExpBuffer(query);
10756 if (fout->remoteVersion >= 80300)
10758 appendPQExpBuffer(query, "SELECT amprocnum, "
10759 "amproc::pg_catalog.regprocedure, "
10760 "amproclefttype::pg_catalog.regtype, "
10761 "amprocrighttype::pg_catalog.regtype "
10762 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10763 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10764 "AND refobjid = '%u'::pg_catalog.oid "
10765 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10766 "AND objid = ap.oid "
10767 "ORDER BY amprocnum",
10768 opcinfo->dobj.catId.oid);
10772 appendPQExpBuffer(query, "SELECT amprocnum, "
10773 "amproc::pg_catalog.regprocedure, "
10774 "'' AS amproclefttype, "
10775 "'' AS amprocrighttype "
10776 "FROM pg_catalog.pg_amproc "
10777 "WHERE amopclaid = '%u'::pg_catalog.oid "
10778 "ORDER BY amprocnum",
10779 opcinfo->dobj.catId.oid);
10782 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10784 ntups = PQntuples(res);
10786 i_amprocnum = PQfnumber(res, "amprocnum");
10787 i_amproc = PQfnumber(res, "amproc");
10788 i_amproclefttype = PQfnumber(res, "amproclefttype");
10789 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10791 for (i = 0; i < ntups; i++)
10793 amprocnum = PQgetvalue(res, i, i_amprocnum);
10794 amproc = PQgetvalue(res, i, i_amproc);
10795 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10796 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10799 appendPQExpBuffer(q, " ,\n ");
10801 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10803 if (*amproclefttype && *amprocrighttype)
10804 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10806 appendPQExpBuffer(q, " %s", amproc);
10813 appendPQExpBuffer(q, ";\n");
10815 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10816 fmtId(opcinfo->dobj.name));
10817 appendPQExpBuffer(labelq, " USING %s",
10820 if (binary_upgrade)
10821 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10823 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10824 opcinfo->dobj.name,
10825 opcinfo->dobj.namespace->dobj.name,
10828 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10829 q->data, delq->data, NULL,
10833 /* Dump Operator Class Comments */
10834 dumpComment(fout, labelq->data,
10835 NULL, opcinfo->rolname,
10836 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10839 destroyPQExpBuffer(query);
10840 destroyPQExpBuffer(q);
10841 destroyPQExpBuffer(delq);
10842 destroyPQExpBuffer(labelq);
10847 * write out a single operator family definition
10849 * Note: this also dumps any "loose" operator members that aren't bound to a
10850 * specific opclass within the opfamily.
10853 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10858 PQExpBuffer labelq;
10861 PGresult *res_procs;
10864 int i_amopstrategy;
10865 int i_amopreqcheck;
10868 int i_sortfamilynsp;
10871 int i_amproclefttype;
10872 int i_amprocrighttype;
10874 char *amopstrategy;
10875 char *amopreqcheck;
10878 char *sortfamilynsp;
10881 char *amproclefttype;
10882 char *amprocrighttype;
10886 /* Skip if not to be dumped */
10887 if (!opfinfo->dobj.dump || dataOnly)
10891 * We want to dump the opfamily only if (1) it contains "loose" operators
10892 * or functions, or (2) it contains an opclass with a different name or
10893 * owner. Otherwise it's sufficient to let it be created during creation
10894 * of the contained opclass, and not dumping it improves portability of
10895 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10899 query = createPQExpBuffer();
10900 q = createPQExpBuffer();
10901 delq = createPQExpBuffer();
10902 labelq = createPQExpBuffer();
10904 /* Make sure we are in proper schema so regoperator works correctly */
10905 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10908 * Fetch only those opfamily members that are tied directly to the
10909 * opfamily by pg_depend entries.
10911 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10912 * older server's opclass in which it is used. This is to avoid
10913 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10914 * older server and then reload into that old version. This can go away
10915 * once 8.3 is so old as to not be of interest to anyone.
10917 if (fout->remoteVersion >= 90100)
10919 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10920 "amopopr::pg_catalog.regoperator, "
10921 "opfname AS sortfamily, "
10922 "nspname AS sortfamilynsp "
10923 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10924 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10925 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10926 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10927 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10928 "AND refobjid = '%u'::pg_catalog.oid "
10929 "AND amopfamily = '%u'::pg_catalog.oid "
10930 "ORDER BY amopstrategy",
10931 opfinfo->dobj.catId.oid,
10932 opfinfo->dobj.catId.oid);
10934 else if (fout->remoteVersion >= 80400)
10936 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10937 "amopopr::pg_catalog.regoperator, "
10938 "NULL AS sortfamily, "
10939 "NULL AS sortfamilynsp "
10940 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10941 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10942 "AND refobjid = '%u'::pg_catalog.oid "
10943 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10944 "AND objid = ao.oid "
10945 "ORDER BY amopstrategy",
10946 opfinfo->dobj.catId.oid);
10950 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10951 "amopopr::pg_catalog.regoperator, "
10952 "NULL AS sortfamily, "
10953 "NULL AS sortfamilynsp "
10954 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10955 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10956 "AND refobjid = '%u'::pg_catalog.oid "
10957 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10958 "AND objid = ao.oid "
10959 "ORDER BY amopstrategy",
10960 opfinfo->dobj.catId.oid);
10963 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10965 resetPQExpBuffer(query);
10967 appendPQExpBuffer(query, "SELECT amprocnum, "
10968 "amproc::pg_catalog.regprocedure, "
10969 "amproclefttype::pg_catalog.regtype, "
10970 "amprocrighttype::pg_catalog.regtype "
10971 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10972 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10973 "AND refobjid = '%u'::pg_catalog.oid "
10974 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10975 "AND objid = ap.oid "
10976 "ORDER BY amprocnum",
10977 opfinfo->dobj.catId.oid);
10979 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10981 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10983 /* No loose members, so check contained opclasses */
10984 resetPQExpBuffer(query);
10986 appendPQExpBuffer(query, "SELECT 1 "
10987 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10988 "WHERE f.oid = '%u'::pg_catalog.oid "
10989 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10990 "AND refobjid = f.oid "
10991 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10992 "AND objid = c.oid "
10993 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10995 opfinfo->dobj.catId.oid);
10997 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10999 if (PQntuples(res) == 0)
11001 /* no need to dump it, so bail out */
11004 PQclear(res_procs);
11005 destroyPQExpBuffer(query);
11006 destroyPQExpBuffer(q);
11007 destroyPQExpBuffer(delq);
11008 destroyPQExpBuffer(labelq);
11015 /* Get additional fields from the pg_opfamily row */
11016 resetPQExpBuffer(query);
11018 appendPQExpBuffer(query, "SELECT "
11019 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
11020 "FROM pg_catalog.pg_opfamily "
11021 "WHERE oid = '%u'::pg_catalog.oid",
11022 opfinfo->dobj.catId.oid);
11024 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11026 i_amname = PQfnumber(res, "amname");
11028 /* amname will still be needed after we PQclear res */
11029 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
11032 * DROP must be fully qualified in case same name appears in pg_catalog
11034 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
11035 fmtId(opfinfo->dobj.namespace->dobj.name));
11036 appendPQExpBuffer(delq, ".%s",
11037 fmtId(opfinfo->dobj.name));
11038 appendPQExpBuffer(delq, " USING %s;\n",
11041 /* Build the fixed portion of the CREATE command */
11042 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
11043 fmtId(opfinfo->dobj.name));
11044 appendPQExpBuffer(q, " USING %s;\n",
11049 /* Do we need an ALTER to add loose members? */
11050 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
11052 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
11053 fmtId(opfinfo->dobj.name));
11054 appendPQExpBuffer(q, " USING %s ADD\n ",
11060 * Now fetch and print the OPERATOR entries (pg_amop rows).
11062 ntups = PQntuples(res_ops);
11064 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
11065 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
11066 i_amopopr = PQfnumber(res_ops, "amopopr");
11067 i_sortfamily = PQfnumber(res_ops, "sortfamily");
11068 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
11070 for (i = 0; i < ntups; i++)
11072 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
11073 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
11074 amopopr = PQgetvalue(res_ops, i, i_amopopr);
11075 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
11076 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
11079 appendPQExpBuffer(q, " ,\n ");
11081 appendPQExpBuffer(q, "OPERATOR %s %s",
11082 amopstrategy, amopopr);
11084 if (strlen(sortfamily) > 0)
11086 appendPQExpBuffer(q, " FOR ORDER BY ");
11087 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
11088 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
11089 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
11092 if (strcmp(amopreqcheck, "t") == 0)
11093 appendPQExpBuffer(q, " RECHECK");
11099 * Now fetch and print the FUNCTION entries (pg_amproc rows).
11101 ntups = PQntuples(res_procs);
11103 i_amprocnum = PQfnumber(res_procs, "amprocnum");
11104 i_amproc = PQfnumber(res_procs, "amproc");
11105 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
11106 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
11108 for (i = 0; i < ntups; i++)
11110 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
11111 amproc = PQgetvalue(res_procs, i, i_amproc);
11112 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
11113 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
11116 appendPQExpBuffer(q, " ,\n ");
11118 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
11119 amprocnum, amproclefttype, amprocrighttype,
11125 appendPQExpBuffer(q, ";\n");
11128 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
11129 fmtId(opfinfo->dobj.name));
11130 appendPQExpBuffer(labelq, " USING %s",
11133 if (binary_upgrade)
11134 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
11136 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
11137 opfinfo->dobj.name,
11138 opfinfo->dobj.namespace->dobj.name,
11141 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
11142 q->data, delq->data, NULL,
11146 /* Dump Operator Family Comments */
11147 dumpComment(fout, labelq->data,
11148 NULL, opfinfo->rolname,
11149 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
11153 PQclear(res_procs);
11154 destroyPQExpBuffer(query);
11155 destroyPQExpBuffer(q);
11156 destroyPQExpBuffer(delq);
11157 destroyPQExpBuffer(labelq);
11162 * write out a single collation definition
11165 dumpCollation(Archive *fout, CollInfo *collinfo)
11170 PQExpBuffer labelq;
11174 const char *collcollate;
11175 const char *collctype;
11177 /* Skip if not to be dumped */
11178 if (!collinfo->dobj.dump || dataOnly)
11181 query = createPQExpBuffer();
11182 q = createPQExpBuffer();
11183 delq = createPQExpBuffer();
11184 labelq = createPQExpBuffer();
11186 /* Make sure we are in proper schema */
11187 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
11189 /* Get conversion-specific details */
11190 appendPQExpBuffer(query, "SELECT "
11193 "FROM pg_catalog.pg_collation c "
11194 "WHERE c.oid = '%u'::pg_catalog.oid",
11195 collinfo->dobj.catId.oid);
11197 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11199 i_collcollate = PQfnumber(res, "collcollate");
11200 i_collctype = PQfnumber(res, "collctype");
11202 collcollate = PQgetvalue(res, 0, i_collcollate);
11203 collctype = PQgetvalue(res, 0, i_collctype);
11206 * DROP must be fully qualified in case same name appears in pg_catalog
11208 appendPQExpBuffer(delq, "DROP COLLATION %s",
11209 fmtId(collinfo->dobj.namespace->dobj.name));
11210 appendPQExpBuffer(delq, ".%s;\n",
11211 fmtId(collinfo->dobj.name));
11213 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
11214 fmtId(collinfo->dobj.name));
11215 appendStringLiteralAH(q, collcollate, fout);
11216 appendPQExpBuffer(q, ", lc_ctype = ");
11217 appendStringLiteralAH(q, collctype, fout);
11218 appendPQExpBuffer(q, ");\n");
11220 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
11222 if (binary_upgrade)
11223 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
11225 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
11226 collinfo->dobj.name,
11227 collinfo->dobj.namespace->dobj.name,
11230 false, "COLLATION", SECTION_PRE_DATA,
11231 q->data, delq->data, NULL,
11235 /* Dump Collation Comments */
11236 dumpComment(fout, labelq->data,
11237 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
11238 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
11242 destroyPQExpBuffer(query);
11243 destroyPQExpBuffer(q);
11244 destroyPQExpBuffer(delq);
11245 destroyPQExpBuffer(labelq);
11250 * write out a single conversion definition
11253 dumpConversion(Archive *fout, ConvInfo *convinfo)
11258 PQExpBuffer labelq;
11260 int i_conforencoding;
11261 int i_contoencoding;
11264 const char *conforencoding;
11265 const char *contoencoding;
11266 const char *conproc;
11269 /* Skip if not to be dumped */
11270 if (!convinfo->dobj.dump || dataOnly)
11273 query = createPQExpBuffer();
11274 q = createPQExpBuffer();
11275 delq = createPQExpBuffer();
11276 labelq = createPQExpBuffer();
11278 /* Make sure we are in proper schema */
11279 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
11281 /* Get conversion-specific details */
11282 appendPQExpBuffer(query, "SELECT "
11283 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
11284 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
11285 "conproc, condefault "
11286 "FROM pg_catalog.pg_conversion c "
11287 "WHERE c.oid = '%u'::pg_catalog.oid",
11288 convinfo->dobj.catId.oid);
11290 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11292 i_conforencoding = PQfnumber(res, "conforencoding");
11293 i_contoencoding = PQfnumber(res, "contoencoding");
11294 i_conproc = PQfnumber(res, "conproc");
11295 i_condefault = PQfnumber(res, "condefault");
11297 conforencoding = PQgetvalue(res, 0, i_conforencoding);
11298 contoencoding = PQgetvalue(res, 0, i_contoencoding);
11299 conproc = PQgetvalue(res, 0, i_conproc);
11300 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
11303 * DROP must be fully qualified in case same name appears in pg_catalog
11305 appendPQExpBuffer(delq, "DROP CONVERSION %s",
11306 fmtId(convinfo->dobj.namespace->dobj.name));
11307 appendPQExpBuffer(delq, ".%s;\n",
11308 fmtId(convinfo->dobj.name));
11310 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
11311 (condefault) ? "DEFAULT " : "",
11312 fmtId(convinfo->dobj.name));
11313 appendStringLiteralAH(q, conforencoding, fout);
11314 appendPQExpBuffer(q, " TO ");
11315 appendStringLiteralAH(q, contoencoding, fout);
11316 /* regproc is automatically quoted in 7.3 and above */
11317 appendPQExpBuffer(q, " FROM %s;\n", conproc);
11319 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
11321 if (binary_upgrade)
11322 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
11324 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
11325 convinfo->dobj.name,
11326 convinfo->dobj.namespace->dobj.name,
11329 false, "CONVERSION", SECTION_PRE_DATA,
11330 q->data, delq->data, NULL,
11334 /* Dump Conversion Comments */
11335 dumpComment(fout, labelq->data,
11336 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
11337 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
11341 destroyPQExpBuffer(query);
11342 destroyPQExpBuffer(q);
11343 destroyPQExpBuffer(delq);
11344 destroyPQExpBuffer(labelq);
11348 * format_aggregate_signature: generate aggregate name and argument list
11350 * The argument type names are qualified if needed. The aggregate name
11351 * is never qualified.
11354 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
11356 PQExpBufferData buf;
11359 initPQExpBuffer(&buf);
11361 appendPQExpBuffer(&buf, "%s",
11362 fmtId(agginfo->aggfn.dobj.name));
11364 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11366 if (agginfo->aggfn.nargs == 0)
11367 appendPQExpBuffer(&buf, "(*)");
11370 appendPQExpBuffer(&buf, "(");
11371 for (j = 0; j < agginfo->aggfn.nargs; j++)
11375 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11378 appendPQExpBuffer(&buf, "%s%s",
11379 (j > 0) ? ", " : "",
11383 appendPQExpBuffer(&buf, ")");
11390 * write out a single aggregate definition
11393 dumpAgg(Archive *fout, AggInfo *agginfo)
11398 PQExpBuffer labelq;
11399 PQExpBuffer details;
11406 int i_aggtranstype;
11409 const char *aggtransfn;
11410 const char *aggfinalfn;
11411 const char *aggsortop;
11412 const char *aggtranstype;
11413 const char *agginitval;
11416 /* Skip if not to be dumped */
11417 if (!agginfo->aggfn.dobj.dump || dataOnly)
11420 query = createPQExpBuffer();
11421 q = createPQExpBuffer();
11422 delq = createPQExpBuffer();
11423 labelq = createPQExpBuffer();
11424 details = createPQExpBuffer();
11426 /* Make sure we are in proper schema */
11427 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11429 /* Get aggregate-specific details */
11430 if (fout->remoteVersion >= 80100)
11432 appendPQExpBuffer(query, "SELECT aggtransfn, "
11433 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11434 "aggsortop::pg_catalog.regoperator, "
11436 "'t'::boolean AS convertok "
11437 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11438 "WHERE a.aggfnoid = p.oid "
11439 "AND p.oid = '%u'::pg_catalog.oid",
11440 agginfo->aggfn.dobj.catId.oid);
11442 else if (fout->remoteVersion >= 70300)
11444 appendPQExpBuffer(query, "SELECT aggtransfn, "
11445 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11448 "'t'::boolean AS convertok "
11449 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11450 "WHERE a.aggfnoid = p.oid "
11451 "AND p.oid = '%u'::pg_catalog.oid",
11452 agginfo->aggfn.dobj.catId.oid);
11454 else if (fout->remoteVersion >= 70100)
11456 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11457 "format_type(aggtranstype, NULL) AS aggtranstype, "
11460 "'t'::boolean AS convertok "
11461 "FROM pg_aggregate "
11462 "WHERE oid = '%u'::oid",
11463 agginfo->aggfn.dobj.catId.oid);
11467 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11469 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11471 "agginitval1 AS agginitval, "
11472 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11473 "FROM pg_aggregate "
11474 "WHERE oid = '%u'::oid",
11475 agginfo->aggfn.dobj.catId.oid);
11478 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11480 i_aggtransfn = PQfnumber(res, "aggtransfn");
11481 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11482 i_aggsortop = PQfnumber(res, "aggsortop");
11483 i_aggtranstype = PQfnumber(res, "aggtranstype");
11484 i_agginitval = PQfnumber(res, "agginitval");
11485 i_convertok = PQfnumber(res, "convertok");
11487 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11488 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11489 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11490 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11491 agginitval = PQgetvalue(res, 0, i_agginitval);
11492 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11494 aggsig = format_aggregate_signature(agginfo, fout, true);
11495 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11499 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11504 if (fout->remoteVersion >= 70300)
11506 /* If using 7.3's regproc or regtype, data is already quoted */
11507 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11511 else if (fout->remoteVersion >= 70100)
11513 /* format_type quotes, regproc does not */
11514 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11520 /* need quotes all around */
11521 appendPQExpBuffer(details, " SFUNC = %s,\n",
11522 fmtId(aggtransfn));
11523 appendPQExpBuffer(details, " STYPE = %s",
11524 fmtId(aggtranstype));
11527 if (!PQgetisnull(res, 0, i_agginitval))
11529 appendPQExpBuffer(details, ",\n INITCOND = ");
11530 appendStringLiteralAH(details, agginitval, fout);
11533 if (strcmp(aggfinalfn, "-") != 0)
11535 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11539 aggsortop = convertOperatorReference(fout, aggsortop);
11542 appendPQExpBuffer(details, ",\n SORTOP = %s",
11547 * DROP must be fully qualified in case same name appears in pg_catalog
11549 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11550 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11553 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11554 aggsig, details->data);
11556 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11558 if (binary_upgrade)
11559 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11561 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11563 agginfo->aggfn.dobj.namespace->dobj.name,
11565 agginfo->aggfn.rolname,
11566 false, "AGGREGATE", SECTION_PRE_DATA,
11567 q->data, delq->data, NULL,
11571 /* Dump Aggregate Comments */
11572 dumpComment(fout, labelq->data,
11573 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11574 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11575 dumpSecLabel(fout, labelq->data,
11576 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11577 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11580 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11581 * command look like a function's GRANT; in particular this affects the
11582 * syntax for zero-argument aggregates.
11587 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11588 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11590 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11592 aggsig, NULL, aggsig_tag,
11593 agginfo->aggfn.dobj.namespace->dobj.name,
11594 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11601 destroyPQExpBuffer(query);
11602 destroyPQExpBuffer(q);
11603 destroyPQExpBuffer(delq);
11604 destroyPQExpBuffer(labelq);
11605 destroyPQExpBuffer(details);
11610 * write out a single text search parser
11613 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11617 PQExpBuffer labelq;
11619 /* Skip if not to be dumped */
11620 if (!prsinfo->dobj.dump || dataOnly)
11623 q = createPQExpBuffer();
11624 delq = createPQExpBuffer();
11625 labelq = createPQExpBuffer();
11627 /* Make sure we are in proper schema */
11628 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11630 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11631 fmtId(prsinfo->dobj.name));
11633 appendPQExpBuffer(q, " START = %s,\n",
11634 convertTSFunction(fout, prsinfo->prsstart));
11635 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11636 convertTSFunction(fout, prsinfo->prstoken));
11637 appendPQExpBuffer(q, " END = %s,\n",
11638 convertTSFunction(fout, prsinfo->prsend));
11639 if (prsinfo->prsheadline != InvalidOid)
11640 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11641 convertTSFunction(fout, prsinfo->prsheadline));
11642 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11643 convertTSFunction(fout, prsinfo->prslextype));
11646 * DROP must be fully qualified in case same name appears in pg_catalog
11648 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11649 fmtId(prsinfo->dobj.namespace->dobj.name));
11650 appendPQExpBuffer(delq, ".%s;\n",
11651 fmtId(prsinfo->dobj.name));
11653 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11654 fmtId(prsinfo->dobj.name));
11656 if (binary_upgrade)
11657 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11659 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11660 prsinfo->dobj.name,
11661 prsinfo->dobj.namespace->dobj.name,
11664 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11665 q->data, delq->data, NULL,
11669 /* Dump Parser Comments */
11670 dumpComment(fout, labelq->data,
11672 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11674 destroyPQExpBuffer(q);
11675 destroyPQExpBuffer(delq);
11676 destroyPQExpBuffer(labelq);
11681 * write out a single text search dictionary
11684 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11688 PQExpBuffer labelq;
11694 /* Skip if not to be dumped */
11695 if (!dictinfo->dobj.dump || dataOnly)
11698 q = createPQExpBuffer();
11699 delq = createPQExpBuffer();
11700 labelq = createPQExpBuffer();
11701 query = createPQExpBuffer();
11703 /* Fetch name and namespace of the dictionary's template */
11704 selectSourceSchema(fout, "pg_catalog");
11705 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11706 "FROM pg_ts_template p, pg_namespace n "
11707 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11708 dictinfo->dicttemplate);
11709 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11710 nspname = PQgetvalue(res, 0, 0);
11711 tmplname = PQgetvalue(res, 0, 1);
11713 /* Make sure we are in proper schema */
11714 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11716 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11717 fmtId(dictinfo->dobj.name));
11719 appendPQExpBuffer(q, " TEMPLATE = ");
11720 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11721 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11722 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11726 /* the dictinitoption can be dumped straight into the command */
11727 if (dictinfo->dictinitoption)
11728 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11730 appendPQExpBuffer(q, " );\n");
11733 * DROP must be fully qualified in case same name appears in pg_catalog
11735 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11736 fmtId(dictinfo->dobj.namespace->dobj.name));
11737 appendPQExpBuffer(delq, ".%s;\n",
11738 fmtId(dictinfo->dobj.name));
11740 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11741 fmtId(dictinfo->dobj.name));
11743 if (binary_upgrade)
11744 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11746 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11747 dictinfo->dobj.name,
11748 dictinfo->dobj.namespace->dobj.name,
11751 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11752 q->data, delq->data, NULL,
11756 /* Dump Dictionary Comments */
11757 dumpComment(fout, labelq->data,
11758 NULL, dictinfo->rolname,
11759 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11761 destroyPQExpBuffer(q);
11762 destroyPQExpBuffer(delq);
11763 destroyPQExpBuffer(labelq);
11764 destroyPQExpBuffer(query);
11769 * write out a single text search template
11772 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11776 PQExpBuffer labelq;
11778 /* Skip if not to be dumped */
11779 if (!tmplinfo->dobj.dump || dataOnly)
11782 q = createPQExpBuffer();
11783 delq = createPQExpBuffer();
11784 labelq = createPQExpBuffer();
11786 /* Make sure we are in proper schema */
11787 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11789 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11790 fmtId(tmplinfo->dobj.name));
11792 if (tmplinfo->tmplinit != InvalidOid)
11793 appendPQExpBuffer(q, " INIT = %s,\n",
11794 convertTSFunction(fout, tmplinfo->tmplinit));
11795 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11796 convertTSFunction(fout, tmplinfo->tmpllexize));
11799 * DROP must be fully qualified in case same name appears in pg_catalog
11801 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11802 fmtId(tmplinfo->dobj.namespace->dobj.name));
11803 appendPQExpBuffer(delq, ".%s;\n",
11804 fmtId(tmplinfo->dobj.name));
11806 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11807 fmtId(tmplinfo->dobj.name));
11809 if (binary_upgrade)
11810 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11812 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11813 tmplinfo->dobj.name,
11814 tmplinfo->dobj.namespace->dobj.name,
11817 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11818 q->data, delq->data, NULL,
11822 /* Dump Template Comments */
11823 dumpComment(fout, labelq->data,
11825 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11827 destroyPQExpBuffer(q);
11828 destroyPQExpBuffer(delq);
11829 destroyPQExpBuffer(labelq);
11834 * write out a single text search configuration
11837 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11841 PQExpBuffer labelq;
11851 /* Skip if not to be dumped */
11852 if (!cfginfo->dobj.dump || dataOnly)
11855 q = createPQExpBuffer();
11856 delq = createPQExpBuffer();
11857 labelq = createPQExpBuffer();
11858 query = createPQExpBuffer();
11860 /* Fetch name and namespace of the config's parser */
11861 selectSourceSchema(fout, "pg_catalog");
11862 appendPQExpBuffer(query, "SELECT nspname, prsname "
11863 "FROM pg_ts_parser p, pg_namespace n "
11864 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11865 cfginfo->cfgparser);
11866 res = ExecuteSqlQueryForSingleRow(fout, query->data);
11867 nspname = PQgetvalue(res, 0, 0);
11868 prsname = PQgetvalue(res, 0, 1);
11870 /* Make sure we are in proper schema */
11871 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11873 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11874 fmtId(cfginfo->dobj.name));
11876 appendPQExpBuffer(q, " PARSER = ");
11877 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11878 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11879 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11883 resetPQExpBuffer(query);
11884 appendPQExpBuffer(query,
11886 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11887 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11888 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11889 "FROM pg_catalog.pg_ts_config_map AS m \n"
11890 "WHERE m.mapcfg = '%u' \n"
11891 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11892 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11894 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11895 ntups = PQntuples(res);
11897 i_tokenname = PQfnumber(res, "tokenname");
11898 i_dictname = PQfnumber(res, "dictname");
11900 for (i = 0; i < ntups; i++)
11902 char *tokenname = PQgetvalue(res, i, i_tokenname);
11903 char *dictname = PQgetvalue(res, i, i_dictname);
11906 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11908 /* starting a new token type, so start a new command */
11910 appendPQExpBuffer(q, ";\n");
11911 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11912 fmtId(cfginfo->dobj.name));
11913 /* tokenname needs quoting, dictname does NOT */
11914 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11915 fmtId(tokenname), dictname);
11918 appendPQExpBuffer(q, ", %s", dictname);
11922 appendPQExpBuffer(q, ";\n");
11927 * DROP must be fully qualified in case same name appears in pg_catalog
11929 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11930 fmtId(cfginfo->dobj.namespace->dobj.name));
11931 appendPQExpBuffer(delq, ".%s;\n",
11932 fmtId(cfginfo->dobj.name));
11934 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11935 fmtId(cfginfo->dobj.name));
11937 if (binary_upgrade)
11938 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11940 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11941 cfginfo->dobj.name,
11942 cfginfo->dobj.namespace->dobj.name,
11945 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11946 q->data, delq->data, NULL,
11950 /* Dump Configuration Comments */
11951 dumpComment(fout, labelq->data,
11952 NULL, cfginfo->rolname,
11953 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11955 destroyPQExpBuffer(q);
11956 destroyPQExpBuffer(delq);
11957 destroyPQExpBuffer(labelq);
11958 destroyPQExpBuffer(query);
11962 * dumpForeignDataWrapper
11963 * write out a single foreign-data wrapper definition
11966 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11970 PQExpBuffer labelq;
11973 /* Skip if not to be dumped */
11974 if (!fdwinfo->dobj.dump || dataOnly)
11978 * FDWs that belong to an extension are dumped based on their "dump"
11979 * field. Otherwise omit them if we are only dumping some specific object.
11981 if (!fdwinfo->dobj.ext_member)
11982 if (!include_everything)
11985 q = createPQExpBuffer();
11986 delq = createPQExpBuffer();
11987 labelq = createPQExpBuffer();
11989 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11991 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11994 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11995 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11997 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11998 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
12000 if (strlen(fdwinfo->fdwoptions) > 0)
12001 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
12003 appendPQExpBuffer(q, ";\n");
12005 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
12008 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
12011 if (binary_upgrade)
12012 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
12014 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12015 fdwinfo->dobj.name,
12019 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
12020 q->data, delq->data, NULL,
12024 /* Handle the ACL */
12025 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
12026 "FOREIGN DATA WRAPPER",
12027 qfdwname, NULL, fdwinfo->dobj.name,
12028 NULL, fdwinfo->rolname,
12031 /* Dump Foreign Data Wrapper Comments */
12032 dumpComment(fout, labelq->data,
12033 NULL, fdwinfo->rolname,
12034 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
12038 destroyPQExpBuffer(q);
12039 destroyPQExpBuffer(delq);
12040 destroyPQExpBuffer(labelq);
12044 * dumpForeignServer
12045 * write out a foreign server definition
12048 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
12052 PQExpBuffer labelq;
12058 /* Skip if not to be dumped */
12059 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
12062 q = createPQExpBuffer();
12063 delq = createPQExpBuffer();
12064 labelq = createPQExpBuffer();
12065 query = createPQExpBuffer();
12067 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
12069 /* look up the foreign-data wrapper */
12070 selectSourceSchema(fout, "pg_catalog");
12071 appendPQExpBuffer(query, "SELECT fdwname "
12072 "FROM pg_foreign_data_wrapper w "
12073 "WHERE w.oid = '%u'",
12075 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12076 fdwname = PQgetvalue(res, 0, 0);
12078 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
12079 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
12081 appendPQExpBuffer(q, " TYPE ");
12082 appendStringLiteralAH(q, srvinfo->srvtype, fout);
12084 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
12086 appendPQExpBuffer(q, " VERSION ");
12087 appendStringLiteralAH(q, srvinfo->srvversion, fout);
12090 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
12091 appendPQExpBuffer(q, "%s", fmtId(fdwname));
12093 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
12094 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
12096 appendPQExpBuffer(q, ";\n");
12098 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
12101 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
12103 if (binary_upgrade)
12104 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
12106 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12107 srvinfo->dobj.name,
12111 false, "SERVER", SECTION_PRE_DATA,
12112 q->data, delq->data, NULL,
12116 /* Handle the ACL */
12117 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
12119 qsrvname, NULL, srvinfo->dobj.name,
12120 NULL, srvinfo->rolname,
12123 /* Dump user mappings */
12124 dumpUserMappings(fout,
12125 srvinfo->dobj.name, NULL,
12127 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
12129 /* Dump Foreign Server Comments */
12130 dumpComment(fout, labelq->data,
12131 NULL, srvinfo->rolname,
12132 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
12136 destroyPQExpBuffer(q);
12137 destroyPQExpBuffer(delq);
12138 destroyPQExpBuffer(labelq);
12144 * This routine is used to dump any user mappings associated with the
12145 * server handed to this routine. Should be called after ArchiveEntry()
12149 dumpUserMappings(Archive *fout,
12150 const char *servername, const char *namespace,
12152 CatalogId catalogId, DumpId dumpId)
12164 q = createPQExpBuffer();
12165 tag = createPQExpBuffer();
12166 delq = createPQExpBuffer();
12167 query = createPQExpBuffer();
12170 * We read from the publicly accessible view pg_user_mappings, so as not
12171 * to fail if run by a non-superuser. Note that the view will show
12172 * umoptions as null if the user hasn't got privileges for the associated
12173 * server; this means that pg_dump will dump such a mapping, but with no
12174 * OPTIONS clause. A possible alternative is to skip such mappings
12175 * altogether, but it's not clear that that's an improvement.
12177 selectSourceSchema(fout, "pg_catalog");
12179 appendPQExpBuffer(query,
12181 "array_to_string(ARRAY("
12182 "SELECT quote_ident(option_name) || ' ' || "
12183 "quote_literal(option_value) "
12184 "FROM pg_options_to_table(umoptions) "
12185 "ORDER BY option_name"
12186 "), E',\n ') AS umoptions "
12187 "FROM pg_user_mappings "
12188 "WHERE srvid = '%u' "
12189 "ORDER BY usename",
12192 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12194 ntups = PQntuples(res);
12195 i_usename = PQfnumber(res, "usename");
12196 i_umoptions = PQfnumber(res, "umoptions");
12198 for (i = 0; i < ntups; i++)
12203 usename = PQgetvalue(res, i, i_usename);
12204 umoptions = PQgetvalue(res, i, i_umoptions);
12206 resetPQExpBuffer(q);
12207 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
12208 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
12210 if (umoptions && strlen(umoptions) > 0)
12211 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
12213 appendPQExpBuffer(q, ";\n");
12215 resetPQExpBuffer(delq);
12216 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
12217 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
12219 resetPQExpBuffer(tag);
12220 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
12221 usename, servername);
12223 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12228 "USER MAPPING", SECTION_PRE_DATA,
12229 q->data, delq->data, NULL,
12236 destroyPQExpBuffer(query);
12237 destroyPQExpBuffer(delq);
12238 destroyPQExpBuffer(q);
12242 * Write out default privileges information
12245 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
12251 /* Skip if not to be dumped */
12252 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
12255 q = createPQExpBuffer();
12256 tag = createPQExpBuffer();
12258 switch (daclinfo->defaclobjtype)
12260 case DEFACLOBJ_RELATION:
12263 case DEFACLOBJ_SEQUENCE:
12264 type = "SEQUENCES";
12266 case DEFACLOBJ_FUNCTION:
12267 type = "FUNCTIONS";
12269 case DEFACLOBJ_TYPE:
12273 /* shouldn't get here */
12274 exit_horribly(NULL,
12275 "unrecognized object type in default privileges: %d\n",
12276 (int) daclinfo->defaclobjtype);
12277 type = ""; /* keep compiler quiet */
12280 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
12282 /* build the actual command(s) for this tuple */
12283 if (!buildDefaultACLCommands(type,
12284 daclinfo->dobj.namespace != NULL ?
12285 daclinfo->dobj.namespace->dobj.name : NULL,
12286 daclinfo->defaclacl,
12287 daclinfo->defaclrole,
12288 fout->remoteVersion,
12290 exit_horribly(NULL, "could not parse default ACL list (%s)\n",
12291 daclinfo->defaclacl);
12293 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
12295 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
12297 daclinfo->defaclrole,
12298 false, "DEFAULT ACL", SECTION_POST_DATA,
12303 destroyPQExpBuffer(tag);
12304 destroyPQExpBuffer(q);
12308 * Write out grant/revoke information
12310 * 'objCatId' is the catalog ID of the underlying object.
12311 * 'objDumpId' is the dump ID of the underlying object.
12312 * 'type' must be one of
12313 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
12314 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
12315 * 'name' is the formatted name of the object. Must be quoted etc. already.
12316 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
12317 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12318 * 'nspname' is the namespace the object is in (NULL if none).
12319 * 'owner' is the owner, NULL if there is no owner (for languages).
12320 * 'acls' is the string read out of the fooacl system catalog field;
12321 * it will be parsed here.
12325 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12326 const char *type, const char *name, const char *subname,
12327 const char *tag, const char *nspname, const char *owner,
12332 /* Do nothing if ACL dump is not enabled */
12336 /* --data-only skips ACLs *except* BLOB ACLs */
12337 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12340 sql = createPQExpBuffer();
12342 if (!buildACLCommands(name, subname, type, acls, owner,
12343 "", fout->remoteVersion, sql))
12344 exit_horribly(NULL,
12345 "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12349 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12352 owner ? owner : "",
12353 false, "ACL", SECTION_NONE,
12354 sql->data, "", NULL,
12358 destroyPQExpBuffer(sql);
12364 * This routine is used to dump any security labels associated with the
12365 * object handed to this routine. The routine takes a constant character
12366 * string for the target part of the security-label command, plus
12367 * the namespace and owner of the object (for labeling the ArchiveEntry),
12368 * plus catalog ID and subid which are the lookup key for pg_seclabel,
12369 * plus the dump ID for the object (for setting a dependency).
12370 * If a matching pg_seclabel entry is found, it is dumped.
12372 * Note: although this routine takes a dumpId for dependency purposes,
12373 * that purpose is just to mark the dependency in the emitted dump file
12374 * for possible future use by pg_restore. We do NOT use it for determining
12375 * ordering of the label in the dump file, because this routine is called
12376 * after dependency sorting occurs. This routine should be called just after
12377 * calling ArchiveEntry() for the specified object.
12380 dumpSecLabel(Archive *fout, const char *target,
12381 const char *namespace, const char *owner,
12382 CatalogId catalogId, int subid, DumpId dumpId)
12384 SecLabelItem *labels;
12389 /* do nothing, if --no-security-labels is supplied */
12390 if (no_security_labels)
12393 /* Comments are schema not data ... except blob comments are data */
12394 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12405 /* Search for security labels associated with catalogId, using table */
12406 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12408 query = createPQExpBuffer();
12410 for (i = 0; i < nlabels; i++)
12413 * Ignore label entries for which the subid doesn't match.
12415 if (labels[i].objsubid != subid)
12418 appendPQExpBuffer(query,
12419 "SECURITY LABEL FOR %s ON %s IS ",
12420 fmtId(labels[i].provider), target);
12421 appendStringLiteralAH(query, labels[i].label, fout);
12422 appendPQExpBuffer(query, ";\n");
12425 if (query->len > 0)
12427 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12428 target, namespace, NULL, owner,
12429 false, "SECURITY LABEL", SECTION_NONE,
12430 query->data, "", NULL,
12434 destroyPQExpBuffer(query);
12438 * dumpTableSecLabel
12440 * As above, but dump security label for both the specified table (or view)
12444 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12446 SecLabelItem *labels;
12450 PQExpBuffer target;
12452 /* do nothing, if --no-security-labels is supplied */
12453 if (no_security_labels)
12456 /* SecLabel are SCHEMA not data */
12460 /* Search for comments associated with relation, using table */
12461 nlabels = findSecLabels(fout,
12462 tbinfo->dobj.catId.tableoid,
12463 tbinfo->dobj.catId.oid,
12466 /* If security labels exist, build SECURITY LABEL statements */
12470 query = createPQExpBuffer();
12471 target = createPQExpBuffer();
12473 for (i = 0; i < nlabels; i++)
12475 const char *colname;
12476 const char *provider = labels[i].provider;
12477 const char *label = labels[i].label;
12478 int objsubid = labels[i].objsubid;
12480 resetPQExpBuffer(target);
12483 appendPQExpBuffer(target, "%s %s", reltypename,
12484 fmtId(tbinfo->dobj.name));
12488 colname = getAttrName(objsubid, tbinfo);
12489 /* first fmtId result must be consumed before calling it again */
12490 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12491 appendPQExpBuffer(target, ".%s", fmtId(colname));
12493 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12494 fmtId(provider), target->data);
12495 appendStringLiteralAH(query, label, fout);
12496 appendPQExpBuffer(query, ";\n");
12498 if (query->len > 0)
12500 resetPQExpBuffer(target);
12501 appendPQExpBuffer(target, "%s %s", reltypename,
12502 fmtId(tbinfo->dobj.name));
12503 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12505 tbinfo->dobj.namespace->dobj.name,
12506 NULL, tbinfo->rolname,
12507 false, "SECURITY LABEL", SECTION_NONE,
12508 query->data, "", NULL,
12509 &(tbinfo->dobj.dumpId), 1,
12512 destroyPQExpBuffer(query);
12513 destroyPQExpBuffer(target);
12519 * Find the security label(s), if any, associated with the given object.
12520 * All the objsubid values associated with the given classoid/objoid are
12521 * found with one search.
12524 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12526 /* static storage for table of security labels */
12527 static SecLabelItem *labels = NULL;
12528 static int nlabels = -1;
12530 SecLabelItem *middle = NULL;
12532 SecLabelItem *high;
12535 /* Get security labels if we didn't already */
12537 nlabels = collectSecLabels(fout, &labels);
12539 if (nlabels <= 0) /* no labels, so no match is possible */
12546 * Do binary search to find some item matching the object.
12549 high = &labels[nlabels - 1];
12550 while (low <= high)
12552 middle = low + (high - low) / 2;
12554 if (classoid < middle->classoid)
12556 else if (classoid > middle->classoid)
12558 else if (objoid < middle->objoid)
12560 else if (objoid > middle->objoid)
12563 break; /* found a match */
12566 if (low > high) /* no matches */
12573 * Now determine how many items match the object. The search loop
12574 * invariant still holds: only items between low and high inclusive could
12578 while (middle > low)
12580 if (classoid != middle[-1].classoid ||
12581 objoid != middle[-1].objoid)
12590 while (middle <= high)
12592 if (classoid != middle->classoid ||
12593 objoid != middle->objoid)
12605 * Construct a table of all security labels available for database objects.
12606 * It's much faster to pull them all at once.
12608 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12611 collectSecLabels(Archive *fout, SecLabelItem **items)
12622 SecLabelItem *labels;
12624 query = createPQExpBuffer();
12626 appendPQExpBuffer(query,
12627 "SELECT label, provider, classoid, objoid, objsubid "
12628 "FROM pg_catalog.pg_seclabel "
12629 "ORDER BY classoid, objoid, objsubid");
12631 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12633 /* Construct lookup table containing OIDs in numeric form */
12634 i_label = PQfnumber(res, "label");
12635 i_provider = PQfnumber(res, "provider");
12636 i_classoid = PQfnumber(res, "classoid");
12637 i_objoid = PQfnumber(res, "objoid");
12638 i_objsubid = PQfnumber(res, "objsubid");
12640 ntups = PQntuples(res);
12642 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12644 for (i = 0; i < ntups; i++)
12646 labels[i].label = PQgetvalue(res, i, i_label);
12647 labels[i].provider = PQgetvalue(res, i, i_provider);
12648 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12649 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12650 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12653 /* Do NOT free the PGresult since we are keeping pointers into it */
12654 destroyPQExpBuffer(query);
12662 * write out to fout the declarations (not data) of a user-defined table
12665 dumpTable(Archive *fout, TableInfo *tbinfo)
12667 if (tbinfo->dobj.dump && !dataOnly)
12671 if (tbinfo->relkind == RELKIND_SEQUENCE)
12672 dumpSequence(fout, tbinfo);
12674 dumpTableSchema(fout, tbinfo);
12676 /* Handle the ACL here */
12677 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12678 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12679 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12681 namecopy, NULL, tbinfo->dobj.name,
12682 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12686 * Handle column ACLs, if any. Note: we pull these with a separate
12687 * query rather than trying to fetch them during getTableAttrs, so
12688 * that we won't miss ACLs on system columns.
12690 if (fout->remoteVersion >= 80400)
12692 PQExpBuffer query = createPQExpBuffer();
12696 appendPQExpBuffer(query,
12697 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12698 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12700 tbinfo->dobj.catId.oid);
12701 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12703 for (i = 0; i < PQntuples(res); i++)
12705 char *attname = PQgetvalue(res, i, 0);
12706 char *attacl = PQgetvalue(res, i, 1);
12710 attnamecopy = pg_strdup(fmtId(attname));
12711 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12712 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12713 /* Column's GRANT type is always TABLE */
12714 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12715 namecopy, attnamecopy, acltag,
12716 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12722 destroyPQExpBuffer(query);
12730 * Create the AS clause for a view or materialized view. The semicolon is
12731 * stripped because a materialized view must add a WITH NO DATA clause.
12733 * This returns a new buffer which must be freed by the caller.
12736 createViewAsClause(Archive *fout, TableInfo *tbinfo)
12738 PQExpBuffer query = createPQExpBuffer();
12739 PQExpBuffer result = createPQExpBuffer();
12743 /* Fetch the view definition */
12744 if (fout->remoteVersion >= 70300)
12746 /* Beginning in 7.3, viewname is not unique; rely on OID */
12747 appendPQExpBuffer(query,
12748 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12749 tbinfo->dobj.catId.oid);
12753 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12754 "FROM pg_views WHERE viewname = ");
12755 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12756 appendPQExpBuffer(query, ";");
12759 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12761 if (PQntuples(res) != 1)
12763 if (PQntuples(res) < 1)
12764 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12765 tbinfo->dobj.name);
12767 exit_horribly(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12768 tbinfo->dobj.name);
12771 len = PQgetlength(res, 0, 0);
12774 exit_horribly(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12775 tbinfo->dobj.name);
12777 /* Strip off the trailing semicolon so that other things may follow. */
12778 Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
12779 appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
12782 destroyPQExpBuffer(query);
12789 * write the declaration (not data) of one user-defined table or view
12792 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12794 PQExpBuffer q = createPQExpBuffer();
12795 PQExpBuffer delq = createPQExpBuffer();
12796 PQExpBuffer labelq = createPQExpBuffer();
12798 TableInfo **parents;
12799 int actual_atts; /* number of attrs in this CREATE statement */
12800 const char *reltypename;
12807 /* Make sure we are in proper schema */
12808 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12810 if (binary_upgrade)
12811 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12812 tbinfo->dobj.catId.oid);
12814 /* Is it a table or a view? */
12815 if (tbinfo->relkind == RELKIND_VIEW)
12817 PQExpBuffer result;
12819 reltypename = "VIEW";
12822 * DROP must be fully qualified in case same name appears in
12825 appendPQExpBuffer(delq, "DROP VIEW %s.",
12826 fmtId(tbinfo->dobj.namespace->dobj.name));
12827 appendPQExpBuffer(delq, "%s;\n",
12828 fmtId(tbinfo->dobj.name));
12830 if (binary_upgrade)
12831 binary_upgrade_set_pg_class_oids(fout, q,
12832 tbinfo->dobj.catId.oid, false);
12834 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12835 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12836 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12837 result = createViewAsClause(fout, tbinfo);
12838 appendPQExpBuffer(q, " AS\n%s;\n", result->data);
12839 destroyPQExpBuffer(result);
12841 appendPQExpBuffer(labelq, "VIEW %s",
12842 fmtId(tbinfo->dobj.name));
12846 switch (tbinfo->relkind)
12848 case (RELKIND_FOREIGN_TABLE):
12850 PQExpBuffer query = createPQExpBuffer();
12855 reltypename = "FOREIGN TABLE";
12857 /* retrieve name of foreign server and generic options */
12858 appendPQExpBuffer(query,
12859 "SELECT fs.srvname, "
12860 "pg_catalog.array_to_string(ARRAY("
12861 "SELECT pg_catalog.quote_ident(option_name) || "
12862 "' ' || pg_catalog.quote_literal(option_value) "
12863 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12864 "ORDER BY option_name"
12865 "), E',\n ') AS ftoptions "
12866 "FROM pg_catalog.pg_foreign_table ft "
12867 "JOIN pg_catalog.pg_foreign_server fs "
12868 "ON (fs.oid = ft.ftserver) "
12869 "WHERE ft.ftrelid = '%u'",
12870 tbinfo->dobj.catId.oid);
12871 res = ExecuteSqlQueryForSingleRow(fout, query->data);
12872 i_srvname = PQfnumber(res, "srvname");
12873 i_ftoptions = PQfnumber(res, "ftoptions");
12874 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12875 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12877 destroyPQExpBuffer(query);
12880 case (RELKIND_MATVIEW):
12881 reltypename = "MATERIALIZED VIEW";
12886 reltypename = "TABLE";
12891 numParents = tbinfo->numParents;
12892 parents = tbinfo->parents;
12895 * DROP must be fully qualified in case same name appears in
12898 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12899 fmtId(tbinfo->dobj.namespace->dobj.name));
12900 appendPQExpBuffer(delq, "%s;\n",
12901 fmtId(tbinfo->dobj.name));
12903 appendPQExpBuffer(labelq, "%s %s", reltypename,
12904 fmtId(tbinfo->dobj.name));
12906 if (binary_upgrade)
12907 binary_upgrade_set_pg_class_oids(fout, q,
12908 tbinfo->dobj.catId.oid, false);
12910 appendPQExpBuffer(q, "CREATE %s%s %s",
12911 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12914 fmtId(tbinfo->dobj.name));
12917 * Attach to type, if reloftype; except in case of a binary upgrade,
12918 * we dump the table normally and attach it to the type afterward.
12920 if (tbinfo->reloftype && !binary_upgrade)
12921 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12923 if (tbinfo->relkind != RELKIND_MATVIEW)
12925 /* Dump the attributes */
12927 for (j = 0; j < tbinfo->numatts; j++)
12930 * Normally, dump if it's locally defined in this table, and
12931 * not dropped. But for binary upgrade, we'll dump all the
12932 * columns, and then fix up the dropped and nonlocal cases
12935 if (shouldPrintColumn(tbinfo, j))
12938 * Default value --- suppress if to be printed separately.
12940 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12941 !tbinfo->attrdefs[j]->separate);
12944 * Not Null constraint --- suppress if inherited, except
12945 * in binary-upgrade case where that won't work.
12947 bool has_notnull = (tbinfo->notnull[j] &&
12948 (!tbinfo->inhNotNull[j] ||
12951 /* Skip column if fully defined by reloftype */
12952 if (tbinfo->reloftype &&
12953 !has_default && !has_notnull && !binary_upgrade)
12956 /* Format properly if not first attr */
12957 if (actual_atts == 0)
12958 appendPQExpBuffer(q, " (");
12960 appendPQExpBuffer(q, ",");
12961 appendPQExpBuffer(q, "\n ");
12964 /* Attribute name */
12965 appendPQExpBuffer(q, "%s",
12966 fmtId(tbinfo->attnames[j]));
12968 if (tbinfo->attisdropped[j])
12971 * ALTER TABLE DROP COLUMN clears
12972 * pg_attribute.atttypid, so we will not have gotten a
12973 * valid type name; insert INTEGER as a stopgap. We'll
12974 * clean things up later.
12976 appendPQExpBuffer(q, " INTEGER /* dummy */");
12977 /* Skip all the rest, too */
12981 /* Attribute type */
12982 if (tbinfo->reloftype && !binary_upgrade)
12984 appendPQExpBuffer(q, " WITH OPTIONS");
12986 else if (fout->remoteVersion >= 70100)
12988 appendPQExpBuffer(q, " %s",
12989 tbinfo->atttypnames[j]);
12993 /* If no format_type, fake it */
12994 appendPQExpBuffer(q, " %s",
12995 myFormatType(tbinfo->atttypnames[j],
12996 tbinfo->atttypmod[j]));
12999 /* Add collation if not default for the type */
13000 if (OidIsValid(tbinfo->attcollation[j]))
13004 coll = findCollationByOid(tbinfo->attcollation[j]);
13007 /* always schema-qualify, don't try to be smart */
13008 appendPQExpBuffer(q, " COLLATE %s.",
13009 fmtId(coll->dobj.namespace->dobj.name));
13010 appendPQExpBuffer(q, "%s",
13011 fmtId(coll->dobj.name));
13016 appendPQExpBuffer(q, " DEFAULT %s",
13017 tbinfo->attrdefs[j]->adef_expr);
13020 appendPQExpBuffer(q, " NOT NULL");
13025 * Add non-inherited CHECK constraints, if any.
13027 for (j = 0; j < tbinfo->ncheck; j++)
13029 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13031 if (constr->separate || !constr->conislocal)
13034 if (actual_atts == 0)
13035 appendPQExpBuffer(q, " (\n ");
13037 appendPQExpBuffer(q, ",\n ");
13039 appendPQExpBuffer(q, "CONSTRAINT %s ",
13040 fmtId(constr->dobj.name));
13041 appendPQExpBuffer(q, "%s", constr->condef);
13047 appendPQExpBuffer(q, "\n)");
13048 else if (!(tbinfo->reloftype && !binary_upgrade))
13051 * We must have a parenthesized attribute list, even though
13052 * empty, when not using the OF TYPE syntax.
13054 appendPQExpBuffer(q, " (\n)");
13057 if (numParents > 0 && !binary_upgrade)
13059 appendPQExpBuffer(q, "\nINHERITS (");
13060 for (k = 0; k < numParents; k++)
13062 TableInfo *parentRel = parents[k];
13065 appendPQExpBuffer(q, ", ");
13066 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13067 appendPQExpBuffer(q, "%s.",
13068 fmtId(parentRel->dobj.namespace->dobj.name));
13069 appendPQExpBuffer(q, "%s",
13070 fmtId(parentRel->dobj.name));
13072 appendPQExpBuffer(q, ")");
13075 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
13076 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
13079 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
13080 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
13082 bool addcomma = false;
13084 appendPQExpBuffer(q, "\nWITH (");
13085 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
13088 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
13090 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
13092 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
13093 tbinfo->toast_reloptions);
13095 appendPQExpBuffer(q, ")");
13098 /* Dump generic options if any */
13099 if (ftoptions && ftoptions[0])
13100 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
13103 * For materialized views, create the AS clause just like a view.
13105 if (tbinfo->relkind == RELKIND_MATVIEW)
13107 PQExpBuffer result;
13109 result = createViewAsClause(fout, tbinfo);
13110 appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
13112 destroyPQExpBuffer(result);
13115 appendPQExpBuffer(q, ";\n");
13118 * To create binary-compatible heap files, we have to ensure the same
13119 * physical column order, including dropped columns, as in the
13120 * original. Therefore, we create dropped columns above and drop them
13121 * here, also updating their attlen/attalign values so that the
13122 * dropped column can be skipped properly. (We do not bother with
13123 * restoring the original attbyval setting.) Also, inheritance
13124 * relationships are set up by doing ALTER INHERIT rather than using
13125 * an INHERITS clause --- the latter would possibly mess up the column
13126 * order. That also means we have to take care about setting
13127 * attislocal correctly, plus fix up any inherited CHECK constraints.
13128 * Analogously, we set up typed tables using ALTER TABLE / OF here.
13130 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
13132 for (j = 0; j < tbinfo->numatts; j++)
13134 if (tbinfo->attisdropped[j])
13136 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
13137 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13138 "SET attlen = %d, "
13139 "attalign = '%c', attbyval = false\n"
13140 "WHERE attname = ",
13142 tbinfo->attalign[j]);
13143 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13144 appendPQExpBuffer(q, "\n AND attrelid = ");
13145 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13146 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13148 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13149 fmtId(tbinfo->dobj.name));
13150 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
13151 fmtId(tbinfo->attnames[j]));
13153 else if (!tbinfo->attislocal[j])
13155 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
13156 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
13157 "SET attislocal = false\n"
13158 "WHERE attname = ");
13159 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
13160 appendPQExpBuffer(q, "\n AND attrelid = ");
13161 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13162 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13166 for (k = 0; k < tbinfo->ncheck; k++)
13168 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
13170 if (constr->separate || constr->conislocal)
13173 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
13174 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13175 fmtId(tbinfo->dobj.name));
13176 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13177 fmtId(constr->dobj.name));
13178 appendPQExpBuffer(q, "%s;\n", constr->condef);
13179 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
13180 "SET conislocal = false\n"
13181 "WHERE contype = 'c' AND conname = ");
13182 appendStringLiteralAH(q, constr->dobj.name, fout);
13183 appendPQExpBuffer(q, "\n AND conrelid = ");
13184 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13185 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13188 if (numParents > 0)
13190 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
13191 for (k = 0; k < numParents; k++)
13193 TableInfo *parentRel = parents[k];
13195 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
13196 fmtId(tbinfo->dobj.name));
13197 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
13198 appendPQExpBuffer(q, "%s.",
13199 fmtId(parentRel->dobj.namespace->dobj.name));
13200 appendPQExpBuffer(q, "%s;\n",
13201 fmtId(parentRel->dobj.name));
13205 if (tbinfo->reloftype)
13207 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
13208 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
13209 fmtId(tbinfo->dobj.name),
13210 tbinfo->reloftype);
13213 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
13214 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13215 "SET relfrozenxid = '%u'\n"
13217 tbinfo->frozenxid);
13218 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
13219 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
13221 if (tbinfo->toast_oid)
13223 /* We preserve the toast oids, so we can use it during restore */
13224 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
13225 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
13226 "SET relfrozenxid = '%u'\n"
13227 "WHERE oid = '%u';\n",
13228 tbinfo->toast_frozenxid, tbinfo->toast_oid);
13233 * Dump additional per-column properties that we can't handle in the
13234 * main CREATE TABLE command.
13236 for (j = 0; j < tbinfo->numatts; j++)
13238 /* None of this applies to dropped columns */
13239 if (tbinfo->attisdropped[j])
13243 * If we didn't dump the column definition explicitly above, and
13244 * it is NOT NULL and did not inherit that property from a parent,
13245 * we have to mark it separately.
13247 if (!shouldPrintColumn(tbinfo, j) &&
13248 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
13250 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13251 fmtId(tbinfo->dobj.name));
13252 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
13253 fmtId(tbinfo->attnames[j]));
13257 * Dump per-column statistics information. We only issue an ALTER
13258 * TABLE statement if the attstattarget entry for this column is
13259 * non-negative (i.e. it's not the default value)
13261 if (tbinfo->attstattarget[j] >= 0)
13263 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13264 fmtId(tbinfo->dobj.name));
13265 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13266 fmtId(tbinfo->attnames[j]));
13267 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
13268 tbinfo->attstattarget[j]);
13272 * Dump per-column storage information. The statement is only
13273 * dumped if the storage has been changed from the type's default.
13275 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
13277 switch (tbinfo->attstorage[j])
13283 storage = "EXTERNAL";
13289 storage = "EXTENDED";
13296 * Only dump the statement if it's a storage type we recognize
13298 if (storage != NULL)
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 STORAGE %s;\n",
13310 * Dump per-column attributes.
13312 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
13314 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13315 fmtId(tbinfo->dobj.name));
13316 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13317 fmtId(tbinfo->attnames[j]));
13318 appendPQExpBuffer(q, "SET (%s);\n",
13319 tbinfo->attoptions[j]);
13323 * Dump per-column fdw options.
13325 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
13326 tbinfo->attfdwoptions[j] &&
13327 tbinfo->attfdwoptions[j][0] != '\0')
13329 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
13330 fmtId(tbinfo->dobj.name));
13331 appendPQExpBuffer(q, "ALTER COLUMN %s ",
13332 fmtId(tbinfo->attnames[j]));
13333 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
13334 tbinfo->attfdwoptions[j]);
13339 if (binary_upgrade)
13340 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
13342 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13344 tbinfo->dobj.namespace->dobj.name,
13345 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
13347 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
13348 reltypename, SECTION_PRE_DATA,
13349 q->data, delq->data, NULL,
13354 /* Dump Table Comments */
13355 dumpTableComment(fout, tbinfo, reltypename);
13357 /* Dump Table Security Labels */
13358 dumpTableSecLabel(fout, tbinfo, reltypename);
13360 /* Dump comments on inlined table constraints */
13361 for (j = 0; j < tbinfo->ncheck; j++)
13363 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13365 if (constr->separate || !constr->conislocal)
13368 dumpTableConstraintComment(fout, constr);
13371 destroyPQExpBuffer(q);
13372 destroyPQExpBuffer(delq);
13373 destroyPQExpBuffer(labelq);
13377 * dumpAttrDef --- dump an attribute's default-value declaration
13380 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13382 TableInfo *tbinfo = adinfo->adtable;
13383 int adnum = adinfo->adnum;
13387 /* Skip if table definition not to be dumped */
13388 if (!tbinfo->dobj.dump || dataOnly)
13391 /* Skip if not "separate"; it was dumped in the table's definition */
13392 if (!adinfo->separate)
13395 q = createPQExpBuffer();
13396 delq = createPQExpBuffer();
13398 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13399 fmtId(tbinfo->dobj.name));
13400 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13401 fmtId(tbinfo->attnames[adnum - 1]),
13402 adinfo->adef_expr);
13405 * DROP must be fully qualified in case same name appears in pg_catalog
13407 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13408 fmtId(tbinfo->dobj.namespace->dobj.name));
13409 appendPQExpBuffer(delq, "%s ",
13410 fmtId(tbinfo->dobj.name));
13411 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13412 fmtId(tbinfo->attnames[adnum - 1]));
13414 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13415 tbinfo->attnames[adnum - 1],
13416 tbinfo->dobj.namespace->dobj.name,
13419 false, "DEFAULT", SECTION_PRE_DATA,
13420 q->data, delq->data, NULL,
13424 destroyPQExpBuffer(q);
13425 destroyPQExpBuffer(delq);
13429 * getAttrName: extract the correct name for an attribute
13431 * The array tblInfo->attnames[] only provides names of user attributes;
13432 * if a system attribute number is supplied, we have to fake it.
13433 * We also do a little bit of bounds checking for safety's sake.
13435 static const char *
13436 getAttrName(int attrnum, TableInfo *tblInfo)
13438 if (attrnum > 0 && attrnum <= tblInfo->numatts)
13439 return tblInfo->attnames[attrnum - 1];
13442 case SelfItemPointerAttributeNumber:
13444 case ObjectIdAttributeNumber:
13446 case MinTransactionIdAttributeNumber:
13448 case MinCommandIdAttributeNumber:
13450 case MaxTransactionIdAttributeNumber:
13452 case MaxCommandIdAttributeNumber:
13454 case TableOidAttributeNumber:
13457 exit_horribly(NULL, "invalid column number %d for table \"%s\"\n",
13458 attrnum, tblInfo->dobj.name);
13459 return NULL; /* keep compiler quiet */
13464 * write out to fout a user-defined index
13467 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13469 TableInfo *tbinfo = indxinfo->indextable;
13472 PQExpBuffer labelq;
13477 q = createPQExpBuffer();
13478 delq = createPQExpBuffer();
13479 labelq = createPQExpBuffer();
13481 appendPQExpBuffer(labelq, "INDEX %s",
13482 fmtId(indxinfo->dobj.name));
13485 * If there's an associated constraint, don't dump the index per se, but
13486 * do dump any comment for it. (This is safe because dependency ordering
13487 * will have ensured the constraint is emitted first.)
13489 if (indxinfo->indexconstraint == 0)
13491 if (binary_upgrade)
13492 binary_upgrade_set_pg_class_oids(fout, q,
13493 indxinfo->dobj.catId.oid, true);
13495 /* Plain secondary index */
13496 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13498 /* If the index is clustered, we need to record that. */
13499 if (indxinfo->indisclustered)
13501 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13502 fmtId(tbinfo->dobj.name));
13503 appendPQExpBuffer(q, " ON %s;\n",
13504 fmtId(indxinfo->dobj.name));
13508 * DROP must be fully qualified in case same name appears in
13511 appendPQExpBuffer(delq, "DROP INDEX %s.",
13512 fmtId(tbinfo->dobj.namespace->dobj.name));
13513 appendPQExpBuffer(delq, "%s;\n",
13514 fmtId(indxinfo->dobj.name));
13516 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13517 indxinfo->dobj.name,
13518 tbinfo->dobj.namespace->dobj.name,
13519 indxinfo->tablespace,
13520 tbinfo->rolname, false,
13521 "INDEX", SECTION_POST_DATA,
13522 q->data, delq->data, NULL,
13527 /* Dump Index Comments */
13528 dumpComment(fout, labelq->data,
13529 tbinfo->dobj.namespace->dobj.name,
13531 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13533 destroyPQExpBuffer(q);
13534 destroyPQExpBuffer(delq);
13535 destroyPQExpBuffer(labelq);
13540 * write out to fout a user-defined constraint
13543 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13545 TableInfo *tbinfo = coninfo->contable;
13549 /* Skip if not to be dumped */
13550 if (!coninfo->dobj.dump || dataOnly)
13553 q = createPQExpBuffer();
13554 delq = createPQExpBuffer();
13556 if (coninfo->contype == 'p' ||
13557 coninfo->contype == 'u' ||
13558 coninfo->contype == 'x')
13560 /* Index-related constraint */
13561 IndxInfo *indxinfo;
13564 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13566 if (indxinfo == NULL)
13567 exit_horribly(NULL, "missing index for constraint \"%s\"\n",
13568 coninfo->dobj.name);
13570 if (binary_upgrade)
13571 binary_upgrade_set_pg_class_oids(fout, q,
13572 indxinfo->dobj.catId.oid, true);
13574 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13575 fmtId(tbinfo->dobj.name));
13576 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13577 fmtId(coninfo->dobj.name));
13579 if (coninfo->condef)
13581 /* pg_get_constraintdef should have provided everything */
13582 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13586 appendPQExpBuffer(q, "%s (",
13587 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13588 for (k = 0; k < indxinfo->indnkeys; k++)
13590 int indkey = (int) indxinfo->indkeys[k];
13591 const char *attname;
13593 if (indkey == InvalidAttrNumber)
13595 attname = getAttrName(indkey, tbinfo);
13597 appendPQExpBuffer(q, "%s%s",
13598 (k == 0) ? "" : ", ",
13602 appendPQExpBuffer(q, ")");
13604 if (indxinfo->options && strlen(indxinfo->options) > 0)
13605 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13607 if (coninfo->condeferrable)
13609 appendPQExpBuffer(q, " DEFERRABLE");
13610 if (coninfo->condeferred)
13611 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13614 appendPQExpBuffer(q, ";\n");
13617 /* If the index is clustered, we need to record that. */
13618 if (indxinfo->indisclustered)
13620 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13621 fmtId(tbinfo->dobj.name));
13622 appendPQExpBuffer(q, " ON %s;\n",
13623 fmtId(indxinfo->dobj.name));
13627 * DROP must be fully qualified in case same name appears in
13630 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13631 fmtId(tbinfo->dobj.namespace->dobj.name));
13632 appendPQExpBuffer(delq, "%s ",
13633 fmtId(tbinfo->dobj.name));
13634 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13635 fmtId(coninfo->dobj.name));
13637 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13638 coninfo->dobj.name,
13639 tbinfo->dobj.namespace->dobj.name,
13640 indxinfo->tablespace,
13641 tbinfo->rolname, false,
13642 "CONSTRAINT", SECTION_POST_DATA,
13643 q->data, delq->data, NULL,
13647 else if (coninfo->contype == 'f')
13650 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13651 * current table data is not processed
13653 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13654 fmtId(tbinfo->dobj.name));
13655 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13656 fmtId(coninfo->dobj.name),
13660 * DROP must be fully qualified in case same name appears in
13663 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13664 fmtId(tbinfo->dobj.namespace->dobj.name));
13665 appendPQExpBuffer(delq, "%s ",
13666 fmtId(tbinfo->dobj.name));
13667 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13668 fmtId(coninfo->dobj.name));
13670 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13671 coninfo->dobj.name,
13672 tbinfo->dobj.namespace->dobj.name,
13674 tbinfo->rolname, false,
13675 "FK CONSTRAINT", SECTION_POST_DATA,
13676 q->data, delq->data, NULL,
13680 else if (coninfo->contype == 'c' && tbinfo)
13682 /* CHECK constraint on a table */
13684 /* Ignore if not to be dumped separately */
13685 if (coninfo->separate)
13687 /* not ONLY since we want it to propagate to children */
13688 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13689 fmtId(tbinfo->dobj.name));
13690 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13691 fmtId(coninfo->dobj.name),
13695 * DROP must be fully qualified in case same name appears in
13698 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13699 fmtId(tbinfo->dobj.namespace->dobj.name));
13700 appendPQExpBuffer(delq, "%s ",
13701 fmtId(tbinfo->dobj.name));
13702 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13703 fmtId(coninfo->dobj.name));
13705 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13706 coninfo->dobj.name,
13707 tbinfo->dobj.namespace->dobj.name,
13709 tbinfo->rolname, false,
13710 "CHECK CONSTRAINT", SECTION_POST_DATA,
13711 q->data, delq->data, NULL,
13716 else if (coninfo->contype == 'c' && tbinfo == NULL)
13718 /* CHECK constraint on a domain */
13719 TypeInfo *tyinfo = coninfo->condomain;
13721 /* Ignore if not to be dumped separately */
13722 if (coninfo->separate)
13724 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13725 fmtId(tyinfo->dobj.name));
13726 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13727 fmtId(coninfo->dobj.name),
13731 * DROP must be fully qualified in case same name appears in
13734 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13735 fmtId(tyinfo->dobj.namespace->dobj.name));
13736 appendPQExpBuffer(delq, "%s ",
13737 fmtId(tyinfo->dobj.name));
13738 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13739 fmtId(coninfo->dobj.name));
13741 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13742 coninfo->dobj.name,
13743 tyinfo->dobj.namespace->dobj.name,
13745 tyinfo->rolname, false,
13746 "CHECK CONSTRAINT", SECTION_POST_DATA,
13747 q->data, delq->data, NULL,
13754 exit_horribly(NULL, "unrecognized constraint type: %c\n",
13758 /* Dump Constraint Comments --- only works for table constraints */
13759 if (tbinfo && coninfo->separate)
13760 dumpTableConstraintComment(fout, coninfo);
13762 destroyPQExpBuffer(q);
13763 destroyPQExpBuffer(delq);
13767 * dumpTableConstraintComment --- dump a constraint's comment if any
13769 * This is split out because we need the function in two different places
13770 * depending on whether the constraint is dumped as part of CREATE TABLE
13771 * or as a separate ALTER command.
13774 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13776 TableInfo *tbinfo = coninfo->contable;
13777 PQExpBuffer labelq = createPQExpBuffer();
13779 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13780 fmtId(coninfo->dobj.name));
13781 appendPQExpBuffer(labelq, "ON %s",
13782 fmtId(tbinfo->dobj.name));
13783 dumpComment(fout, labelq->data,
13784 tbinfo->dobj.namespace->dobj.name,
13786 coninfo->dobj.catId, 0,
13787 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13789 destroyPQExpBuffer(labelq);
13793 * findLastBuiltInOid -
13794 * find the last built in oid
13796 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13797 * pg_database entry for the current database
13800 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13804 PQExpBuffer query = createPQExpBuffer();
13806 resetPQExpBuffer(query);
13807 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13808 appendStringLiteralAH(query, dbname, fout);
13810 res = ExecuteSqlQueryForSingleRow(fout, query->data);
13811 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13813 destroyPQExpBuffer(query);
13818 * findLastBuiltInOid -
13819 * find the last built in oid
13821 * For 7.0, we do this by assuming that the last thing that initdb does is to
13822 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13823 * initdb won't be changing anymore, it'll do.
13826 findLastBuiltinOid_V70(Archive *fout)
13831 res = ExecuteSqlQueryForSingleRow(fout,
13832 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13833 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13840 * write the declaration (not data) of one user-defined sequence
13843 dumpSequence(Archive *fout, TableInfo *tbinfo)
13854 PQExpBuffer query = createPQExpBuffer();
13855 PQExpBuffer delqry = createPQExpBuffer();
13856 PQExpBuffer labelq = createPQExpBuffer();
13858 /* Make sure we are in proper schema */
13859 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13861 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13862 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13864 if (fout->remoteVersion >= 80400)
13866 appendPQExpBuffer(query,
13867 "SELECT sequence_name, "
13868 "start_value, increment_by, "
13869 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13870 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13872 "END AS max_value, "
13873 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13874 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13876 "END AS min_value, "
13877 "cache_value, is_cycled FROM %s",
13879 fmtId(tbinfo->dobj.name));
13883 appendPQExpBuffer(query,
13884 "SELECT sequence_name, "
13885 "0 AS start_value, increment_by, "
13886 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13887 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13889 "END AS max_value, "
13890 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13891 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13893 "END AS min_value, "
13894 "cache_value, is_cycled FROM %s",
13896 fmtId(tbinfo->dobj.name));
13899 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13901 if (PQntuples(res) != 1)
13903 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13904 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13906 tbinfo->dobj.name, PQntuples(res));
13910 /* Disable this check: it fails if sequence has been renamed */
13912 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13914 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13915 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13920 startv = PQgetvalue(res, 0, 1);
13921 incby = PQgetvalue(res, 0, 2);
13922 if (!PQgetisnull(res, 0, 3))
13923 maxv = PQgetvalue(res, 0, 3);
13924 if (!PQgetisnull(res, 0, 4))
13925 minv = PQgetvalue(res, 0, 4);
13926 cache = PQgetvalue(res, 0, 5);
13927 cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
13930 * DROP must be fully qualified in case same name appears in pg_catalog
13932 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13933 fmtId(tbinfo->dobj.namespace->dobj.name));
13934 appendPQExpBuffer(delqry, "%s;\n",
13935 fmtId(tbinfo->dobj.name));
13937 resetPQExpBuffer(query);
13939 if (binary_upgrade)
13941 binary_upgrade_set_pg_class_oids(fout, query,
13942 tbinfo->dobj.catId.oid, false);
13943 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13944 tbinfo->dobj.catId.oid);
13947 appendPQExpBuffer(query,
13948 "CREATE SEQUENCE %s\n",
13949 fmtId(tbinfo->dobj.name));
13951 if (fout->remoteVersion >= 80400)
13952 appendPQExpBuffer(query, " START WITH %s\n", startv);
13954 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13957 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13959 appendPQExpBuffer(query, " NO MINVALUE\n");
13962 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13964 appendPQExpBuffer(query, " NO MAXVALUE\n");
13966 appendPQExpBuffer(query,
13968 cache, (cycled ? "\n CYCLE" : ""));
13970 appendPQExpBuffer(query, ";\n");
13972 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13974 /* binary_upgrade: no need to clear TOAST table oid */
13976 if (binary_upgrade)
13977 binary_upgrade_extension_member(query, &tbinfo->dobj,
13980 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13982 tbinfo->dobj.namespace->dobj.name,
13985 false, "SEQUENCE", SECTION_PRE_DATA,
13986 query->data, delqry->data, NULL,
13991 * If the sequence is owned by a table column, emit the ALTER for it as a
13992 * separate TOC entry immediately following the sequence's own entry. It's
13993 * OK to do this rather than using full sorting logic, because the
13994 * dependency that tells us it's owned will have forced the table to be
13995 * created first. We can't just include the ALTER in the TOC entry
13996 * because it will fail if we haven't reassigned the sequence owner to
13997 * match the table's owner.
13999 * We need not schema-qualify the table reference because both sequence
14000 * and table must be in the same schema.
14002 if (OidIsValid(tbinfo->owning_tab))
14004 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
14006 if (owning_tab && owning_tab->dobj.dump)
14008 resetPQExpBuffer(query);
14009 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
14010 fmtId(tbinfo->dobj.name));
14011 appendPQExpBuffer(query, " OWNED BY %s",
14012 fmtId(owning_tab->dobj.name));
14013 appendPQExpBuffer(query, ".%s;\n",
14014 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
14016 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14018 tbinfo->dobj.namespace->dobj.name,
14021 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
14022 query->data, "", NULL,
14023 &(tbinfo->dobj.dumpId), 1,
14028 /* Dump Sequence Comments and Security Labels */
14029 dumpComment(fout, labelq->data,
14030 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14031 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14032 dumpSecLabel(fout, labelq->data,
14033 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14034 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
14038 destroyPQExpBuffer(query);
14039 destroyPQExpBuffer(delqry);
14040 destroyPQExpBuffer(labelq);
14045 * write the data of one user-defined sequence
14048 dumpSequenceData(Archive *fout, TableDataInfo *tdinfo)
14050 TableInfo *tbinfo = tdinfo->tdtable;
14054 PQExpBuffer query = createPQExpBuffer();
14056 /* Make sure we are in proper schema */
14057 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14059 appendPQExpBuffer(query,
14060 "SELECT last_value, is_called FROM %s",
14061 fmtId(tbinfo->dobj.name));
14063 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14065 if (PQntuples(res) != 1)
14067 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
14068 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
14070 tbinfo->dobj.name, PQntuples(res));
14074 last = PQgetvalue(res, 0, 0);
14075 called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
14077 resetPQExpBuffer(query);
14078 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
14079 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
14080 appendPQExpBuffer(query, ", %s, %s);\n",
14081 last, (called ? "true" : "false"));
14083 ArchiveEntry(fout, nilCatalogId, createDumpId(),
14085 tbinfo->dobj.namespace->dobj.name,
14088 false, "SEQUENCE SET", SECTION_DATA,
14089 query->data, "", NULL,
14090 &(tbinfo->dobj.dumpId), 1,
14095 destroyPQExpBuffer(query);
14099 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
14101 TableInfo *tbinfo = tginfo->tgtable;
14103 PQExpBuffer delqry;
14104 PQExpBuffer labelq;
14113 query = createPQExpBuffer();
14114 delqry = createPQExpBuffer();
14115 labelq = createPQExpBuffer();
14118 * DROP must be fully qualified in case same name appears in pg_catalog
14120 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
14121 fmtId(tginfo->dobj.name));
14122 appendPQExpBuffer(delqry, "ON %s.",
14123 fmtId(tbinfo->dobj.namespace->dobj.name));
14124 appendPQExpBuffer(delqry, "%s;\n",
14125 fmtId(tbinfo->dobj.name));
14129 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
14133 if (tginfo->tgisconstraint)
14135 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
14136 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
14140 appendPQExpBuffer(query, "CREATE TRIGGER ");
14141 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
14143 appendPQExpBuffer(query, "\n ");
14146 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
14147 appendPQExpBuffer(query, "BEFORE");
14148 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
14149 appendPQExpBuffer(query, "AFTER");
14150 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
14151 appendPQExpBuffer(query, "INSTEAD OF");
14154 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
14159 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
14161 appendPQExpBuffer(query, " INSERT");
14164 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
14167 appendPQExpBuffer(query, " OR DELETE");
14169 appendPQExpBuffer(query, " DELETE");
14172 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
14175 appendPQExpBuffer(query, " OR UPDATE");
14177 appendPQExpBuffer(query, " UPDATE");
14180 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
14183 appendPQExpBuffer(query, " OR TRUNCATE");
14185 appendPQExpBuffer(query, " TRUNCATE");
14188 appendPQExpBuffer(query, " ON %s\n",
14189 fmtId(tbinfo->dobj.name));
14191 if (tginfo->tgisconstraint)
14193 if (OidIsValid(tginfo->tgconstrrelid))
14195 /* If we are using regclass, name is already quoted */
14196 if (fout->remoteVersion >= 70300)
14197 appendPQExpBuffer(query, " FROM %s\n ",
14198 tginfo->tgconstrrelname);
14200 appendPQExpBuffer(query, " FROM %s\n ",
14201 fmtId(tginfo->tgconstrrelname));
14203 if (!tginfo->tgdeferrable)
14204 appendPQExpBuffer(query, "NOT ");
14205 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
14206 if (tginfo->tginitdeferred)
14207 appendPQExpBuffer(query, "DEFERRED\n");
14209 appendPQExpBuffer(query, "IMMEDIATE\n");
14212 if (TRIGGER_FOR_ROW(tginfo->tgtype))
14213 appendPQExpBuffer(query, " FOR EACH ROW\n ");
14215 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
14217 /* In 7.3, result of regproc is already quoted */
14218 if (fout->remoteVersion >= 70300)
14219 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14222 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
14223 fmtId(tginfo->tgfname));
14225 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
14228 for (findx = 0; findx < tginfo->tgnargs; findx++)
14230 /* find the embedded null that terminates this trigger argument */
14231 size_t tlen = strlen(p);
14233 if (p + tlen >= tgargs + lentgargs)
14235 /* hm, not found before end of bytea value... */
14236 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
14239 tbinfo->dobj.name);
14244 appendPQExpBuffer(query, ", ");
14245 appendStringLiteralAH(query, p, fout);
14249 appendPQExpBuffer(query, ");\n");
14252 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
14254 appendPQExpBuffer(query, "\nALTER TABLE %s ",
14255 fmtId(tbinfo->dobj.name));
14256 switch (tginfo->tgenabled)
14260 appendPQExpBuffer(query, "DISABLE");
14263 appendPQExpBuffer(query, "ENABLE ALWAYS");
14266 appendPQExpBuffer(query, "ENABLE REPLICA");
14269 appendPQExpBuffer(query, "ENABLE");
14272 appendPQExpBuffer(query, " TRIGGER %s;\n",
14273 fmtId(tginfo->dobj.name));
14276 appendPQExpBuffer(labelq, "TRIGGER %s ",
14277 fmtId(tginfo->dobj.name));
14278 appendPQExpBuffer(labelq, "ON %s",
14279 fmtId(tbinfo->dobj.name));
14281 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
14283 tbinfo->dobj.namespace->dobj.name,
14285 tbinfo->rolname, false,
14286 "TRIGGER", SECTION_POST_DATA,
14287 query->data, delqry->data, NULL,
14291 dumpComment(fout, labelq->data,
14292 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
14293 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
14295 destroyPQExpBuffer(query);
14296 destroyPQExpBuffer(delqry);
14297 destroyPQExpBuffer(labelq);
14301 dumpEventTrigger(Archive *fout, EventTriggerInfo *evtinfo)
14304 PQExpBuffer labelq;
14306 query = createPQExpBuffer();
14307 labelq = createPQExpBuffer();
14309 appendPQExpBuffer(query, "CREATE EVENT TRIGGER ");
14310 appendPQExpBufferStr(query, fmtId(evtinfo->dobj.name));
14311 appendPQExpBuffer(query, " ON ");
14312 appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
14313 appendPQExpBufferStr(query, " ");
14315 if (strcmp("", evtinfo->evttags) != 0)
14317 appendPQExpBufferStr(query, "\n WHEN TAG IN (");
14318 appendPQExpBufferStr(query, evtinfo->evttags);
14319 appendPQExpBufferStr(query, ") ");
14322 appendPQExpBuffer(query, "\n EXECUTE PROCEDURE ");
14323 appendPQExpBufferStr(query, evtinfo->evtfname);
14324 appendPQExpBuffer(query, "();\n");
14326 if (evtinfo->evtenabled != 'O')
14328 appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
14329 fmtId(evtinfo->dobj.name));
14330 switch (evtinfo->evtenabled)
14333 appendPQExpBuffer(query, "DISABLE");
14336 appendPQExpBuffer(query, "ENABLE ALWAYS");
14339 appendPQExpBuffer(query, "ENABLE REPLICA");
14342 appendPQExpBuffer(query, "ENABLE");
14345 appendPQExpBuffer(query, ";\n");
14347 appendPQExpBuffer(labelq, "EVENT TRIGGER %s ",
14348 fmtId(evtinfo->dobj.name));
14350 ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
14351 evtinfo->dobj.name, NULL, NULL, evtinfo->evtowner, false,
14352 "EVENT TRIGGER", SECTION_POST_DATA,
14353 query->data, "", NULL, NULL, 0, NULL, NULL);
14355 dumpComment(fout, labelq->data,
14357 evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
14359 destroyPQExpBuffer(query);
14360 destroyPQExpBuffer(labelq);
14368 dumpRule(Archive *fout, RuleInfo *rinfo)
14370 TableInfo *tbinfo = rinfo->ruletable;
14373 PQExpBuffer delcmd;
14374 PQExpBuffer labelq;
14377 /* Skip if not to be dumped */
14378 if (!rinfo->dobj.dump || dataOnly)
14382 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
14383 * we do not want to dump it as a separate object.
14385 if (!rinfo->separate)
14389 * Make sure we are in proper schema.
14391 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
14393 query = createPQExpBuffer();
14394 cmd = createPQExpBuffer();
14395 delcmd = createPQExpBuffer();
14396 labelq = createPQExpBuffer();
14398 if (fout->remoteVersion >= 70300)
14400 appendPQExpBuffer(query,
14401 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14402 rinfo->dobj.catId.oid);
14406 /* Rule name was unique before 7.3 ... */
14407 appendPQExpBuffer(query,
14408 "SELECT pg_get_ruledef('%s') AS definition",
14412 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14414 if (PQntuples(res) != 1)
14416 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14417 rinfo->dobj.name, tbinfo->dobj.name);
14421 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14424 * Add the command to alter the rules replication firing semantics if it
14425 * differs from the default.
14427 if (rinfo->ev_enabled != 'O')
14429 appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtId(tbinfo->dobj.name));
14430 switch (rinfo->ev_enabled)
14433 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14434 fmtId(rinfo->dobj.name));
14437 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14438 fmtId(rinfo->dobj.name));
14441 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14442 fmtId(rinfo->dobj.name));
14448 * Apply view's reloptions when its ON SELECT rule is separate.
14450 if (rinfo->reloptions && strlen(rinfo->reloptions) > 0)
14452 appendPQExpBuffer(cmd, "ALTER VIEW %s SET (%s);\n",
14453 fmtId(tbinfo->dobj.name),
14454 rinfo->reloptions);
14458 * DROP must be fully qualified in case same name appears in pg_catalog
14460 appendPQExpBuffer(delcmd, "DROP RULE %s ",
14461 fmtId(rinfo->dobj.name));
14462 appendPQExpBuffer(delcmd, "ON %s.",
14463 fmtId(tbinfo->dobj.namespace->dobj.name));
14464 appendPQExpBuffer(delcmd, "%s;\n",
14465 fmtId(tbinfo->dobj.name));
14467 appendPQExpBuffer(labelq, "RULE %s",
14468 fmtId(rinfo->dobj.name));
14469 appendPQExpBuffer(labelq, " ON %s",
14470 fmtId(tbinfo->dobj.name));
14472 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14474 tbinfo->dobj.namespace->dobj.name,
14476 tbinfo->rolname, false,
14477 "RULE", SECTION_POST_DATA,
14478 cmd->data, delcmd->data, NULL,
14482 /* Dump rule comments */
14483 dumpComment(fout, labelq->data,
14484 tbinfo->dobj.namespace->dobj.name,
14486 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14490 destroyPQExpBuffer(query);
14491 destroyPQExpBuffer(cmd);
14492 destroyPQExpBuffer(delcmd);
14493 destroyPQExpBuffer(labelq);
14497 * getExtensionMembership --- obtain extension membership data
14500 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14511 DumpableObject *dobj,
14514 /* Nothing to do if no extensions */
14515 if (numExtensions == 0)
14518 /* Make sure we are in proper schema */
14519 selectSourceSchema(fout, "pg_catalog");
14521 query = createPQExpBuffer();
14523 /* refclassid constraint is redundant but may speed the search */
14524 appendPQExpBuffer(query, "SELECT "
14525 "classid, objid, refclassid, refobjid "
14527 "WHERE refclassid = 'pg_extension'::regclass "
14528 "AND deptype = 'e' "
14531 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14533 ntups = PQntuples(res);
14535 i_classid = PQfnumber(res, "classid");
14536 i_objid = PQfnumber(res, "objid");
14537 i_refclassid = PQfnumber(res, "refclassid");
14538 i_refobjid = PQfnumber(res, "refobjid");
14541 * Since we ordered the SELECT by referenced ID, we can expect that
14542 * multiple entries for the same extension will appear together; this
14543 * saves on searches.
14547 for (i = 0; i < ntups; i++)
14550 CatalogId refobjId;
14552 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14553 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14554 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14555 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14557 if (refdobj == NULL ||
14558 refdobj->catId.tableoid != refobjId.tableoid ||
14559 refdobj->catId.oid != refobjId.oid)
14560 refdobj = findObjectByCatalogId(refobjId);
14563 * Failure to find objects mentioned in pg_depend is not unexpected,
14564 * since for example we don't collect info about TOAST tables.
14566 if (refdobj == NULL)
14569 fprintf(stderr, "no referenced object %u %u\n",
14570 refobjId.tableoid, refobjId.oid);
14575 dobj = findObjectByCatalogId(objId);
14580 fprintf(stderr, "no referencing object %u %u\n",
14581 objId.tableoid, objId.oid);
14586 /* Record dependency so that getDependencies needn't repeat this */
14587 addObjectDependency(dobj, refdobj->dumpId);
14589 dobj->ext_member = true;
14592 * Normally, mark the member object as not to be dumped. But in
14593 * binary upgrades, we still dump the members individually, since the
14594 * idea is to exactly reproduce the database contents rather than
14595 * replace the extension contents with something different.
14597 if (!binary_upgrade)
14598 dobj->dump = false;
14600 dobj->dump = refdobj->dump;
14606 * Now identify extension configuration tables and create TableDataInfo
14607 * objects for them, ensuring their data will be dumped even though the
14608 * tables themselves won't be.
14610 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14611 * user data in a configuration table is treated like schema data. This
14612 * seems appropriate since system data in a config table would get
14613 * reloaded by CREATE EXTENSION.
14615 for (i = 0; i < numExtensions; i++)
14617 ExtensionInfo *curext = &(extinfo[i]);
14618 char *extconfig = curext->extconfig;
14619 char *extcondition = curext->extcondition;
14620 char **extconfigarray = NULL;
14621 char **extconditionarray = NULL;
14623 int nconditionitems;
14625 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14626 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14627 nconfigitems == nconditionitems)
14631 for (j = 0; j < nconfigitems; j++)
14633 TableInfo *configtbl;
14634 Oid configtbloid = atooid(extconfigarray[j]);
14635 bool dumpobj = curext->dobj.dump;
14637 configtbl = findTableByOid(configtbloid);
14638 if (configtbl == NULL)
14642 * Tables of not-to-be-dumped extensions shouldn't be dumped
14643 * unless the table or its schema is explicitly included
14645 if (!curext->dobj.dump)
14647 /* check table explicitly requested */
14648 if (table_include_oids.head != NULL &&
14649 simple_oid_list_member(&table_include_oids,
14653 /* check table's schema explicitly requested */
14654 if (configtbl->dobj.namespace->dobj.dump)
14658 /* check table excluded by an exclusion switch */
14659 if (table_exclude_oids.head != NULL &&
14660 simple_oid_list_member(&table_exclude_oids,
14664 /* check schema excluded by an exclusion switch */
14665 if (simple_oid_list_member(&schema_exclude_oids,
14666 configtbl->dobj.namespace->dobj.catId.oid))
14672 * Note: config tables are dumped without OIDs regardless of
14673 * the --oids setting. This is because row filtering
14674 * conditions aren't compatible with dumping OIDs.
14676 makeTableDataInfo(configtbl, false);
14677 if (configtbl->dataObj != NULL)
14679 if (strlen(extconditionarray[j]) > 0)
14680 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14685 if (extconfigarray)
14686 free(extconfigarray);
14687 if (extconditionarray)
14688 free(extconditionarray);
14691 destroyPQExpBuffer(query);
14695 * getDependencies --- obtain available dependency data
14698 getDependencies(Archive *fout)
14709 DumpableObject *dobj,
14712 /* No dependency info available before 7.3 */
14713 if (fout->remoteVersion < 70300)
14717 write_msg(NULL, "reading dependency data\n");
14719 /* Make sure we are in proper schema */
14720 selectSourceSchema(fout, "pg_catalog");
14722 query = createPQExpBuffer();
14725 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14726 * already processed by getExtensionMembership.
14728 appendPQExpBuffer(query, "SELECT "
14729 "classid, objid, refclassid, refobjid, deptype "
14731 "WHERE deptype != 'p' AND deptype != 'e' "
14734 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14736 ntups = PQntuples(res);
14738 i_classid = PQfnumber(res, "classid");
14739 i_objid = PQfnumber(res, "objid");
14740 i_refclassid = PQfnumber(res, "refclassid");
14741 i_refobjid = PQfnumber(res, "refobjid");
14742 i_deptype = PQfnumber(res, "deptype");
14745 * Since we ordered the SELECT by referencing ID, we can expect that
14746 * multiple entries for the same object will appear together; this saves
14751 for (i = 0; i < ntups; i++)
14754 CatalogId refobjId;
14757 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14758 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14759 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14760 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14761 deptype = *(PQgetvalue(res, i, i_deptype));
14763 if (dobj == NULL ||
14764 dobj->catId.tableoid != objId.tableoid ||
14765 dobj->catId.oid != objId.oid)
14766 dobj = findObjectByCatalogId(objId);
14769 * Failure to find objects mentioned in pg_depend is not unexpected,
14770 * since for example we don't collect info about TOAST tables.
14775 fprintf(stderr, "no referencing object %u %u\n",
14776 objId.tableoid, objId.oid);
14781 refdobj = findObjectByCatalogId(refobjId);
14783 if (refdobj == NULL)
14786 fprintf(stderr, "no referenced object %u %u\n",
14787 refobjId.tableoid, refobjId.oid);
14793 * Ordinarily, table rowtypes have implicit dependencies on their
14794 * tables. However, for a composite type the implicit dependency goes
14795 * the other way in pg_depend; which is the right thing for DROP but
14796 * it doesn't produce the dependency ordering we need. So in that one
14797 * case, we reverse the direction of the dependency.
14799 if (deptype == 'i' &&
14800 dobj->objType == DO_TABLE &&
14801 refdobj->objType == DO_TYPE)
14802 addObjectDependency(refdobj, dobj->dumpId);
14805 addObjectDependency(dobj, refdobj->dumpId);
14810 destroyPQExpBuffer(query);
14815 * createBoundaryObjects - create dummy DumpableObjects to represent
14816 * dump section boundaries.
14818 static DumpableObject *
14819 createBoundaryObjects(void)
14821 DumpableObject *dobjs;
14823 dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
14825 dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
14826 dobjs[0].catId = nilCatalogId;
14827 AssignDumpId(dobjs + 0);
14828 dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
14830 dobjs[1].objType = DO_POST_DATA_BOUNDARY;
14831 dobjs[1].catId = nilCatalogId;
14832 AssignDumpId(dobjs + 1);
14833 dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
14839 * addBoundaryDependencies - add dependencies as needed to enforce the dump
14840 * section boundaries.
14843 addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
14844 DumpableObject *boundaryObjs)
14846 DumpableObject *preDataBound = boundaryObjs + 0;
14847 DumpableObject *postDataBound = boundaryObjs + 1;
14850 for (i = 0; i < numObjs; i++)
14852 DumpableObject *dobj = dobjs[i];
14855 * The classification of object types here must match the SECTION_xxx
14856 * values assigned during subsequent ArchiveEntry calls!
14858 switch (dobj->objType)
14863 case DO_SHELL_TYPE:
14870 case DO_CONVERSION:
14875 case DO_DUMMY_TYPE:
14878 case DO_TSTEMPLATE:
14881 case DO_FOREIGN_SERVER:
14883 /* Pre-data objects: must come before the pre-data boundary */
14884 addObjectDependency(preDataBound, dobj->dumpId);
14886 case DO_TABLE_DATA:
14888 /* Data objects: must come between the boundaries */
14889 addObjectDependency(dobj, preDataBound->dumpId);
14890 addObjectDependency(postDataBound, dobj->dumpId);
14893 case DO_REFRESH_MATVIEW:
14895 case DO_EVENT_TRIGGER:
14896 case DO_DEFAULT_ACL:
14897 /* Post-data objects: must come after the post-data boundary */
14898 addObjectDependency(dobj, postDataBound->dumpId);
14901 /* Rules are post-data, but only if dumped separately */
14902 if (((RuleInfo *) dobj)->separate)
14903 addObjectDependency(dobj, postDataBound->dumpId);
14905 case DO_CONSTRAINT:
14906 case DO_FK_CONSTRAINT:
14907 /* Constraints are post-data, but only if dumped separately */
14908 if (((ConstraintInfo *) dobj)->separate)
14909 addObjectDependency(dobj, postDataBound->dumpId);
14911 case DO_PRE_DATA_BOUNDARY:
14912 /* nothing to do */
14914 case DO_POST_DATA_BOUNDARY:
14915 /* must come after the pre-data boundary */
14916 addObjectDependency(dobj, preDataBound->dumpId);
14924 * BuildArchiveDependencies - create dependency data for archive TOC entries
14926 * The raw dependency data obtained by getDependencies() is not terribly
14927 * useful in an archive dump, because in many cases there are dependency
14928 * chains linking through objects that don't appear explicitly in the dump.
14929 * For example, a view will depend on its _RETURN rule while the _RETURN rule
14930 * will depend on other objects --- but the rule will not appear as a separate
14931 * object in the dump. We need to adjust the view's dependencies to include
14932 * whatever the rule depends on that is included in the dump.
14934 * Just to make things more complicated, there are also "special" dependencies
14935 * such as the dependency of a TABLE DATA item on its TABLE, which we must
14936 * not rearrange because pg_restore knows that TABLE DATA only depends on
14937 * its table. In these cases we must leave the dependencies strictly as-is
14938 * even if they refer to not-to-be-dumped objects.
14940 * To handle this, the convention is that "special" dependencies are created
14941 * during ArchiveEntry calls, and an archive TOC item that has any such
14942 * entries will not be touched here. Otherwise, we recursively search the
14943 * DumpableObject data structures to build the correct dependencies for each
14944 * archive TOC item.
14947 BuildArchiveDependencies(Archive *fout)
14949 ArchiveHandle *AH = (ArchiveHandle *) fout;
14952 /* Scan all TOC entries in the archive */
14953 for (te = AH->toc->next; te != AH->toc; te = te->next)
14955 DumpableObject *dobj;
14956 DumpId *dependencies;
14960 /* No need to process entries that will not be dumped */
14963 /* Ignore entries that already have "special" dependencies */
14966 /* Otherwise, look up the item's original DumpableObject, if any */
14967 dobj = findObjectByDumpId(te->dumpId);
14970 /* No work if it has no dependencies */
14971 if (dobj->nDeps <= 0)
14973 /* Set up work array */
14975 dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
14977 /* Recursively find all dumpable dependencies */
14978 findDumpableDependencies(AH, dobj,
14979 &dependencies, &nDeps, &allocDeps);
14980 /* And save 'em ... */
14983 dependencies = (DumpId *) pg_realloc(dependencies,
14984 nDeps * sizeof(DumpId));
14985 te->dependencies = dependencies;
14989 free(dependencies);
14993 /* Recursive search subroutine for BuildArchiveDependencies */
14995 findDumpableDependencies(ArchiveHandle *AH, DumpableObject *dobj,
14996 DumpId **dependencies, int *nDeps, int *allocDeps)
15001 * Ignore section boundary objects: if we search through them, we'll
15002 * report lots of bogus dependencies.
15004 if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
15005 dobj->objType == DO_POST_DATA_BOUNDARY)
15008 for (i = 0; i < dobj->nDeps; i++)
15010 DumpId depid = dobj->dependencies[i];
15012 if (TocIDRequired(AH, depid) != 0)
15014 /* Object will be dumped, so just reference it as a dependency */
15015 if (*nDeps >= *allocDeps)
15018 *dependencies = (DumpId *) pg_realloc(*dependencies,
15019 *allocDeps * sizeof(DumpId));
15021 (*dependencies)[*nDeps] = depid;
15027 * Object will not be dumped, so recursively consider its deps. We
15028 * rely on the assumption that sortDumpableObjects already broke
15029 * any dependency loops, else we might recurse infinitely.
15031 DumpableObject *otherdobj = findObjectByDumpId(depid);
15034 findDumpableDependencies(AH, otherdobj,
15035 dependencies, nDeps, allocDeps);
15042 * selectSourceSchema - make the specified schema the active search path
15043 * in the source database.
15045 * NB: pg_catalog is explicitly searched after the specified schema;
15046 * so user names are only qualified if they are cross-schema references,
15047 * and system names are only qualified if they conflict with a user name
15048 * in the current schema.
15050 * Whenever the selected schema is not pg_catalog, be careful to qualify
15051 * references to system catalogs and types in our emitted commands!
15053 * This function is called only from selectSourceSchemaOnAH and
15054 * selectSourceSchema.
15057 selectSourceSchema(Archive *fout, const char *schemaName)
15061 /* This is checked by the callers already */
15062 Assert(schemaName != NULL && *schemaName != '\0');
15064 /* Not relevant if fetching from pre-7.3 DB */
15065 if (fout->remoteVersion < 70300)
15068 query = createPQExpBuffer();
15069 appendPQExpBuffer(query, "SET search_path = %s",
15070 fmtId(schemaName));
15071 if (strcmp(schemaName, "pg_catalog") != 0)
15072 appendPQExpBuffer(query, ", pg_catalog");
15074 ExecuteSqlStatement(fout, query->data);
15076 destroyPQExpBuffer(query);
15080 * getFormattedTypeName - retrieve a nicely-formatted type name for the
15083 * NB: in 7.3 and up the result may depend on the currently-selected
15084 * schema; this is why we don't try to cache the names.
15087 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
15095 if ((opts & zeroAsOpaque) != 0)
15096 return pg_strdup(g_opaque_type);
15097 else if ((opts & zeroAsAny) != 0)
15098 return pg_strdup("'any'");
15099 else if ((opts & zeroAsStar) != 0)
15100 return pg_strdup("*");
15101 else if ((opts & zeroAsNone) != 0)
15102 return pg_strdup("NONE");
15105 query = createPQExpBuffer();
15106 if (fout->remoteVersion >= 70300)
15108 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
15111 else if (fout->remoteVersion >= 70100)
15113 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
15118 appendPQExpBuffer(query, "SELECT typname "
15120 "WHERE oid = '%u'::oid",
15124 res = ExecuteSqlQueryForSingleRow(fout, query->data);
15126 if (fout->remoteVersion >= 70100)
15128 /* already quoted */
15129 result = pg_strdup(PQgetvalue(res, 0, 0));
15133 /* may need to quote it */
15134 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
15138 destroyPQExpBuffer(query);
15144 * myFormatType --- local implementation of format_type for use with 7.0.
15147 myFormatType(const char *typname, int32 typmod)
15150 bool isarray = false;
15151 PQExpBuffer buf = createPQExpBuffer();
15153 /* Handle array types */
15154 if (typname[0] == '_')
15160 /* Show lengths on bpchar and varchar */
15161 if (strcmp(typname, "bpchar") == 0)
15163 int len = (typmod - VARHDRSZ);
15165 appendPQExpBuffer(buf, "character");
15167 appendPQExpBuffer(buf, "(%d)",
15168 typmod - VARHDRSZ);
15170 else if (strcmp(typname, "varchar") == 0)
15172 appendPQExpBuffer(buf, "character varying");
15174 appendPQExpBuffer(buf, "(%d)",
15175 typmod - VARHDRSZ);
15177 else if (strcmp(typname, "numeric") == 0)
15179 appendPQExpBuffer(buf, "numeric");
15186 tmp_typmod = typmod - VARHDRSZ;
15187 precision = (tmp_typmod >> 16) & 0xffff;
15188 scale = tmp_typmod & 0xffff;
15189 appendPQExpBuffer(buf, "(%d,%d)",
15195 * char is an internal single-byte data type; Let's make sure we force it
15196 * through with quotes. - thomas 1998-12-13
15198 else if (strcmp(typname, "char") == 0)
15199 appendPQExpBuffer(buf, "\"char\"");
15201 appendPQExpBuffer(buf, "%s", fmtId(typname));
15203 /* Append array qualifier for array types */
15205 appendPQExpBuffer(buf, "[]");
15207 result = pg_strdup(buf->data);
15208 destroyPQExpBuffer(buf);
15214 * Return a column list clause for the given relation.
15216 * Special case: if there are no undropped columns in the relation, return
15217 * "", not an invalid "()" column list.
15219 static const char *
15220 fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
15222 int numatts = ti->numatts;
15223 char **attnames = ti->attnames;
15224 bool *attisdropped = ti->attisdropped;
15228 appendPQExpBuffer(buffer, "(");
15230 for (i = 0; i < numatts; i++)
15232 if (attisdropped[i])
15235 appendPQExpBuffer(buffer, ", ");
15236 appendPQExpBuffer(buffer, "%s", fmtId(attnames[i]));
15241 return ""; /* no undropped columns */
15243 appendPQExpBuffer(buffer, ")");
15244 return buffer->data;
15248 * Execute an SQL query and verify that we got exactly one row back.
15251 ExecuteSqlQueryForSingleRow(Archive *fout, char *query)
15256 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
15258 /* Expecting a single result only */
15259 ntups = PQntuples(res);
15261 exit_horribly(NULL,
15262 ngettext("query returned %d row instead of one: %s\n",
15263 "query returned %d rows instead of one: %s\n",