1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
14 * Note that pg_dump runs in a transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to run on
18 * SnapshotNow time, ie they look at the currently committed state. So
19 * it is possible to get 'cache lookup failed' error if someone
20 * performs DDL changes while a dump is happening. The window for this
21 * sort of thing is from the acquisition of the transaction snapshot to
22 * getSchemaData() (when pg_dump acquires AccessShareLock on every
23 * table it intends to dump). It isn't very large, but it can happen.
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
33 #include "postgres_fe.h"
44 #include "getopt_long.h"
46 #include "access/attnum.h"
47 #include "access/sysattr.h"
48 #include "access/transam.h"
49 #include "catalog/pg_cast.h"
50 #include "catalog/pg_class.h"
51 #include "catalog/pg_default_acl.h"
52 #include "catalog/pg_largeobject.h"
53 #include "catalog/pg_largeobject_metadata.h"
54 #include "catalog/pg_proc.h"
55 #include "catalog/pg_trigger.h"
56 #include "catalog/pg_type.h"
57 #include "libpq/libpq-fs.h"
59 #include "pg_backup_archiver.h"
60 #include "pg_backup_db.h"
62 #include "dumputils.h"
71 const char *descr; /* comment for an object */
72 Oid classoid; /* object class (catalog OID) */
73 Oid objoid; /* object OID */
74 int objsubid; /* subobject (table column #) */
79 const char *provider; /* label provider of this security label */
80 const char *label; /* security label for an object */
81 Oid classoid; /* object class (catalog OID) */
82 Oid objoid; /* object OID */
83 int objsubid; /* subobject (table column #) */
87 bool g_verbose; /* User wants verbose narration of our
89 PGconn *g_conn; /* the database connection */
91 /* various user-settable parameters */
94 int dumpSections; /* bitmask of chosen sections */
96 const char *lockWaitTimeout;
98 /* subquery used to convert user ID (eg, datdba) to user name */
99 static const char *username_subquery;
101 /* obsolete as of 7.3: */
102 static Oid g_last_builtin_oid; /* value of the last builtin oid */
105 * Object inclusion/exclusion lists
107 * The string lists record the patterns given by command-line switches,
108 * which we then convert to lists of OIDs of matching objects.
110 static SimpleStringList schema_include_patterns = {NULL, NULL};
111 static SimpleOidList schema_include_oids = {NULL, NULL};
112 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
113 static SimpleOidList schema_exclude_oids = {NULL, NULL};
115 static SimpleStringList table_include_patterns = {NULL, NULL};
116 static SimpleOidList table_include_oids = {NULL, NULL};
117 static SimpleStringList table_exclude_patterns = {NULL, NULL};
118 static SimpleOidList table_exclude_oids = {NULL, NULL};
119 static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
120 static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
122 /* default, if no "inclusion" switches appear, is to dump everything */
123 static bool include_everything = true;
125 char g_opaque_type[10]; /* name for the opaque type */
127 /* placeholders for the delimiters for comments */
128 char g_comment_start[10];
129 char g_comment_end[10];
131 static const CatalogId nilCatalogId = {0, 0};
133 /* these are to avoid passing around info for findNamespace() */
134 static NamespaceInfo *g_namespaces;
135 static int g_numNamespaces;
137 /* flags for various command-line long options */
138 static int binary_upgrade = 0;
139 static int disable_dollar_quoting = 0;
140 static int dump_inserts = 0;
141 static int column_inserts = 0;
142 static int no_security_labels = 0;
143 static int no_unlogged_table_data = 0;
144 static int serializable_deferrable = 0;
147 static void help(const char *progname);
148 static void setup_connection(Archive *AH, const char *dumpencoding,
150 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
151 static void expand_schema_name_patterns(Archive *fout,
152 SimpleStringList *patterns,
153 SimpleOidList *oids);
154 static void expand_table_name_patterns(Archive *fout,
155 SimpleStringList *patterns,
156 SimpleOidList *oids);
157 static NamespaceInfo *findNamespace(Archive *fout, Oid nsoid, Oid objoid);
158 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
159 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
160 static void dumpComment(Archive *fout, const char *target,
161 const char *namespace, const char *owner,
162 CatalogId catalogId, int subid, DumpId dumpId);
163 static int findComments(Archive *fout, Oid classoid, Oid objoid,
164 CommentItem **items);
165 static int collectComments(Archive *fout, CommentItem **items);
166 static void dumpSecLabel(Archive *fout, const char *target,
167 const char *namespace, const char *owner,
168 CatalogId catalogId, int subid, DumpId dumpId);
169 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
170 SecLabelItem **items);
171 static int collectSecLabels(Archive *fout, SecLabelItem **items);
172 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
173 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
174 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
175 static void dumpType(Archive *fout, TypeInfo *tyinfo);
176 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
177 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
178 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
179 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
180 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
181 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
182 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
183 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
184 static void dumpFunc(Archive *fout, FuncInfo *finfo);
185 static void dumpCast(Archive *fout, CastInfo *cast);
186 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
187 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
188 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
189 static void dumpCollation(Archive *fout, CollInfo *convinfo);
190 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
191 static void dumpRule(Archive *fout, RuleInfo *rinfo);
192 static void dumpAgg(Archive *fout, AggInfo *agginfo);
193 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
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 dumpIndex(Archive *fout, IndxInfo *indxinfo);
199 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
200 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
201 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
202 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
203 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
204 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
205 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
206 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
207 static void dumpUserMappings(Archive *fout,
208 const char *servername, const char *namespace,
209 const char *owner, CatalogId catalogId, DumpId dumpId);
210 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
212 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
213 const char *type, const char *name, const char *subname,
214 const char *tag, const char *nspname, const char *owner,
217 static void getDependencies(Archive *fout);
218 static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
219 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
220 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
221 static void getTableDataFKConstraints(void);
222 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
223 static char *format_function_arguments_old(Archive *fout,
224 FuncInfo *finfo, int nallargs,
228 static char *format_function_signature(Archive *fout,
229 FuncInfo *finfo, bool honor_quotes);
230 static const char *convertRegProcReference(Archive *fout,
232 static const char *convertOperatorReference(Archive *fout, const char *opr);
233 static const char *convertTSFunction(Archive *fout, Oid funcOid);
234 static Oid findLastBuiltinOid_V71(Archive *fout, const char *);
235 static Oid findLastBuiltinOid_V70(Archive *fout);
236 static void selectSourceSchema(Archive *fout, const char *schemaName);
237 static char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
238 static char *myFormatType(const char *typname, int32 typmod);
239 static const char *fmtQualifiedId(Archive *fout,
240 const char *schema, const char *id);
241 static void getBlobs(Archive *fout);
242 static void dumpBlob(Archive *fout, BlobInfo *binfo);
243 static int dumpBlobs(Archive *fout, void *arg);
244 static void dumpDatabase(Archive *AH);
245 static void dumpEncoding(Archive *AH);
246 static void dumpStdStrings(Archive *AH);
247 static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
248 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
249 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
250 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
251 static void binary_upgrade_set_pg_class_oids(Archive *fout,
252 PQExpBuffer upgrade_buffer,
253 Oid pg_class_oid, bool is_index);
254 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
255 DumpableObject *dobj,
256 const char *objlabel);
257 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
258 static const char *fmtCopyColumnList(const TableInfo *ti);
261 main(int argc, char **argv)
264 const char *filename = NULL;
265 const char *format = "p";
266 const char *dbname = NULL;
267 const char *pghost = NULL;
268 const char *pgport = NULL;
269 const char *username = NULL;
270 const char *dumpencoding = NULL;
274 DumpableObject **dobjs;
277 enum trivalue prompt_password = TRI_DEFAULT;
278 int compressLevel = -1;
281 int outputCreateDB = 0;
282 bool outputBlobs = false;
283 int outputNoOwner = 0;
284 char *outputSuperuser = NULL;
285 char *use_role = NULL;
288 RestoreOptions *ropt;
289 ArchiveFormat archiveFormat = archUnknown;
290 ArchiveMode archiveMode;
291 Archive *fout; /* the script file */
293 static int disable_triggers = 0;
294 static int outputNoTablespaces = 0;
295 static int use_setsessauth = 0;
297 static struct option long_options[] = {
298 {"data-only", no_argument, NULL, 'a'},
299 {"blobs", no_argument, NULL, 'b'},
300 {"clean", no_argument, NULL, 'c'},
301 {"create", no_argument, NULL, 'C'},
302 {"file", required_argument, NULL, 'f'},
303 {"format", required_argument, NULL, 'F'},
304 {"host", required_argument, NULL, 'h'},
305 {"ignore-version", no_argument, NULL, 'i'},
306 {"no-reconnect", no_argument, NULL, 'R'},
307 {"oids", no_argument, NULL, 'o'},
308 {"no-owner", no_argument, NULL, 'O'},
309 {"port", required_argument, NULL, 'p'},
310 {"schema", required_argument, NULL, 'n'},
311 {"exclude-schema", required_argument, NULL, 'N'},
312 {"schema-only", no_argument, NULL, 's'},
313 {"superuser", required_argument, NULL, 'S'},
314 {"table", required_argument, NULL, 't'},
315 {"exclude-table", required_argument, NULL, 'T'},
316 {"no-password", no_argument, NULL, 'w'},
317 {"password", no_argument, NULL, 'W'},
318 {"username", required_argument, NULL, 'U'},
319 {"verbose", no_argument, NULL, 'v'},
320 {"no-privileges", no_argument, NULL, 'x'},
321 {"no-acl", no_argument, NULL, 'x'},
322 {"compress", required_argument, NULL, 'Z'},
323 {"encoding", required_argument, NULL, 'E'},
324 {"help", no_argument, NULL, '?'},
325 {"version", no_argument, NULL, 'V'},
328 * the following options don't have an equivalent short option letter
330 {"attribute-inserts", no_argument, &column_inserts, 1},
331 {"binary-upgrade", no_argument, &binary_upgrade, 1},
332 {"column-inserts", no_argument, &column_inserts, 1},
333 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
334 {"disable-triggers", no_argument, &disable_triggers, 1},
335 {"exclude-table-data", required_argument, NULL, 4},
336 {"inserts", no_argument, &dump_inserts, 1},
337 {"lock-wait-timeout", required_argument, NULL, 2},
338 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
339 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
340 {"role", required_argument, NULL, 3},
341 {"section", required_argument, NULL, 5},
342 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
343 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
344 {"no-security-labels", no_argument, &no_security_labels, 1},
345 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
350 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
354 strcpy(g_comment_start, "-- ");
355 g_comment_end[0] = '\0';
356 strcpy(g_opaque_type, "opaque");
358 dataOnly = schemaOnly = false;
359 dumpSections = DUMP_UNSECTIONED;
360 lockWaitTimeout = NULL;
362 progname = get_progname(argv[0]);
364 /* Set default options based on progname */
365 if (strcmp(progname, "pg_backup") == 0)
370 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
375 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
377 puts("pg_dump (PostgreSQL) " PG_VERSION);
382 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
383 long_options, &optindex)) != -1)
387 case 'a': /* Dump data only */
391 case 'b': /* Dump blobs */
395 case 'c': /* clean (i.e., drop) schema prior to create */
399 case 'C': /* Create DB */
403 case 'E': /* Dump encoding */
404 dumpencoding = optarg;
415 case 'h': /* server host */
420 /* ignored, deprecated option */
423 case 'n': /* include schema(s) */
424 simple_string_list_append(&schema_include_patterns, optarg);
425 include_everything = false;
428 case 'N': /* exclude schema(s) */
429 simple_string_list_append(&schema_exclude_patterns, optarg);
432 case 'o': /* Dump oids */
436 case 'O': /* Don't reconnect to match owner */
440 case 'p': /* server port */
445 /* no-op, still accepted for backwards compatibility */
448 case 's': /* dump schema only */
452 case 'S': /* Username for superuser in plain text output */
453 outputSuperuser = pg_strdup(optarg);
456 case 't': /* include table(s) */
457 simple_string_list_append(&table_include_patterns, optarg);
458 include_everything = false;
461 case 'T': /* exclude table(s) */
462 simple_string_list_append(&table_exclude_patterns, optarg);
469 case 'v': /* verbose */
474 prompt_password = TRI_NO;
478 prompt_password = TRI_YES;
481 case 'x': /* skip ACL dump */
485 case 'Z': /* Compression Level */
486 compressLevel = atoi(optarg);
490 /* This covers the long options. */
493 case 2: /* lock-wait-timeout */
494 lockWaitTimeout = optarg;
497 case 3: /* SET ROLE */
501 case 4: /* exclude table(s) data */
502 simple_string_list_append(&tabledata_exclude_patterns, optarg);
505 case 5: /* section */
506 set_section(optarg, &dumpSections);
510 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
515 /* Get database name from command line */
517 dbname = argv[optind++];
519 /* Complain if any arguments remain */
522 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
523 progname, argv[optind]);
524 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
529 /* --column-inserts implies --inserts */
533 if (dataOnly && schemaOnly)
535 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
539 if ((dataOnly || schemaOnly) && dumpSections != DUMP_UNSECTIONED)
541 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used with --section\n");
546 dumpSections = DUMP_DATA;
548 dumpSections = DUMP_PRE_DATA | DUMP_POST_DATA;
549 else if ( dumpSections != DUMP_UNSECTIONED)
551 dataOnly = dumpSections == DUMP_DATA;
552 schemaOnly = !(dumpSections & DUMP_DATA);
555 if (dataOnly && outputClean)
557 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
561 if (dump_inserts && oids)
563 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
564 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
568 /* Identify archive format to emit */
569 archiveFormat = parseArchiveFormat(format, &archiveMode);
571 /* archiveFormat specific setup */
572 if (archiveFormat == archNull)
575 /* Custom and directory formats are compressed by default, others not */
576 if (compressLevel == -1)
578 if (archiveFormat == archCustom || archiveFormat == archDirectory)
579 compressLevel = Z_DEFAULT_COMPRESSION;
584 /* Open the output file */
585 fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
589 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
593 /* Let the archiver know how noisy to be */
594 fout->verbose = g_verbose;
596 my_version = parse_version(PG_VERSION);
599 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
604 * We allow the server to be back to 7.0, and up to any minor release of
605 * our own major version. (See also version check in pg_dumpall.c.)
607 fout->minRemoteVersion = 70000;
608 fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
611 * Open the database using the Archiver, so it knows about it. Errors mean
614 g_conn = ConnectDatabase(fout, dbname, pghost, pgport,
615 username, prompt_password);
617 setup_connection(fout, dumpencoding, use_role);
620 * Disable security label support if server version < v9.1.x (prevents
621 * access to nonexistent pg_seclabel catalog)
623 if (fout->remoteVersion < 90100)
624 no_security_labels = 1;
627 * Start transaction-snapshot mode transaction to dump consistent data.
629 ExecuteSqlStatement(fout, "BEGIN");
630 if (fout->remoteVersion >= 90100)
632 if (serializable_deferrable)
633 ExecuteSqlStatement(fout,
634 "SET TRANSACTION ISOLATION LEVEL "
635 "SERIALIZABLE, READ ONLY, DEFERRABLE");
637 ExecuteSqlStatement(fout,
638 "SET TRANSACTION ISOLATION LEVEL "
642 ExecuteSqlStatement(fout,
643 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
645 /* Select the appropriate subquery to convert user IDs to names */
646 if (fout->remoteVersion >= 80100)
647 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
648 else if (fout->remoteVersion >= 70300)
649 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
651 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
653 /* Find the last built-in OID, if needed */
654 if (fout->remoteVersion < 70300)
656 if (fout->remoteVersion >= 70100)
657 g_last_builtin_oid = findLastBuiltinOid_V71(fout, PQdb(g_conn));
659 g_last_builtin_oid = findLastBuiltinOid_V70(fout);
661 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
664 /* Expand schema selection patterns into OID lists */
665 if (schema_include_patterns.head != NULL)
667 expand_schema_name_patterns(fout, &schema_include_patterns,
668 &schema_include_oids);
669 if (schema_include_oids.head == NULL)
671 write_msg(NULL, "No matching schemas were found\n");
675 expand_schema_name_patterns(fout, &schema_exclude_patterns,
676 &schema_exclude_oids);
677 /* non-matching exclusion patterns aren't an error */
679 /* Expand table selection patterns into OID lists */
680 if (table_include_patterns.head != NULL)
682 expand_table_name_patterns(fout, &table_include_patterns,
683 &table_include_oids);
684 if (table_include_oids.head == NULL)
686 write_msg(NULL, "No matching tables were found\n");
690 expand_table_name_patterns(fout, &table_exclude_patterns,
691 &table_exclude_oids);
693 expand_table_name_patterns(fout, &tabledata_exclude_patterns,
694 &tabledata_exclude_oids);
696 /* non-matching exclusion patterns aren't an error */
699 * Dumping blobs is now default unless we saw an inclusion switch or -s
700 * ... but even if we did see one of these, -b turns it back on.
702 if (include_everything && !schemaOnly)
706 * Now scan the database and create DumpableObject structs for all the
707 * objects we intend to dump.
709 tblinfo = getSchemaData(fout, &numTables);
711 if (fout->remoteVersion < 80400)
712 guessConstraintInheritance(tblinfo, numTables);
716 getTableData(tblinfo, numTables, oids);
718 getTableDataFKConstraints();
725 * Collect dependency data to assist in ordering the objects.
727 getDependencies(fout);
730 * Sort the objects into a safe dump order (no forward references).
732 * In 7.3 or later, we can rely on dependency information to help us
733 * determine a safe order, so the initial sort is mostly for cosmetic
734 * purposes: we sort by name to ensure that logically identical schemas
735 * will dump identically. Before 7.3 we don't have dependencies and we
736 * use OID ordering as an (unreliable) guide to creation order.
738 getDumpableObjects(&dobjs, &numObjs);
740 if (fout->remoteVersion >= 70300)
741 sortDumpableObjectsByTypeName(dobjs, numObjs);
743 sortDumpableObjectsByTypeOid(dobjs, numObjs);
745 sortDumpableObjects(dobjs, numObjs);
748 * Create archive TOC entries for all the objects to be dumped, in a safe
752 /* First the special ENCODING and STDSTRINGS entries. */
754 dumpStdStrings(fout);
756 /* The database item is always next, unless we don't want it at all */
757 if (include_everything && !dataOnly)
760 /* Now the rearrangeable objects. */
761 for (i = 0; i < numObjs; i++)
762 dumpDumpableObject(fout, dobjs[i]);
765 * And finally we can do the actual output.
769 ropt = NewRestoreOptions();
770 ropt->filename = filename;
771 ropt->dropSchema = outputClean;
772 ropt->aclsSkip = aclsSkip;
773 ropt->superuser = outputSuperuser;
774 ropt->createDB = outputCreateDB;
775 ropt->noOwner = outputNoOwner;
776 ropt->noTablespace = outputNoTablespaces;
777 ropt->disable_triggers = disable_triggers;
778 ropt->use_setsessauth = use_setsessauth;
779 ropt->dataOnly = dataOnly;
781 if (compressLevel == -1)
782 ropt->compression = 0;
784 ropt->compression = compressLevel;
786 ropt->suppressDumpWarnings = true; /* We've already shown them */
788 RestoreArchive(fout, ropt);
800 help(const char *progname)
802 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
803 printf(_("Usage:\n"));
804 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
806 printf(_("\nGeneral options:\n"));
807 printf(_(" -f, --file=FILENAME output file or directory name\n"));
808 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
809 " plain text (default))\n"));
810 printf(_(" -v, --verbose verbose mode\n"));
811 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
812 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
813 printf(_(" --help show this help, then exit\n"));
814 printf(_(" --version output version information, then exit\n"));
816 printf(_("\nOptions controlling the output content:\n"));
817 printf(_(" -a, --data-only dump only the data, not the schema\n"));
818 printf(_(" -b, --blobs include large objects in dump\n"));
819 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
820 printf(_(" -C, --create include commands to create database in dump\n"));
821 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
822 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
823 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
824 printf(_(" -o, --oids include OIDs in dump\n"));
825 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
826 " plain-text format\n"));
827 printf(_(" -s, --schema-only dump only the schema, no data\n"));
828 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
829 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
830 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
831 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
832 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
833 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
834 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
835 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
836 printf(_(" --exclude-table-data=TABLE do NOT dump data for the named table(s)\n"));
837 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
838 printf(_(" --no-security-labels do not dump security label assignments\n"));
839 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
840 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
841 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
842 printf(_(" --section=SECTION dump named section (pre-data, data or post-data)\n"));
843 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
844 printf(_(" --use-set-session-authorization\n"
845 " use SET SESSION AUTHORIZATION commands instead of\n"
846 " ALTER OWNER commands to set ownership\n"));
848 printf(_("\nConnection options:\n"));
849 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
850 printf(_(" -p, --port=PORT database server port number\n"));
851 printf(_(" -U, --username=NAME connect as specified database user\n"));
852 printf(_(" -w, --no-password never prompt for password\n"));
853 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
854 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
856 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
857 "variable value is used.\n\n"));
858 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
866 write_msg(NULL, "*** aborted because of error\n");
871 setup_connection(Archive *AH, const char *dumpencoding, char *use_role)
873 const char *std_strings;
875 /* Set the client encoding if requested */
878 if (PQsetClientEncoding(g_conn, dumpencoding) < 0)
880 write_msg(NULL, "invalid client encoding \"%s\" specified\n",
887 * Get the active encoding and the standard_conforming_strings setting, so
888 * we know how to escape strings.
890 AH->encoding = PQclientEncoding(g_conn);
892 std_strings = PQparameterStatus(g_conn, "standard_conforming_strings");
893 AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
895 /* Set the role if requested */
896 if (use_role && AH->remoteVersion >= 80100)
898 PQExpBuffer query = createPQExpBuffer();
900 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
901 ExecuteSqlStatement(AH, query->data);
902 destroyPQExpBuffer(query);
905 /* Set the datestyle to ISO to ensure the dump's portability */
906 ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
908 /* Likewise, avoid using sql_standard intervalstyle */
909 if (AH->remoteVersion >= 80400)
910 ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
913 * If supported, set extra_float_digits so that we can dump float data
914 * exactly (given correctly implemented float I/O code, anyway)
916 if (AH->remoteVersion >= 90000)
917 ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
918 else if (AH->remoteVersion >= 70400)
919 ExecuteSqlStatement(AH, "SET extra_float_digits TO 2");
922 * If synchronized scanning is supported, disable it, to prevent
923 * unpredictable changes in row ordering across a dump and reload.
925 if (AH->remoteVersion >= 80300)
926 ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
929 * Disable timeouts if supported.
931 if (AH->remoteVersion >= 70300)
932 ExecuteSqlStatement(AH, "SET statement_timeout = 0");
935 * Quote all identifiers, if requested.
937 if (quote_all_identifiers && AH->remoteVersion >= 90100)
938 ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
942 parseArchiveFormat(const char *format, ArchiveMode *mode)
944 ArchiveFormat archiveFormat;
946 *mode = archModeWrite;
948 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
950 /* This is used by pg_dumpall, and is not documented */
951 archiveFormat = archNull;
952 *mode = archModeAppend;
954 else if (pg_strcasecmp(format, "c") == 0)
955 archiveFormat = archCustom;
956 else if (pg_strcasecmp(format, "custom") == 0)
957 archiveFormat = archCustom;
958 else if (pg_strcasecmp(format, "d") == 0)
959 archiveFormat = archDirectory;
960 else if (pg_strcasecmp(format, "directory") == 0)
961 archiveFormat = archDirectory;
962 else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
965 * Dump files into the current directory; for demonstration only, not
968 archiveFormat = archFiles;
969 else if (pg_strcasecmp(format, "p") == 0)
970 archiveFormat = archNull;
971 else if (pg_strcasecmp(format, "plain") == 0)
972 archiveFormat = archNull;
973 else if (pg_strcasecmp(format, "t") == 0)
974 archiveFormat = archTar;
975 else if (pg_strcasecmp(format, "tar") == 0)
976 archiveFormat = archTar;
979 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
982 return archiveFormat;
986 * Find the OIDs of all schemas matching the given list of patterns,
987 * and append them to the given OID list.
990 expand_schema_name_patterns(Archive *fout,
991 SimpleStringList *patterns,
996 SimpleStringListCell *cell;
999 if (patterns->head == NULL)
1000 return; /* nothing to do */
1002 if (fout->remoteVersion < 70300)
1004 write_msg(NULL, "server version must be at least 7.3 to use schema selection switches\n");
1008 query = createPQExpBuffer();
1011 * We use UNION ALL rather than UNION; this might sometimes result in
1012 * duplicate entries in the OID list, but we don't care.
1015 for (cell = patterns->head; cell; cell = cell->next)
1017 if (cell != patterns->head)
1018 appendPQExpBuffer(query, "UNION ALL\n");
1019 appendPQExpBuffer(query,
1020 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1021 processSQLNamePattern(g_conn, query, cell->val, false, false,
1022 NULL, "n.nspname", NULL,
1026 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1028 for (i = 0; i < PQntuples(res); i++)
1030 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1034 destroyPQExpBuffer(query);
1038 * Find the OIDs of all tables matching the given list of patterns,
1039 * and append them to the given OID list.
1042 expand_table_name_patterns(Archive *fout,
1043 SimpleStringList *patterns, SimpleOidList *oids)
1047 SimpleStringListCell *cell;
1050 if (patterns->head == NULL)
1051 return; /* nothing to do */
1053 query = createPQExpBuffer();
1056 * We use UNION ALL rather than UNION; this might sometimes result in
1057 * duplicate entries in the OID list, but we don't care.
1060 for (cell = patterns->head; cell; cell = cell->next)
1062 if (cell != patterns->head)
1063 appendPQExpBuffer(query, "UNION ALL\n");
1064 appendPQExpBuffer(query,
1066 "\nFROM pg_catalog.pg_class c"
1067 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1068 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1069 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1070 RELKIND_FOREIGN_TABLE);
1071 processSQLNamePattern(g_conn, query, cell->val, true, false,
1072 "n.nspname", "c.relname", NULL,
1073 "pg_catalog.pg_table_is_visible(c.oid)");
1076 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1078 for (i = 0; i < PQntuples(res); i++)
1080 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1084 destroyPQExpBuffer(query);
1088 * selectDumpableNamespace: policy-setting subroutine
1089 * Mark a namespace as to be dumped or not
1092 selectDumpableNamespace(NamespaceInfo *nsinfo)
1095 * If specific tables are being dumped, do not dump any complete
1096 * namespaces. If specific namespaces are being dumped, dump just those
1097 * namespaces. Otherwise, dump all non-system namespaces.
1099 if (table_include_oids.head != NULL)
1100 nsinfo->dobj.dump = false;
1101 else if (schema_include_oids.head != NULL)
1102 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1103 nsinfo->dobj.catId.oid);
1104 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1105 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1106 nsinfo->dobj.dump = false;
1108 nsinfo->dobj.dump = true;
1111 * In any case, a namespace can be excluded by an exclusion switch
1113 if (nsinfo->dobj.dump &&
1114 simple_oid_list_member(&schema_exclude_oids,
1115 nsinfo->dobj.catId.oid))
1116 nsinfo->dobj.dump = false;
1120 * selectDumpableTable: policy-setting subroutine
1121 * Mark a table as to be dumped or not
1124 selectDumpableTable(TableInfo *tbinfo)
1127 * If specific tables are being dumped, dump just those tables; else, dump
1128 * according to the parent namespace's dump flag.
1130 if (table_include_oids.head != NULL)
1131 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1132 tbinfo->dobj.catId.oid);
1134 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1137 * In any case, a table can be excluded by an exclusion switch
1139 if (tbinfo->dobj.dump &&
1140 simple_oid_list_member(&table_exclude_oids,
1141 tbinfo->dobj.catId.oid))
1142 tbinfo->dobj.dump = false;
1144 /* If table is to be dumped, check that the data is not excluded */
1145 if (tbinfo->dobj.dump && !
1146 simple_oid_list_member(&tabledata_exclude_oids,
1147 tbinfo->dobj.catId.oid))
1148 tbinfo->dobj.dumpdata = true;
1150 tbinfo->dobj.dumpdata = false;
1155 * selectDumpableType: policy-setting subroutine
1156 * Mark a type as to be dumped or not
1158 * If it's a table's rowtype or an autogenerated array type, we also apply a
1159 * special type code to facilitate sorting into the desired order. (We don't
1160 * want to consider those to be ordinary types because that would bring tables
1161 * up into the datatype part of the dump order.) We still set the object's
1162 * dump flag; that's not going to cause the dummy type to be dumped, but we
1163 * need it so that casts involving such types will be dumped correctly -- see
1164 * dumpCast. This means the flag should be set the same as for the underlying
1165 * object (the table or base type).
1168 selectDumpableType(TypeInfo *tyinfo)
1170 /* skip complex types, except for standalone composite types */
1171 if (OidIsValid(tyinfo->typrelid) &&
1172 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1174 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1176 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1177 if (tytable != NULL)
1178 tyinfo->dobj.dump = tytable->dobj.dump;
1180 tyinfo->dobj.dump = false;
1184 /* skip auto-generated array types */
1185 if (tyinfo->isArray)
1187 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1189 * Fall through to set the dump flag; we assume that the subsequent
1190 * rules will do the same thing as they would for the array's base
1191 * type. (We cannot reliably look up the base type here, since
1192 * getTypes may not have processed it yet.)
1196 /* dump only types in dumpable namespaces */
1197 if (!tyinfo->dobj.namespace->dobj.dump)
1198 tyinfo->dobj.dump = false;
1200 /* skip undefined placeholder types */
1201 else if (!tyinfo->isDefined)
1202 tyinfo->dobj.dump = false;
1205 tyinfo->dobj.dump = true;
1209 * selectDumpableDefaultACL: policy-setting subroutine
1210 * Mark a default ACL as to be dumped or not
1212 * For per-schema default ACLs, dump if the schema is to be dumped.
1213 * Otherwise dump if we are dumping "everything". Note that dataOnly
1214 * and aclsSkip are checked separately.
1217 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1219 if (dinfo->dobj.namespace)
1220 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1222 dinfo->dobj.dump = include_everything;
1226 * selectDumpableExtension: policy-setting subroutine
1227 * Mark an extension as to be dumped or not
1229 * Normally, we dump all extensions, or none of them if include_everything
1230 * is false (i.e., a --schema or --table switch was given). However, in
1231 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1232 * assume those will already be installed in the target database. We identify
1233 * such extensions by their having OIDs in the range reserved for initdb.
1236 selectDumpableExtension(ExtensionInfo *extinfo)
1238 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1239 extinfo->dobj.dump = false;
1241 extinfo->dobj.dump = include_everything;
1245 * selectDumpableObject: policy-setting subroutine
1246 * Mark a generic dumpable object as to be dumped or not
1248 * Use this only for object types without a special-case routine above.
1251 selectDumpableObject(DumpableObject *dobj)
1254 * Default policy is to dump if parent namespace is dumpable, or always
1255 * for non-namespace-associated items.
1257 if (dobj->namespace)
1258 dobj->dump = dobj->namespace->dobj.dump;
1264 * Dump a table's contents for loading using the COPY command
1265 * - this routine is called by the Archiver when it wants the table
1270 dumpTableData_copy(Archive *fout, void *dcontext)
1272 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1273 TableInfo *tbinfo = tdinfo->tdtable;
1274 const char *classname = tbinfo->dobj.name;
1275 const bool hasoids = tbinfo->hasoids;
1276 const bool oids = tdinfo->oids;
1277 PQExpBuffer q = createPQExpBuffer();
1281 const char *column_list;
1284 write_msg(NULL, "dumping contents of table %s\n", classname);
1287 * Make sure we are in proper schema. We will qualify the table name
1288 * below anyway (in case its name conflicts with a pg_catalog table); but
1289 * this ensures reproducible results in case the table contains regproc,
1290 * regclass, etc columns.
1292 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1295 * If possible, specify the column list explicitly so that we have no
1296 * possibility of retrieving data in the wrong column order. (The default
1297 * column ordering of COPY will not be what we want in certain corner
1298 * cases involving ADD COLUMN and inheritance.)
1300 if (fout->remoteVersion >= 70300)
1301 column_list = fmtCopyColumnList(tbinfo);
1303 column_list = ""; /* can't select columns in COPY */
1305 if (oids && hasoids)
1307 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1308 fmtQualifiedId(fout,
1309 tbinfo->dobj.namespace->dobj.name,
1313 else if (tdinfo->filtercond)
1315 /* Note: this syntax is only supported in 8.2 and up */
1316 appendPQExpBufferStr(q, "COPY (SELECT ");
1317 /* klugery to get rid of parens in column list */
1318 if (strlen(column_list) > 2)
1320 appendPQExpBufferStr(q, column_list + 1);
1321 q->data[q->len - 1] = ' ';
1324 appendPQExpBufferStr(q, "* ");
1325 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1326 fmtQualifiedId(fout,
1327 tbinfo->dobj.namespace->dobj.name,
1329 tdinfo->filtercond);
1333 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1334 fmtQualifiedId(fout,
1335 tbinfo->dobj.namespace->dobj.name,
1339 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1344 ret = PQgetCopyData(g_conn, ©buf, 0);
1347 break; /* done or error */
1351 WriteData(fout, copybuf, ret);
1358 * There was considerable discussion in late July, 2000 regarding
1359 * slowing down pg_dump when backing up large tables. Users with both
1360 * slow & fast (multi-processor) machines experienced performance
1361 * degradation when doing a backup.
1363 * Initial attempts based on sleeping for a number of ms for each ms
1364 * of work were deemed too complex, then a simple 'sleep in each loop'
1365 * implementation was suggested. The latter failed because the loop
1366 * was too tight. Finally, the following was implemented:
1368 * If throttle is non-zero, then
1369 * See how long since the last sleep.
1370 * Work out how long to sleep (based on ratio).
1371 * If sleep is more than 100ms, then
1377 * where the throttle value was the number of ms to sleep per ms of
1378 * work. The calculation was done in each loop.
1380 * Most of the hard work is done in the backend, and this solution
1381 * still did not work particularly well: on slow machines, the ratio
1382 * was 50:1, and on medium paced machines, 1:1, and on fast
1383 * multi-processor machines, it had little or no effect, for reasons
1384 * that were unclear.
1386 * Further discussion ensued, and the proposal was dropped.
1388 * For those people who want this feature, it can be implemented using
1389 * gettimeofday in each loop, calculating the time since last sleep,
1390 * multiplying that by the sleep ratio, then if the result is more
1391 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1392 * function to sleep for a subsecond period ie.
1394 * select(0, NULL, NULL, NULL, &tvi);
1396 * This will return after the interval specified in the structure tvi.
1397 * Finally, call gettimeofday again to save the 'last sleep time'.
1401 archprintf(fout, "\\.\n\n\n");
1405 /* copy data transfer failed */
1406 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1407 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1408 write_msg(NULL, "The command was: %s\n", q->data);
1412 /* Check command status and return to normal libpq state */
1413 res = PQgetResult(g_conn);
1414 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1416 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1417 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1418 write_msg(NULL, "The command was: %s\n", q->data);
1423 destroyPQExpBuffer(q);
1428 * Dump table data using INSERT commands.
1430 * Caution: when we restore from an archive file direct to database, the
1431 * INSERT commands emitted by this function have to be parsed by
1432 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1433 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1436 dumpTableData_insert(Archive *fout, void *dcontext)
1438 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1439 TableInfo *tbinfo = tdinfo->tdtable;
1440 const char *classname = tbinfo->dobj.name;
1441 PQExpBuffer q = createPQExpBuffer();
1448 * Make sure we are in proper schema. We will qualify the table name
1449 * below anyway (in case its name conflicts with a pg_catalog table); but
1450 * this ensures reproducible results in case the table contains regproc,
1451 * regclass, etc columns.
1453 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1455 if (fout->remoteVersion >= 70100)
1457 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1458 "SELECT * FROM ONLY %s",
1459 fmtQualifiedId(fout,
1460 tbinfo->dobj.namespace->dobj.name,
1465 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1467 fmtQualifiedId(fout,
1468 tbinfo->dobj.namespace->dobj.name,
1471 if (tdinfo->filtercond)
1472 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1474 ExecuteSqlStatement(fout, q->data);
1478 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1480 nfields = PQnfields(res);
1481 for (tuple = 0; tuple < PQntuples(res); tuple++)
1483 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1486 /* corner case for zero-column table */
1487 archprintf(fout, "DEFAULT VALUES;\n");
1492 resetPQExpBuffer(q);
1493 appendPQExpBuffer(q, "(");
1494 for (field = 0; field < nfields; field++)
1497 appendPQExpBuffer(q, ", ");
1498 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1500 appendPQExpBuffer(q, ") ");
1501 archputs(q->data, fout);
1503 archprintf(fout, "VALUES (");
1504 for (field = 0; field < nfields; field++)
1507 archprintf(fout, ", ");
1508 if (PQgetisnull(res, tuple, field))
1510 archprintf(fout, "NULL");
1514 /* XXX This code is partially duplicated in ruleutils.c */
1515 switch (PQftype(res, field))
1526 * These types are printed without quotes unless
1527 * they contain values that aren't accepted by the
1528 * scanner unquoted (e.g., 'NaN'). Note that
1529 * strtod() and friends might accept NaN, so we
1530 * can't use that to test.
1532 * In reality we only need to defend against
1533 * infinity and NaN, so we need not get too crazy
1534 * about pattern matching here.
1536 const char *s = PQgetvalue(res, tuple, field);
1538 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1539 archprintf(fout, "%s", s);
1541 archprintf(fout, "'%s'", s);
1547 archprintf(fout, "B'%s'",
1548 PQgetvalue(res, tuple, field));
1552 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1553 archprintf(fout, "true");
1555 archprintf(fout, "false");
1559 /* All other types are printed as string literals. */
1560 resetPQExpBuffer(q);
1561 appendStringLiteralAH(q,
1562 PQgetvalue(res, tuple, field),
1564 archputs(q->data, fout);
1568 archprintf(fout, ");\n");
1571 if (PQntuples(res) <= 0)
1579 archprintf(fout, "\n\n");
1581 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1583 destroyPQExpBuffer(q);
1590 * dump the contents of a single table
1592 * Actually, this just makes an ArchiveEntry for the table contents.
1595 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1597 TableInfo *tbinfo = tdinfo->tdtable;
1598 PQExpBuffer copyBuf = createPQExpBuffer();
1599 DataDumperPtr dumpFn;
1602 /* don't do anything if the data isn't wanted */
1603 if (!tbinfo->dobj.dumpdata)
1608 /* Dump/restore using COPY */
1609 dumpFn = dumpTableData_copy;
1610 /* must use 2 steps here 'cause fmtId is nonreentrant */
1611 appendPQExpBuffer(copyBuf, "COPY %s ",
1612 fmtId(tbinfo->dobj.name));
1613 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1614 fmtCopyColumnList(tbinfo),
1615 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1616 copyStmt = copyBuf->data;
1620 /* Restore using INSERT */
1621 dumpFn = dumpTableData_insert;
1625 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1626 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1627 NULL, tbinfo->rolname,
1628 false, "TABLE DATA", SECTION_DATA,
1630 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1633 destroyPQExpBuffer(copyBuf);
1638 * set up dumpable objects representing the contents of tables
1641 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1645 for (i = 0; i < numTables; i++)
1647 /* Skip VIEWs (no data to dump) */
1648 if (tblinfo[i].relkind == RELKIND_VIEW)
1650 /* Skip SEQUENCEs (handled elsewhere) */
1651 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1653 /* Skip FOREIGN TABLEs (no data to dump) */
1654 if (tblinfo[i].relkind == RELKIND_FOREIGN_TABLE)
1656 /* Skip unlogged tables if so requested */
1657 if (tblinfo[i].relpersistence == RELPERSISTENCE_UNLOGGED
1658 && no_unlogged_table_data)
1661 if (tblinfo[i].dobj.dump && tblinfo[i].dataObj == NULL)
1662 makeTableDataInfo(&(tblinfo[i]), oids);
1667 * Make a dumpable object for the data of this specific table
1670 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1672 TableDataInfo *tdinfo;
1674 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1676 tdinfo->dobj.objType = DO_TABLE_DATA;
1679 * Note: use tableoid 0 so that this object won't be mistaken for
1680 * something that pg_depend entries apply to.
1682 tdinfo->dobj.catId.tableoid = 0;
1683 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1684 AssignDumpId(&tdinfo->dobj);
1685 tdinfo->dobj.name = tbinfo->dobj.name;
1686 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1687 tdinfo->tdtable = tbinfo;
1688 tdinfo->oids = oids;
1689 tdinfo->filtercond = NULL; /* might get set later */
1690 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1692 tbinfo->dataObj = tdinfo;
1696 * getTableDataFKConstraints -
1697 * add dump-order dependencies reflecting foreign key constraints
1699 * This code is executed only in a data-only dump --- in schema+data dumps
1700 * we handle foreign key issues by not creating the FK constraints until
1701 * after the data is loaded. In a data-only dump, however, we want to
1702 * order the table data objects in such a way that a table's referenced
1703 * tables are restored first. (In the presence of circular references or
1704 * self-references this may be impossible; we'll detect and complain about
1705 * that during the dependency sorting step.)
1708 getTableDataFKConstraints(void)
1710 DumpableObject **dobjs;
1714 /* Search through all the dumpable objects for FK constraints */
1715 getDumpableObjects(&dobjs, &numObjs);
1716 for (i = 0; i < numObjs; i++)
1718 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1720 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1723 /* Not interesting unless both tables are to be dumped */
1724 if (cinfo->contable == NULL ||
1725 cinfo->contable->dataObj == NULL)
1727 ftable = findTableByOid(cinfo->confrelid);
1728 if (ftable == NULL ||
1729 ftable->dataObj == NULL)
1733 * Okay, make referencing table's TABLE_DATA object depend on the
1734 * referenced table's TABLE_DATA object.
1736 addObjectDependency(&cinfo->contable->dataObj->dobj,
1737 ftable->dataObj->dobj.dumpId);
1745 * guessConstraintInheritance:
1746 * In pre-8.4 databases, we can't tell for certain which constraints
1747 * are inherited. We assume a CHECK constraint is inherited if its name
1748 * matches the name of any constraint in the parent. Originally this code
1749 * tried to compare the expression texts, but that can fail for various
1750 * reasons --- for example, if the parent and child tables are in different
1751 * schemas, reverse-listing of function calls may produce different text
1752 * (schema-qualified or not) depending on search path.
1754 * In 8.4 and up we can rely on the conislocal field to decide which
1755 * constraints must be dumped; much safer.
1757 * This function assumes all conislocal flags were initialized to TRUE.
1758 * It clears the flag on anything that seems to be inherited.
1761 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1767 for (i = 0; i < numTables; i++)
1769 TableInfo *tbinfo = &(tblinfo[i]);
1771 TableInfo **parents;
1774 /* Sequences and views never have parents */
1775 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1776 tbinfo->relkind == RELKIND_VIEW)
1779 /* Don't bother computing anything for non-target tables, either */
1780 if (!tbinfo->dobj.dump)
1783 numParents = tbinfo->numParents;
1784 parents = tbinfo->parents;
1786 if (numParents == 0)
1787 continue; /* nothing to see here, move along */
1789 /* scan for inherited CHECK constraints */
1790 for (j = 0; j < tbinfo->ncheck; j++)
1792 ConstraintInfo *constr;
1794 constr = &(tbinfo->checkexprs[j]);
1796 for (k = 0; k < numParents; k++)
1800 parent = parents[k];
1801 for (l = 0; l < parent->ncheck; l++)
1803 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1805 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1807 constr->conislocal = false;
1811 if (!constr->conislocal)
1821 * dump the database definition
1824 dumpDatabase(Archive *fout)
1826 PQExpBuffer dbQry = createPQExpBuffer();
1827 PQExpBuffer delQry = createPQExpBuffer();
1828 PQExpBuffer creaQry = createPQExpBuffer();
1841 const char *datname,
1849 datname = PQdb(g_conn);
1852 write_msg(NULL, "saving database definition\n");
1854 /* Make sure we are in proper schema */
1855 selectSourceSchema(fout, "pg_catalog");
1857 /* Get the database owner and parameters from pg_database */
1858 if (fout->remoteVersion >= 80400)
1860 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1861 "(%s datdba) AS dba, "
1862 "pg_encoding_to_char(encoding) AS encoding, "
1863 "datcollate, datctype, datfrozenxid, "
1864 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1865 "shobj_description(oid, 'pg_database') AS description "
1870 appendStringLiteralAH(dbQry, datname, fout);
1872 else if (fout->remoteVersion >= 80200)
1874 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1875 "(%s datdba) AS dba, "
1876 "pg_encoding_to_char(encoding) AS encoding, "
1877 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1878 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1879 "shobj_description(oid, 'pg_database') AS description "
1884 appendStringLiteralAH(dbQry, datname, fout);
1886 else if (fout->remoteVersion >= 80000)
1888 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1889 "(%s datdba) AS dba, "
1890 "pg_encoding_to_char(encoding) AS encoding, "
1891 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1892 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1896 appendStringLiteralAH(dbQry, datname, fout);
1898 else if (fout->remoteVersion >= 70100)
1900 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1901 "(%s datdba) AS dba, "
1902 "pg_encoding_to_char(encoding) AS encoding, "
1903 "NULL AS datcollate, NULL AS datctype, "
1904 "0 AS datfrozenxid, "
1905 "NULL AS tablespace "
1909 appendStringLiteralAH(dbQry, datname, fout);
1913 appendPQExpBuffer(dbQry, "SELECT "
1914 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1916 "(%s datdba) AS dba, "
1917 "pg_encoding_to_char(encoding) AS encoding, "
1918 "NULL AS datcollate, NULL AS datctype, "
1919 "0 AS datfrozenxid, "
1920 "NULL AS tablespace "
1924 appendStringLiteralAH(dbQry, datname, fout);
1927 res = ExecuteSqlQuery(fout, dbQry->data, PGRES_TUPLES_OK);
1929 ntups = PQntuples(res);
1933 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1940 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1945 i_tableoid = PQfnumber(res, "tableoid");
1946 i_oid = PQfnumber(res, "oid");
1947 i_dba = PQfnumber(res, "dba");
1948 i_encoding = PQfnumber(res, "encoding");
1949 i_collate = PQfnumber(res, "datcollate");
1950 i_ctype = PQfnumber(res, "datctype");
1951 i_frozenxid = PQfnumber(res, "datfrozenxid");
1952 i_tablespace = PQfnumber(res, "tablespace");
1954 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1955 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1956 dba = PQgetvalue(res, 0, i_dba);
1957 encoding = PQgetvalue(res, 0, i_encoding);
1958 collate = PQgetvalue(res, 0, i_collate);
1959 ctype = PQgetvalue(res, 0, i_ctype);
1960 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1961 tablespace = PQgetvalue(res, 0, i_tablespace);
1963 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1965 if (strlen(encoding) > 0)
1967 appendPQExpBuffer(creaQry, " ENCODING = ");
1968 appendStringLiteralAH(creaQry, encoding, fout);
1970 if (strlen(collate) > 0)
1972 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1973 appendStringLiteralAH(creaQry, collate, fout);
1975 if (strlen(ctype) > 0)
1977 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1978 appendStringLiteralAH(creaQry, ctype, fout);
1980 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1981 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1983 appendPQExpBuffer(creaQry, ";\n");
1987 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1988 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1989 "SET datfrozenxid = '%u'\n"
1992 appendStringLiteralAH(creaQry, datname, fout);
1993 appendPQExpBuffer(creaQry, ";\n");
1997 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2000 dbDumpId = createDumpId();
2003 dbCatId, /* catalog ID */
2004 dbDumpId, /* dump ID */
2006 NULL, /* Namespace */
2007 NULL, /* Tablespace */
2009 false, /* with oids */
2010 "DATABASE", /* Desc */
2011 SECTION_PRE_DATA, /* Section */
2012 creaQry->data, /* Create */
2013 delQry->data, /* Del */
2018 NULL); /* Dumper Arg */
2021 * pg_largeobject and pg_largeobject_metadata come from the old system
2022 * intact, so set their relfrozenxids.
2027 PQExpBuffer loFrozenQry = createPQExpBuffer();
2028 PQExpBuffer loOutQry = createPQExpBuffer();
2034 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2035 "FROM pg_catalog.pg_class\n"
2036 "WHERE oid = %u;\n",
2037 LargeObjectRelationId);
2039 lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
2041 if (PQntuples(lo_res) != 1)
2043 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
2047 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2049 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2050 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2051 "SET relfrozenxid = '%u'\n"
2052 "WHERE oid = %u;\n",
2053 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2054 LargeObjectRelationId);
2055 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2056 "pg_largeobject", NULL, NULL, "",
2057 false, "pg_largeobject", SECTION_PRE_DATA,
2058 loOutQry->data, "", NULL,
2065 * pg_largeobject_metadata
2067 if (fout->remoteVersion >= 90000)
2069 resetPQExpBuffer(loFrozenQry);
2070 resetPQExpBuffer(loOutQry);
2072 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2073 "FROM pg_catalog.pg_class\n"
2074 "WHERE oid = %u;\n",
2075 LargeObjectMetadataRelationId);
2077 lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
2079 if (PQntuples(lo_res) != 1)
2081 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject_metadata.relfrozenxid\n");
2085 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2087 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2088 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2089 "SET relfrozenxid = '%u'\n"
2090 "WHERE oid = %u;\n",
2091 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2092 LargeObjectMetadataRelationId);
2093 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2094 "pg_largeobject_metadata", NULL, NULL, "",
2095 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2096 loOutQry->data, "", NULL,
2103 destroyPQExpBuffer(loFrozenQry);
2104 destroyPQExpBuffer(loOutQry);
2107 /* Dump DB comment if any */
2108 if (fout->remoteVersion >= 80200)
2111 * 8.2 keeps comments on shared objects in a shared table, so we
2112 * cannot use the dumpComment used for other database objects.
2114 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2116 if (comment && strlen(comment))
2118 resetPQExpBuffer(dbQry);
2121 * Generates warning when loaded into a differently-named
2124 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2125 appendStringLiteralAH(dbQry, comment, fout);
2126 appendPQExpBuffer(dbQry, ";\n");
2128 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2129 dba, false, "COMMENT", SECTION_NONE,
2130 dbQry->data, "", NULL,
2131 &dbDumpId, 1, NULL, NULL);
2136 resetPQExpBuffer(dbQry);
2137 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2138 dumpComment(fout, dbQry->data, NULL, "",
2139 dbCatId, 0, dbDumpId);
2144 /* Dump shared security label. */
2145 if (!no_security_labels && fout->remoteVersion >= 90200)
2147 PQExpBuffer seclabelQry = createPQExpBuffer();
2149 buildShSecLabelQuery(g_conn, "pg_database", dbCatId.oid, seclabelQry);
2150 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2151 resetPQExpBuffer(seclabelQry);
2152 emitShSecLabels(g_conn, res, seclabelQry, "DATABASE", datname);
2153 if (strlen(seclabelQry->data))
2154 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2155 dba, false, "SECURITY LABEL", SECTION_NONE,
2156 seclabelQry->data, "", NULL,
2157 &dbDumpId, 1, NULL, NULL);
2158 destroyPQExpBuffer(seclabelQry);
2161 destroyPQExpBuffer(dbQry);
2162 destroyPQExpBuffer(delQry);
2163 destroyPQExpBuffer(creaQry);
2168 * dumpEncoding: put the correct encoding into the archive
2171 dumpEncoding(Archive *AH)
2173 const char *encname = pg_encoding_to_char(AH->encoding);
2174 PQExpBuffer qry = createPQExpBuffer();
2177 write_msg(NULL, "saving encoding = %s\n", encname);
2179 appendPQExpBuffer(qry, "SET client_encoding = ");
2180 appendStringLiteralAH(qry, encname, AH);
2181 appendPQExpBuffer(qry, ";\n");
2183 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2184 "ENCODING", NULL, NULL, "",
2185 false, "ENCODING", SECTION_PRE_DATA,
2186 qry->data, "", NULL,
2190 destroyPQExpBuffer(qry);
2195 * dumpStdStrings: put the correct escape string behavior into the archive
2198 dumpStdStrings(Archive *AH)
2200 const char *stdstrings = AH->std_strings ? "on" : "off";
2201 PQExpBuffer qry = createPQExpBuffer();
2204 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2207 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2210 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2211 "STDSTRINGS", NULL, NULL, "",
2212 false, "STDSTRINGS", SECTION_PRE_DATA,
2213 qry->data, "", NULL,
2217 destroyPQExpBuffer(qry);
2223 * Collect schema-level data about large objects
2226 getBlobs(Archive *fout)
2228 PQExpBuffer blobQry = createPQExpBuffer();
2230 DumpableObject *bdata;
2235 /* Verbose message */
2237 write_msg(NULL, "reading large objects\n");
2239 /* Make sure we are in proper schema */
2240 selectSourceSchema(fout, "pg_catalog");
2242 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2243 if (fout->remoteVersion >= 90000)
2244 appendPQExpBuffer(blobQry,
2245 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2246 " FROM pg_largeobject_metadata",
2248 else if (fout->remoteVersion >= 70100)
2249 appendPQExpBuffer(blobQry,
2250 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2251 " FROM pg_largeobject");
2253 appendPQExpBuffer(blobQry,
2254 "SELECT oid, NULL::oid, NULL::oid"
2255 " FROM pg_class WHERE relkind = 'l'");
2257 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2259 ntups = PQntuples(res);
2263 * Each large object has its own BLOB archive entry.
2265 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2267 for (i = 0; i < ntups; i++)
2269 binfo[i].dobj.objType = DO_BLOB;
2270 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2271 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2272 AssignDumpId(&binfo[i].dobj);
2274 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2275 if (!PQgetisnull(res, i, 1))
2276 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2278 binfo[i].rolname = "";
2279 if (!PQgetisnull(res, i, 2))
2280 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2282 binfo[i].blobacl = NULL;
2286 * If we have any large objects, a "BLOBS" archive entry is needed.
2287 * This is just a placeholder for sorting; it carries no data now.
2289 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2290 bdata->objType = DO_BLOB_DATA;
2291 bdata->catId = nilCatalogId;
2292 AssignDumpId(bdata);
2293 bdata->name = pg_strdup("BLOBS");
2297 destroyPQExpBuffer(blobQry);
2303 * dump the definition (metadata) of the given large object
2306 dumpBlob(Archive *fout, BlobInfo *binfo)
2308 PQExpBuffer cquery = createPQExpBuffer();
2309 PQExpBuffer dquery = createPQExpBuffer();
2311 appendPQExpBuffer(cquery,
2312 "SELECT pg_catalog.lo_create('%s');\n",
2315 appendPQExpBuffer(dquery,
2316 "SELECT pg_catalog.lo_unlink('%s');\n",
2319 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2322 binfo->rolname, false,
2323 "BLOB", SECTION_PRE_DATA,
2324 cquery->data, dquery->data, NULL,
2325 binfo->dobj.dependencies, binfo->dobj.nDeps,
2328 /* set up tag for comment and/or ACL */
2329 resetPQExpBuffer(cquery);
2330 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2332 /* Dump comment if any */
2333 dumpComment(fout, cquery->data,
2334 NULL, binfo->rolname,
2335 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2337 /* Dump security label if any */
2338 dumpSecLabel(fout, cquery->data,
2339 NULL, binfo->rolname,
2340 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2342 /* Dump ACL if any */
2344 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2345 binfo->dobj.name, NULL, cquery->data,
2346 NULL, binfo->rolname, binfo->blobacl);
2348 destroyPQExpBuffer(cquery);
2349 destroyPQExpBuffer(dquery);
2354 * dump the data contents of all large objects
2357 dumpBlobs(Archive *fout, void *arg)
2359 const char *blobQry;
2360 const char *blobFetchQry;
2362 char buf[LOBBUFSIZE];
2368 write_msg(NULL, "saving large objects\n");
2370 /* Make sure we are in proper schema */
2371 selectSourceSchema(fout, "pg_catalog");
2374 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2375 * the already-in-memory dumpable objects instead...
2377 if (fout->remoteVersion >= 90000)
2378 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2379 else if (fout->remoteVersion >= 70100)
2380 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2382 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2384 ExecuteSqlStatement(fout, blobQry);
2386 /* Command to fetch from cursor */
2387 blobFetchQry = "FETCH 1000 IN bloboid";
2392 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2394 /* Process the tuples, if any */
2395 ntups = PQntuples(res);
2396 for (i = 0; i < ntups; i++)
2401 blobOid = atooid(PQgetvalue(res, i, 0));
2403 loFd = lo_open(g_conn, blobOid, INV_READ);
2406 write_msg(NULL, "could not open large object %u: %s",
2407 blobOid, PQerrorMessage(g_conn));
2411 StartBlob(fout, blobOid);
2413 /* Now read it in chunks, sending data to archive */
2416 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2419 write_msg(NULL, "error reading large object %u: %s",
2420 blobOid, PQerrorMessage(g_conn));
2424 WriteData(fout, buf, cnt);
2427 lo_close(g_conn, loFd);
2429 EndBlob(fout, blobOid);
2433 } while (ntups > 0);
2441 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2442 PQExpBuffer upgrade_buffer,
2445 PQExpBuffer upgrade_query = createPQExpBuffer();
2447 PGresult *upgrade_res;
2448 Oid pg_type_array_oid;
2450 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2451 appendPQExpBuffer(upgrade_buffer,
2452 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2455 /* we only support old >= 8.3 for binary upgrades */
2456 appendPQExpBuffer(upgrade_query,
2458 "FROM pg_catalog.pg_type "
2459 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2462 upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2464 /* Expecting a single result only */
2465 ntups = PQntuples(upgrade_res);
2468 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2469 "query returned %d rows instead of one: %s\n",
2471 ntups, upgrade_query->data);
2475 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2477 if (OidIsValid(pg_type_array_oid))
2479 appendPQExpBuffer(upgrade_buffer,
2480 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2481 appendPQExpBuffer(upgrade_buffer,
2482 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2486 PQclear(upgrade_res);
2487 destroyPQExpBuffer(upgrade_query);
2491 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2492 PQExpBuffer upgrade_buffer,
2495 PQExpBuffer upgrade_query = createPQExpBuffer();
2497 PGresult *upgrade_res;
2499 bool toast_set = false;
2501 /* we only support old >= 8.3 for binary upgrades */
2502 appendPQExpBuffer(upgrade_query,
2503 "SELECT c.reltype AS crel, t.reltype AS trel "
2504 "FROM pg_catalog.pg_class c "
2505 "LEFT JOIN pg_catalog.pg_class t ON "
2506 " (c.reltoastrelid = t.oid) "
2507 "WHERE c.oid = '%u'::pg_catalog.oid;",
2510 upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2512 /* Expecting a single result only */
2513 ntups = PQntuples(upgrade_res);
2516 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2517 "query returned %d rows instead of one: %s\n",
2519 ntups, upgrade_query->data);
2523 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2525 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2528 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2530 /* Toast tables do not have pg_type array rows */
2531 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2532 PQfnumber(upgrade_res, "trel")));
2534 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2535 appendPQExpBuffer(upgrade_buffer,
2536 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2542 PQclear(upgrade_res);
2543 destroyPQExpBuffer(upgrade_query);
2549 binary_upgrade_set_pg_class_oids(Archive *fout,
2550 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2553 PQExpBuffer upgrade_query = createPQExpBuffer();
2555 PGresult *upgrade_res;
2556 Oid pg_class_reltoastrelid;
2557 Oid pg_class_reltoastidxid;
2559 appendPQExpBuffer(upgrade_query,
2560 "SELECT c.reltoastrelid, t.reltoastidxid "
2561 "FROM pg_catalog.pg_class c LEFT JOIN "
2562 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2563 "WHERE c.oid = '%u'::pg_catalog.oid;",
2566 upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2568 /* Expecting a single result only */
2569 ntups = PQntuples(upgrade_res);
2572 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2573 "query returned %d rows instead of one: %s\n",
2575 ntups, upgrade_query->data);
2579 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2580 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2582 appendPQExpBuffer(upgrade_buffer,
2583 "\n-- For binary upgrade, must preserve pg_class oids\n");
2587 appendPQExpBuffer(upgrade_buffer,
2588 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2590 /* only tables have toast tables, not indexes */
2591 if (OidIsValid(pg_class_reltoastrelid))
2594 * One complexity is that the table definition might not require
2595 * the creation of a TOAST table, and the TOAST table might have
2596 * been created long after table creation, when the table was
2597 * loaded with wide data. By setting the TOAST oid we force
2598 * creation of the TOAST heap and TOAST index by the backend so we
2599 * can cleanly copy the files during binary upgrade.
2602 appendPQExpBuffer(upgrade_buffer,
2603 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2604 pg_class_reltoastrelid);
2606 /* every toast table has an index */
2607 appendPQExpBuffer(upgrade_buffer,
2608 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2609 pg_class_reltoastidxid);
2613 appendPQExpBuffer(upgrade_buffer,
2614 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2617 appendPQExpBuffer(upgrade_buffer, "\n");
2619 PQclear(upgrade_res);
2620 destroyPQExpBuffer(upgrade_query);
2624 * If the DumpableObject is a member of an extension, add a suitable
2625 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2628 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2629 DumpableObject *dobj,
2630 const char *objlabel)
2632 DumpableObject *extobj = NULL;
2635 if (!dobj->ext_member)
2639 * Find the parent extension. We could avoid this search if we wanted to
2640 * add a link field to DumpableObject, but the space costs of that would
2641 * be considerable. We assume that member objects could only have a
2642 * direct dependency on their own extension, not any others.
2644 for (i = 0; i < dobj->nDeps; i++)
2646 extobj = findObjectByDumpId(dobj->dependencies[i]);
2647 if (extobj && extobj->objType == DO_EXTENSION)
2653 write_msg(NULL, "could not find parent extension for %s", objlabel);
2657 appendPQExpBuffer(upgrade_buffer,
2658 "\n-- For binary upgrade, handle extension membership the hard way\n");
2659 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2660 fmtId(extobj->name),
2666 * read all namespaces in the system catalogs and return them in the
2667 * NamespaceInfo* structure
2669 * numNamespaces is set to the number of namespaces read in
2672 getNamespaces(Archive *fout, int *numNamespaces)
2678 NamespaceInfo *nsinfo;
2686 * Before 7.3, there are no real namespaces; create two dummy entries, one
2687 * for user stuff and one for system stuff.
2689 if (fout->remoteVersion < 70300)
2691 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2693 nsinfo[0].dobj.objType = DO_NAMESPACE;
2694 nsinfo[0].dobj.catId.tableoid = 0;
2695 nsinfo[0].dobj.catId.oid = 0;
2696 AssignDumpId(&nsinfo[0].dobj);
2697 nsinfo[0].dobj.name = pg_strdup("public");
2698 nsinfo[0].rolname = pg_strdup("");
2699 nsinfo[0].nspacl = pg_strdup("");
2701 selectDumpableNamespace(&nsinfo[0]);
2703 nsinfo[1].dobj.objType = DO_NAMESPACE;
2704 nsinfo[1].dobj.catId.tableoid = 0;
2705 nsinfo[1].dobj.catId.oid = 1;
2706 AssignDumpId(&nsinfo[1].dobj);
2707 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2708 nsinfo[1].rolname = pg_strdup("");
2709 nsinfo[1].nspacl = pg_strdup("");
2711 selectDumpableNamespace(&nsinfo[1]);
2713 g_namespaces = nsinfo;
2714 g_numNamespaces = *numNamespaces = 2;
2719 query = createPQExpBuffer();
2721 /* Make sure we are in proper schema */
2722 selectSourceSchema(fout, "pg_catalog");
2725 * we fetch all namespaces including system ones, so that every object we
2726 * read in can be linked to a containing namespace.
2728 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2729 "(%s nspowner) AS rolname, "
2730 "nspacl FROM pg_namespace",
2733 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2735 ntups = PQntuples(res);
2737 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2739 i_tableoid = PQfnumber(res, "tableoid");
2740 i_oid = PQfnumber(res, "oid");
2741 i_nspname = PQfnumber(res, "nspname");
2742 i_rolname = PQfnumber(res, "rolname");
2743 i_nspacl = PQfnumber(res, "nspacl");
2745 for (i = 0; i < ntups; i++)
2747 nsinfo[i].dobj.objType = DO_NAMESPACE;
2748 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2749 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2750 AssignDumpId(&nsinfo[i].dobj);
2751 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2752 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2753 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2755 /* Decide whether to dump this namespace */
2756 selectDumpableNamespace(&nsinfo[i]);
2758 if (strlen(nsinfo[i].rolname) == 0)
2759 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2760 nsinfo[i].dobj.name);
2764 destroyPQExpBuffer(query);
2766 g_namespaces = nsinfo;
2767 g_numNamespaces = *numNamespaces = ntups;
2774 * given a namespace OID and an object OID, look up the info read by
2777 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2778 * a system object or not. In 7.3 and later there is no guessing.
2780 static NamespaceInfo *
2781 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2785 if (fout->remoteVersion >= 70300)
2787 for (i = 0; i < g_numNamespaces; i++)
2789 NamespaceInfo *nsinfo = &g_namespaces[i];
2791 if (nsoid == nsinfo->dobj.catId.oid)
2794 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2799 /* This code depends on the layout set up by getNamespaces. */
2800 if (objoid > g_last_builtin_oid)
2801 i = 0; /* user object */
2803 i = 1; /* system object */
2804 return &g_namespaces[i];
2807 return NULL; /* keep compiler quiet */
2812 * read all extensions in the system catalogs and return them in the
2813 * ExtensionInfo* structure
2815 * numExtensions is set to the number of extensions read in
2818 getExtensions(Archive *fout, int *numExtensions)
2824 ExtensionInfo *extinfo;
2829 int i_extrelocatable;
2835 * Before 9.1, there are no extensions.
2837 if (fout->remoteVersion < 90100)
2843 query = createPQExpBuffer();
2845 /* Make sure we are in proper schema */
2846 selectSourceSchema(fout, "pg_catalog");
2848 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2849 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2850 "FROM pg_extension x "
2851 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2853 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2855 ntups = PQntuples(res);
2857 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2859 i_tableoid = PQfnumber(res, "tableoid");
2860 i_oid = PQfnumber(res, "oid");
2861 i_extname = PQfnumber(res, "extname");
2862 i_nspname = PQfnumber(res, "nspname");
2863 i_extrelocatable = PQfnumber(res, "extrelocatable");
2864 i_extversion = PQfnumber(res, "extversion");
2865 i_extconfig = PQfnumber(res, "extconfig");
2866 i_extcondition = PQfnumber(res, "extcondition");
2868 for (i = 0; i < ntups; i++)
2870 extinfo[i].dobj.objType = DO_EXTENSION;
2871 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2872 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2873 AssignDumpId(&extinfo[i].dobj);
2874 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2875 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2876 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2877 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2878 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2879 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2881 /* Decide whether we want to dump it */
2882 selectDumpableExtension(&(extinfo[i]));
2886 destroyPQExpBuffer(query);
2888 *numExtensions = ntups;
2895 * read all types in the system catalogs and return them in the
2896 * TypeInfo* structure
2898 * numTypes is set to the number of types read in
2900 * NB: this must run after getFuncs() because we assume we can do
2904 getTypes(Archive *fout, int *numTypes)
2909 PQExpBuffer query = createPQExpBuffer();
2911 ShellTypeInfo *stinfo;
2927 * we include even the built-in types because those may be used as array
2928 * elements by user-defined types
2930 * we filter out the built-in types when we dump out the types
2932 * same approach for undefined (shell) types and array types
2934 * Note: as of 8.3 we can reliably detect whether a type is an
2935 * auto-generated array type by checking the element type's typarray.
2936 * (Before that the test is capable of generating false positives.) We
2937 * still check for name beginning with '_', though, so as to avoid the
2938 * cost of the subselect probe for all standard types. This would have to
2939 * be revisited if the backend ever allows renaming of array types.
2942 /* Make sure we are in proper schema */
2943 selectSourceSchema(fout, "pg_catalog");
2945 if (fout->remoteVersion >= 80300)
2947 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2949 "(%s typowner) AS rolname, "
2950 "typinput::oid AS typinput, "
2951 "typoutput::oid AS typoutput, typelem, typrelid, "
2952 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2953 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2954 "typtype, typisdefined, "
2955 "typname[0] = '_' AND typelem != 0 AND "
2956 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2960 else if (fout->remoteVersion >= 70300)
2962 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2964 "(%s typowner) AS rolname, "
2965 "typinput::oid AS typinput, "
2966 "typoutput::oid AS typoutput, typelem, typrelid, "
2967 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2968 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2969 "typtype, typisdefined, "
2970 "typname[0] = '_' AND typelem != 0 AS isarray "
2974 else if (fout->remoteVersion >= 70100)
2976 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2977 "0::oid AS typnamespace, "
2978 "(%s typowner) AS rolname, "
2979 "typinput::oid AS typinput, "
2980 "typoutput::oid AS typoutput, typelem, typrelid, "
2981 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2982 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2983 "typtype, typisdefined, "
2984 "typname[0] = '_' AND typelem != 0 AS isarray "
2990 appendPQExpBuffer(query, "SELECT "
2991 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2993 "0::oid AS typnamespace, "
2994 "(%s typowner) AS rolname, "
2995 "typinput::oid AS typinput, "
2996 "typoutput::oid AS typoutput, typelem, typrelid, "
2997 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2998 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2999 "typtype, typisdefined, "
3000 "typname[0] = '_' AND typelem != 0 AS isarray "
3005 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3007 ntups = PQntuples(res);
3009 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3011 i_tableoid = PQfnumber(res, "tableoid");
3012 i_oid = PQfnumber(res, "oid");
3013 i_typname = PQfnumber(res, "typname");
3014 i_typnamespace = PQfnumber(res, "typnamespace");
3015 i_rolname = PQfnumber(res, "rolname");
3016 i_typinput = PQfnumber(res, "typinput");
3017 i_typoutput = PQfnumber(res, "typoutput");
3018 i_typelem = PQfnumber(res, "typelem");
3019 i_typrelid = PQfnumber(res, "typrelid");
3020 i_typrelkind = PQfnumber(res, "typrelkind");
3021 i_typtype = PQfnumber(res, "typtype");
3022 i_typisdefined = PQfnumber(res, "typisdefined");
3023 i_isarray = PQfnumber(res, "isarray");
3025 for (i = 0; i < ntups; i++)
3027 tyinfo[i].dobj.objType = DO_TYPE;
3028 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3029 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3030 AssignDumpId(&tyinfo[i].dobj);
3031 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3032 tyinfo[i].dobj.namespace =
3034 atooid(PQgetvalue(res, i, i_typnamespace)),
3035 tyinfo[i].dobj.catId.oid);
3036 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3037 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3038 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3039 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3040 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3041 tyinfo[i].shellType = NULL;
3043 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3044 tyinfo[i].isDefined = true;
3046 tyinfo[i].isDefined = false;
3048 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3049 tyinfo[i].isArray = true;
3051 tyinfo[i].isArray = false;
3053 /* Decide whether we want to dump it */
3054 selectDumpableType(&tyinfo[i]);
3057 * If it's a domain, fetch info about its constraints, if any
3059 tyinfo[i].nDomChecks = 0;
3060 tyinfo[i].domChecks = NULL;
3061 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3062 getDomainConstraints(fout, &(tyinfo[i]));
3065 * If it's a base type, make a DumpableObject representing a shell
3066 * definition of the type. We will need to dump that ahead of the I/O
3067 * functions for the type. Similarly, range types need a shell
3068 * definition in case they have a canonicalize function.
3070 * Note: the shell type doesn't have a catId. You might think it
3071 * should copy the base type's catId, but then it might capture the
3072 * pg_depend entries for the type, which we don't want.
3074 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3075 tyinfo[i].typtype == TYPTYPE_RANGE))
3077 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3078 stinfo->dobj.objType = DO_SHELL_TYPE;
3079 stinfo->dobj.catId = nilCatalogId;
3080 AssignDumpId(&stinfo->dobj);
3081 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3082 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3083 stinfo->baseType = &(tyinfo[i]);
3084 tyinfo[i].shellType = stinfo;
3087 * Initially mark the shell type as not to be dumped. We'll only
3088 * dump it if the I/O or canonicalize functions need to be dumped;
3089 * this is taken care of while sorting dependencies.
3091 stinfo->dobj.dump = false;
3094 * However, if dumping from pre-7.3, there will be no dependency
3095 * info so we have to fake it here. We only need to worry about
3096 * typinput and typoutput since the other functions only exist
3099 if (fout->remoteVersion < 70300)
3105 typinput = atooid(PQgetvalue(res, i, i_typinput));
3106 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3108 funcInfo = findFuncByOid(typinput);
3109 if (funcInfo && funcInfo->dobj.dump)
3111 /* base type depends on function */
3112 addObjectDependency(&tyinfo[i].dobj,
3113 funcInfo->dobj.dumpId);
3114 /* function depends on shell type */
3115 addObjectDependency(&funcInfo->dobj,
3116 stinfo->dobj.dumpId);
3117 /* mark shell type as to be dumped */
3118 stinfo->dobj.dump = true;
3121 funcInfo = findFuncByOid(typoutput);
3122 if (funcInfo && funcInfo->dobj.dump)
3124 /* base type depends on function */
3125 addObjectDependency(&tyinfo[i].dobj,
3126 funcInfo->dobj.dumpId);
3127 /* function depends on shell type */
3128 addObjectDependency(&funcInfo->dobj,
3129 stinfo->dobj.dumpId);
3130 /* mark shell type as to be dumped */
3131 stinfo->dobj.dump = true;
3136 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3137 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3138 tyinfo[i].dobj.name);
3145 destroyPQExpBuffer(query);
3152 * read all operators in the system catalogs and return them in the
3153 * OprInfo* structure
3155 * numOprs is set to the number of operators read in
3158 getOperators(Archive *fout, int *numOprs)
3163 PQExpBuffer query = createPQExpBuffer();
3174 * find all operators, including builtin operators; we filter out
3175 * system-defined operators at dump-out time.
3178 /* Make sure we are in proper schema */
3179 selectSourceSchema(fout, "pg_catalog");
3181 if (fout->remoteVersion >= 70300)
3183 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3185 "(%s oprowner) AS rolname, "
3187 "oprcode::oid AS oprcode "
3191 else if (fout->remoteVersion >= 70100)
3193 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3194 "0::oid AS oprnamespace, "
3195 "(%s oprowner) AS rolname, "
3197 "oprcode::oid AS oprcode "
3203 appendPQExpBuffer(query, "SELECT "
3204 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3206 "0::oid AS oprnamespace, "
3207 "(%s oprowner) AS rolname, "
3209 "oprcode::oid AS oprcode "
3214 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3216 ntups = PQntuples(res);
3219 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3221 i_tableoid = PQfnumber(res, "tableoid");
3222 i_oid = PQfnumber(res, "oid");
3223 i_oprname = PQfnumber(res, "oprname");
3224 i_oprnamespace = PQfnumber(res, "oprnamespace");
3225 i_rolname = PQfnumber(res, "rolname");
3226 i_oprkind = PQfnumber(res, "oprkind");
3227 i_oprcode = PQfnumber(res, "oprcode");
3229 for (i = 0; i < ntups; i++)
3231 oprinfo[i].dobj.objType = DO_OPERATOR;
3232 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3233 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3234 AssignDumpId(&oprinfo[i].dobj);
3235 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3236 oprinfo[i].dobj.namespace =
3238 atooid(PQgetvalue(res, i, i_oprnamespace)),
3239 oprinfo[i].dobj.catId.oid);
3240 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3241 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3242 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3244 /* Decide whether we want to dump it */
3245 selectDumpableObject(&(oprinfo[i].dobj));
3247 if (strlen(oprinfo[i].rolname) == 0)
3248 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3249 oprinfo[i].dobj.name);
3254 destroyPQExpBuffer(query);
3261 * read all collations in the system catalogs and return them in the
3262 * CollInfo* structure
3264 * numCollations is set to the number of collations read in
3267 getCollations(Archive *fout, int *numCollations)
3272 PQExpBuffer query = createPQExpBuffer();
3277 int i_collnamespace;
3280 /* Collations didn't exist pre-9.1 */
3281 if (fout->remoteVersion < 90100)
3288 * find all collations, including builtin collations; we filter out
3289 * system-defined collations at dump-out time.
3292 /* Make sure we are in proper schema */
3293 selectSourceSchema(fout, "pg_catalog");
3295 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3297 "(%s collowner) AS rolname "
3298 "FROM pg_collation",
3301 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3303 ntups = PQntuples(res);
3304 *numCollations = ntups;
3306 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3308 i_tableoid = PQfnumber(res, "tableoid");
3309 i_oid = PQfnumber(res, "oid");
3310 i_collname = PQfnumber(res, "collname");
3311 i_collnamespace = PQfnumber(res, "collnamespace");
3312 i_rolname = PQfnumber(res, "rolname");
3314 for (i = 0; i < ntups; i++)
3316 collinfo[i].dobj.objType = DO_COLLATION;
3317 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3318 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3319 AssignDumpId(&collinfo[i].dobj);
3320 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3321 collinfo[i].dobj.namespace =
3323 atooid(PQgetvalue(res, i, i_collnamespace)),
3324 collinfo[i].dobj.catId.oid);
3325 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3327 /* Decide whether we want to dump it */
3328 selectDumpableObject(&(collinfo[i].dobj));
3333 destroyPQExpBuffer(query);
3340 * read all conversions in the system catalogs and return them in the
3341 * ConvInfo* structure
3343 * numConversions is set to the number of conversions read in
3346 getConversions(Archive *fout, int *numConversions)
3351 PQExpBuffer query = createPQExpBuffer();
3359 /* Conversions didn't exist pre-7.3 */
3360 if (fout->remoteVersion < 70300)
3362 *numConversions = 0;
3367 * find all conversions, including builtin conversions; we filter out
3368 * system-defined conversions at dump-out time.
3371 /* Make sure we are in proper schema */
3372 selectSourceSchema(fout, "pg_catalog");
3374 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3376 "(%s conowner) AS rolname "
3377 "FROM pg_conversion",
3380 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3382 ntups = PQntuples(res);
3383 *numConversions = ntups;
3385 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3387 i_tableoid = PQfnumber(res, "tableoid");
3388 i_oid = PQfnumber(res, "oid");
3389 i_conname = PQfnumber(res, "conname");
3390 i_connamespace = PQfnumber(res, "connamespace");
3391 i_rolname = PQfnumber(res, "rolname");
3393 for (i = 0; i < ntups; i++)
3395 convinfo[i].dobj.objType = DO_CONVERSION;
3396 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3397 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3398 AssignDumpId(&convinfo[i].dobj);
3399 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3400 convinfo[i].dobj.namespace =
3402 atooid(PQgetvalue(res, i, i_connamespace)),
3403 convinfo[i].dobj.catId.oid);
3404 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3406 /* Decide whether we want to dump it */
3407 selectDumpableObject(&(convinfo[i].dobj));
3412 destroyPQExpBuffer(query);
3419 * read all opclasses in the system catalogs and return them in the
3420 * OpclassInfo* structure
3422 * numOpclasses is set to the number of opclasses read in
3425 getOpclasses(Archive *fout, int *numOpclasses)
3430 PQExpBuffer query = createPQExpBuffer();
3431 OpclassInfo *opcinfo;
3439 * find all opclasses, including builtin opclasses; we filter out
3440 * system-defined opclasses at dump-out time.
3443 /* Make sure we are in proper schema */
3444 selectSourceSchema(fout, "pg_catalog");
3446 if (fout->remoteVersion >= 70300)
3448 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3450 "(%s opcowner) AS rolname "
3454 else if (fout->remoteVersion >= 70100)
3456 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3457 "0::oid AS opcnamespace, "
3458 "''::name AS rolname "
3463 appendPQExpBuffer(query, "SELECT "
3464 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3466 "0::oid AS opcnamespace, "
3467 "''::name AS rolname "
3471 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3473 ntups = PQntuples(res);
3474 *numOpclasses = ntups;
3476 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3478 i_tableoid = PQfnumber(res, "tableoid");
3479 i_oid = PQfnumber(res, "oid");
3480 i_opcname = PQfnumber(res, "opcname");
3481 i_opcnamespace = PQfnumber(res, "opcnamespace");
3482 i_rolname = PQfnumber(res, "rolname");
3484 for (i = 0; i < ntups; i++)
3486 opcinfo[i].dobj.objType = DO_OPCLASS;
3487 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3488 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3489 AssignDumpId(&opcinfo[i].dobj);
3490 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3491 opcinfo[i].dobj.namespace =
3493 atooid(PQgetvalue(res, i, i_opcnamespace)),
3494 opcinfo[i].dobj.catId.oid);
3495 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3497 /* Decide whether we want to dump it */
3498 selectDumpableObject(&(opcinfo[i].dobj));
3500 if (fout->remoteVersion >= 70300)
3502 if (strlen(opcinfo[i].rolname) == 0)
3503 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3504 opcinfo[i].dobj.name);
3510 destroyPQExpBuffer(query);
3517 * read all opfamilies in the system catalogs and return them in the
3518 * OpfamilyInfo* structure
3520 * numOpfamilies is set to the number of opfamilies read in
3523 getOpfamilies(Archive *fout, int *numOpfamilies)
3529 OpfamilyInfo *opfinfo;
3536 /* Before 8.3, there is no separate concept of opfamilies */
3537 if (fout->remoteVersion < 80300)
3543 query = createPQExpBuffer();
3546 * find all opfamilies, including builtin opfamilies; we filter out
3547 * system-defined opfamilies at dump-out time.
3550 /* Make sure we are in proper schema */
3551 selectSourceSchema(fout, "pg_catalog");
3553 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3555 "(%s opfowner) AS rolname "
3559 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3561 ntups = PQntuples(res);
3562 *numOpfamilies = ntups;
3564 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3566 i_tableoid = PQfnumber(res, "tableoid");
3567 i_oid = PQfnumber(res, "oid");
3568 i_opfname = PQfnumber(res, "opfname");
3569 i_opfnamespace = PQfnumber(res, "opfnamespace");
3570 i_rolname = PQfnumber(res, "rolname");
3572 for (i = 0; i < ntups; i++)
3574 opfinfo[i].dobj.objType = DO_OPFAMILY;
3575 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3576 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3577 AssignDumpId(&opfinfo[i].dobj);
3578 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3579 opfinfo[i].dobj.namespace =
3581 atooid(PQgetvalue(res, i, i_opfnamespace)),
3582 opfinfo[i].dobj.catId.oid);
3583 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3585 /* Decide whether we want to dump it */
3586 selectDumpableObject(&(opfinfo[i].dobj));
3588 if (fout->remoteVersion >= 70300)
3590 if (strlen(opfinfo[i].rolname) == 0)
3591 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3592 opfinfo[i].dobj.name);
3598 destroyPQExpBuffer(query);
3605 * read all the user-defined aggregates in the system catalogs and
3606 * return them in the AggInfo* structure
3608 * numAggs is set to the number of aggregates read in
3611 getAggregates(Archive *fout, int *numAggs)
3616 PQExpBuffer query = createPQExpBuffer();
3627 /* Make sure we are in proper schema */
3628 selectSourceSchema(fout, "pg_catalog");
3631 * Find all user-defined aggregates. See comment in getFuncs() for the
3632 * rationale behind the filtering logic.
3635 if (fout->remoteVersion >= 80200)
3637 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3638 "pronamespace AS aggnamespace, "
3639 "pronargs, proargtypes, "
3640 "(%s proowner) AS rolname, "
3643 "WHERE proisagg AND ("
3645 "(SELECT oid FROM pg_namespace "
3646 "WHERE nspname = 'pg_catalog')",
3648 if (binary_upgrade && fout->remoteVersion >= 90100)
3649 appendPQExpBuffer(query,
3650 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3651 "classid = 'pg_proc'::regclass AND "
3652 "objid = p.oid AND "
3653 "refclassid = 'pg_extension'::regclass AND "
3655 appendPQExpBuffer(query, ")");
3657 else if (fout->remoteVersion >= 70300)
3659 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3660 "pronamespace AS aggnamespace, "
3661 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3663 "(%s proowner) AS rolname, "
3667 "AND pronamespace != "
3668 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3671 else if (fout->remoteVersion >= 70100)
3673 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3674 "0::oid AS aggnamespace, "
3675 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3676 "aggbasetype AS proargtypes, "
3677 "(%s aggowner) AS rolname, "
3679 "FROM pg_aggregate "
3680 "where oid > '%u'::oid",
3682 g_last_builtin_oid);
3686 appendPQExpBuffer(query, "SELECT "
3687 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3689 "0::oid AS aggnamespace, "
3690 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3691 "aggbasetype AS proargtypes, "
3692 "(%s aggowner) AS rolname, "
3694 "FROM pg_aggregate "
3695 "where oid > '%u'::oid",
3697 g_last_builtin_oid);
3700 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3702 ntups = PQntuples(res);
3705 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3707 i_tableoid = PQfnumber(res, "tableoid");
3708 i_oid = PQfnumber(res, "oid");
3709 i_aggname = PQfnumber(res, "aggname");
3710 i_aggnamespace = PQfnumber(res, "aggnamespace");
3711 i_pronargs = PQfnumber(res, "pronargs");
3712 i_proargtypes = PQfnumber(res, "proargtypes");
3713 i_rolname = PQfnumber(res, "rolname");
3714 i_aggacl = PQfnumber(res, "aggacl");
3716 for (i = 0; i < ntups; i++)
3718 agginfo[i].aggfn.dobj.objType = DO_AGG;
3719 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3720 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3721 AssignDumpId(&agginfo[i].aggfn.dobj);
3722 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3723 agginfo[i].aggfn.dobj.namespace =
3725 atooid(PQgetvalue(res, i, i_aggnamespace)),
3726 agginfo[i].aggfn.dobj.catId.oid);
3727 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3728 if (strlen(agginfo[i].aggfn.rolname) == 0)
3729 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3730 agginfo[i].aggfn.dobj.name);
3731 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3732 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3733 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3734 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3735 if (agginfo[i].aggfn.nargs == 0)
3736 agginfo[i].aggfn.argtypes = NULL;
3739 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3740 if (fout->remoteVersion >= 70300)
3741 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3742 agginfo[i].aggfn.argtypes,
3743 agginfo[i].aggfn.nargs);
3745 /* it's just aggbasetype */
3746 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3749 /* Decide whether we want to dump it */
3750 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3755 destroyPQExpBuffer(query);
3762 * read all the user-defined functions in the system catalogs and
3763 * return them in the FuncInfo* structure
3765 * numFuncs is set to the number of functions read in
3768 getFuncs(Archive *fout, int *numFuncs)
3773 PQExpBuffer query = createPQExpBuffer();
3786 /* Make sure we are in proper schema */
3787 selectSourceSchema(fout, "pg_catalog");
3790 * Find all user-defined functions. Normally we can exclude functions in
3791 * pg_catalog, which is worth doing since there are several thousand of
3792 * 'em. However, there are some extensions that create functions in
3793 * pg_catalog. In normal dumps we can still ignore those --- but in
3794 * binary-upgrade mode, we must dump the member objects of the extension,
3795 * so be sure to fetch any such functions.
3797 * Also, in 9.2 and up, exclude functions that are internally dependent on
3798 * something else, since presumably those will be created as a result of
3799 * creating the something else. This currently only acts to suppress
3800 * constructor functions for range types. Note that this is OK only
3801 * because the constructors don't have any dependencies the range type
3802 * doesn't have; otherwise we might not get creation ordering correct.
3805 if (fout->remoteVersion >= 70300)
3807 appendPQExpBuffer(query,
3808 "SELECT tableoid, oid, proname, prolang, "
3809 "pronargs, proargtypes, prorettype, proacl, "
3811 "(%s proowner) AS rolname "
3813 "WHERE NOT proisagg AND ("
3815 "(SELECT oid FROM pg_namespace "
3816 "WHERE nspname = 'pg_catalog')",
3818 if (fout->remoteVersion >= 90200)
3819 appendPQExpBuffer(query,
3820 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3821 "WHERE classid = 'pg_proc'::regclass AND "
3822 "objid = p.oid AND deptype = 'i')");
3823 if (binary_upgrade && fout->remoteVersion >= 90100)
3824 appendPQExpBuffer(query,
3825 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3826 "classid = 'pg_proc'::regclass AND "
3827 "objid = p.oid AND "
3828 "refclassid = 'pg_extension'::regclass AND "
3830 appendPQExpBuffer(query, ")");
3832 else if (fout->remoteVersion >= 70100)
3834 appendPQExpBuffer(query,
3835 "SELECT tableoid, oid, proname, prolang, "
3836 "pronargs, proargtypes, prorettype, "
3837 "'{=X}' AS proacl, "
3838 "0::oid AS pronamespace, "
3839 "(%s proowner) AS rolname "
3841 "WHERE pg_proc.oid > '%u'::oid",
3843 g_last_builtin_oid);
3847 appendPQExpBuffer(query,
3849 "(SELECT oid FROM pg_class "
3850 " WHERE relname = 'pg_proc') AS tableoid, "
3851 "oid, proname, prolang, "
3852 "pronargs, proargtypes, prorettype, "
3853 "'{=X}' AS proacl, "
3854 "0::oid AS pronamespace, "
3855 "(%s proowner) AS rolname "
3857 "where pg_proc.oid > '%u'::oid",
3859 g_last_builtin_oid);
3862 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3864 ntups = PQntuples(res);
3868 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3870 i_tableoid = PQfnumber(res, "tableoid");
3871 i_oid = PQfnumber(res, "oid");
3872 i_proname = PQfnumber(res, "proname");
3873 i_pronamespace = PQfnumber(res, "pronamespace");
3874 i_rolname = PQfnumber(res, "rolname");
3875 i_prolang = PQfnumber(res, "prolang");
3876 i_pronargs = PQfnumber(res, "pronargs");
3877 i_proargtypes = PQfnumber(res, "proargtypes");
3878 i_prorettype = PQfnumber(res, "prorettype");
3879 i_proacl = PQfnumber(res, "proacl");
3881 for (i = 0; i < ntups; i++)
3883 finfo[i].dobj.objType = DO_FUNC;
3884 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3885 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3886 AssignDumpId(&finfo[i].dobj);
3887 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3888 finfo[i].dobj.namespace =
3890 atooid(PQgetvalue(res, i, i_pronamespace)),
3891 finfo[i].dobj.catId.oid);
3892 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3893 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3894 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3895 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3896 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3897 if (finfo[i].nargs == 0)
3898 finfo[i].argtypes = NULL;
3901 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3902 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3903 finfo[i].argtypes, finfo[i].nargs);
3906 /* Decide whether we want to dump it */
3907 selectDumpableObject(&(finfo[i].dobj));
3909 if (strlen(finfo[i].rolname) == 0)
3911 "WARNING: owner of function \"%s\" appears to be invalid\n",
3912 finfo[i].dobj.name);
3917 destroyPQExpBuffer(query);
3924 * read all the user-defined tables (no indexes, no catalogs)
3925 * in the system catalogs return them in the TableInfo* structure
3927 * numTables is set to the number of tables read in
3930 getTables(Archive *fout, int *numTables)
3935 PQExpBuffer query = createPQExpBuffer();
3945 int i_relhastriggers;
3951 int i_toastfrozenxid;
3952 int i_relpersistence;
3955 int i_reltablespace;
3957 int i_toastreloptions;
3960 /* Make sure we are in proper schema */
3961 selectSourceSchema(fout, "pg_catalog");
3964 * Find all the tables (including views and sequences).
3966 * We include system catalogs, so that we can work if a user table is
3967 * defined to inherit from a system catalog (pretty weird, but...)
3969 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3970 * (sequence), 'v' (view), or 'c' (composite type).
3972 * Composite-type table entries won't be dumped as such, but we have to
3973 * make a DumpableObject for them so that we can track dependencies of the
3974 * composite type (pg_depend entries for columns of the composite type
3975 * link to the pg_class entry not the pg_type entry).
3977 * Note: in this phase we should collect only a minimal amount of
3978 * information about each table, basically just enough to decide if it is
3979 * interesting. We must fetch all tables in this phase because otherwise
3980 * we cannot correctly identify inherited columns, owned sequences, etc.
3983 if (fout->remoteVersion >= 90100)
3986 * Left join to pick up dependency info linking sequences to their
3987 * owning column, if any (note this dependency is AUTO as of 8.2)
3989 appendPQExpBuffer(query,
3990 "SELECT c.tableoid, c.oid, c.relname, "
3991 "c.relacl, c.relkind, c.relnamespace, "
3992 "(%s c.relowner) AS rolname, "
3993 "c.relchecks, c.relhastriggers, "
3994 "c.relhasindex, c.relhasrules, c.relhasoids, "
3995 "c.relfrozenxid, tc.oid AS toid, "
3996 "tc.relfrozenxid AS tfrozenxid, "
3997 "c.relpersistence, "
3998 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3999 "d.refobjid AS owning_tab, "
4000 "d.refobjsubid AS owning_col, "
4001 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4002 "array_to_string(c.reloptions, ', ') AS reloptions, "
4003 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4005 "LEFT JOIN pg_depend d ON "
4006 "(c.relkind = '%c' AND "
4007 "d.classid = c.tableoid AND d.objid = c.oid AND "
4008 "d.objsubid = 0 AND "
4009 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4010 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4011 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
4015 RELKIND_RELATION, RELKIND_SEQUENCE,
4016 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4017 RELKIND_FOREIGN_TABLE);
4019 else if (fout->remoteVersion >= 90000)
4022 * Left join to pick up dependency info linking sequences to their
4023 * owning column, if any (note this dependency is AUTO as of 8.2)
4025 appendPQExpBuffer(query,
4026 "SELECT c.tableoid, c.oid, c.relname, "
4027 "c.relacl, c.relkind, c.relnamespace, "
4028 "(%s c.relowner) AS rolname, "
4029 "c.relchecks, c.relhastriggers, "
4030 "c.relhasindex, c.relhasrules, c.relhasoids, "
4031 "c.relfrozenxid, tc.oid AS toid, "
4032 "tc.relfrozenxid AS tfrozenxid, "
4033 "'p' AS relpersistence, "
4034 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4035 "d.refobjid AS owning_tab, "
4036 "d.refobjsubid AS owning_col, "
4037 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4038 "array_to_string(c.reloptions, ', ') AS reloptions, "
4039 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4041 "LEFT JOIN pg_depend d ON "
4042 "(c.relkind = '%c' AND "
4043 "d.classid = c.tableoid AND d.objid = c.oid AND "
4044 "d.objsubid = 0 AND "
4045 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4046 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4047 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4051 RELKIND_RELATION, RELKIND_SEQUENCE,
4052 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4054 else if (fout->remoteVersion >= 80400)
4057 * Left join to pick up dependency info linking sequences to their
4058 * owning column, if any (note this dependency is AUTO as of 8.2)
4060 appendPQExpBuffer(query,
4061 "SELECT c.tableoid, c.oid, c.relname, "
4062 "c.relacl, c.relkind, c.relnamespace, "
4063 "(%s c.relowner) AS rolname, "
4064 "c.relchecks, c.relhastriggers, "
4065 "c.relhasindex, c.relhasrules, c.relhasoids, "
4066 "c.relfrozenxid, tc.oid AS toid, "
4067 "tc.relfrozenxid AS tfrozenxid, "
4068 "'p' AS relpersistence, "
4069 "NULL AS reloftype, "
4070 "d.refobjid AS owning_tab, "
4071 "d.refobjsubid AS owning_col, "
4072 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4073 "array_to_string(c.reloptions, ', ') AS reloptions, "
4074 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4076 "LEFT JOIN pg_depend d ON "
4077 "(c.relkind = '%c' AND "
4078 "d.classid = c.tableoid AND d.objid = c.oid AND "
4079 "d.objsubid = 0 AND "
4080 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4081 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4082 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4086 RELKIND_RELATION, RELKIND_SEQUENCE,
4087 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4089 else if (fout->remoteVersion >= 80200)
4092 * Left join to pick up dependency info linking sequences to their
4093 * owning column, if any (note this dependency is AUTO as of 8.2)
4095 appendPQExpBuffer(query,
4096 "SELECT c.tableoid, c.oid, c.relname, "
4097 "c.relacl, c.relkind, c.relnamespace, "
4098 "(%s c.relowner) AS rolname, "
4099 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4100 "c.relhasindex, c.relhasrules, c.relhasoids, "
4101 "c.relfrozenxid, tc.oid AS toid, "
4102 "tc.relfrozenxid AS tfrozenxid, "
4103 "'p' AS relpersistence, "
4104 "NULL AS reloftype, "
4105 "d.refobjid AS owning_tab, "
4106 "d.refobjsubid AS owning_col, "
4107 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4108 "array_to_string(c.reloptions, ', ') AS reloptions, "
4109 "NULL AS toast_reloptions "
4111 "LEFT JOIN pg_depend d ON "
4112 "(c.relkind = '%c' AND "
4113 "d.classid = c.tableoid AND d.objid = c.oid AND "
4114 "d.objsubid = 0 AND "
4115 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4116 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4117 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4121 RELKIND_RELATION, RELKIND_SEQUENCE,
4122 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4124 else if (fout->remoteVersion >= 80000)
4127 * Left join to pick up dependency info linking sequences to their
4128 * owning column, if any
4130 appendPQExpBuffer(query,
4131 "SELECT c.tableoid, c.oid, relname, "
4132 "relacl, relkind, relnamespace, "
4133 "(%s relowner) AS rolname, "
4134 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4135 "relhasindex, relhasrules, relhasoids, "
4136 "0 AS relfrozenxid, "
4139 "'p' AS relpersistence, "
4140 "NULL AS reloftype, "
4141 "d.refobjid AS owning_tab, "
4142 "d.refobjsubid AS owning_col, "
4143 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4144 "NULL AS reloptions, "
4145 "NULL AS toast_reloptions "
4147 "LEFT JOIN pg_depend d ON "
4148 "(c.relkind = '%c' AND "
4149 "d.classid = c.tableoid AND d.objid = c.oid AND "
4150 "d.objsubid = 0 AND "
4151 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4152 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4156 RELKIND_RELATION, RELKIND_SEQUENCE,
4157 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4159 else if (fout->remoteVersion >= 70300)
4162 * Left join to pick up dependency info linking sequences to their
4163 * owning column, if any
4165 appendPQExpBuffer(query,
4166 "SELECT c.tableoid, c.oid, relname, "
4167 "relacl, relkind, relnamespace, "
4168 "(%s relowner) AS rolname, "
4169 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4170 "relhasindex, relhasrules, relhasoids, "
4171 "0 AS relfrozenxid, "
4174 "'p' AS relpersistence, "
4175 "NULL AS reloftype, "
4176 "d.refobjid AS owning_tab, "
4177 "d.refobjsubid AS owning_col, "
4178 "NULL AS reltablespace, "
4179 "NULL AS reloptions, "
4180 "NULL AS toast_reloptions "
4182 "LEFT JOIN pg_depend d ON "
4183 "(c.relkind = '%c' AND "
4184 "d.classid = c.tableoid AND d.objid = c.oid AND "
4185 "d.objsubid = 0 AND "
4186 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4187 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4191 RELKIND_RELATION, RELKIND_SEQUENCE,
4192 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4194 else if (fout->remoteVersion >= 70200)
4196 appendPQExpBuffer(query,
4197 "SELECT tableoid, oid, relname, relacl, relkind, "
4198 "0::oid AS relnamespace, "
4199 "(%s relowner) AS rolname, "
4200 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4201 "relhasindex, relhasrules, relhasoids, "
4202 "0 AS relfrozenxid, "
4205 "'p' AS relpersistence, "
4206 "NULL AS reloftype, "
4207 "NULL::oid AS owning_tab, "
4208 "NULL::int4 AS owning_col, "
4209 "NULL AS reltablespace, "
4210 "NULL AS reloptions, "
4211 "NULL AS toast_reloptions "
4213 "WHERE relkind IN ('%c', '%c', '%c') "
4216 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4218 else if (fout->remoteVersion >= 70100)
4220 /* all tables have oids in 7.1 */
4221 appendPQExpBuffer(query,
4222 "SELECT tableoid, oid, relname, relacl, relkind, "
4223 "0::oid AS relnamespace, "
4224 "(%s relowner) AS rolname, "
4225 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4226 "relhasindex, relhasrules, "
4227 "'t'::bool AS relhasoids, "
4228 "0 AS relfrozenxid, "
4231 "'p' AS relpersistence, "
4232 "NULL AS reloftype, "
4233 "NULL::oid AS owning_tab, "
4234 "NULL::int4 AS owning_col, "
4235 "NULL AS reltablespace, "
4236 "NULL AS reloptions, "
4237 "NULL AS toast_reloptions "
4239 "WHERE relkind IN ('%c', '%c', '%c') "
4242 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4247 * Before 7.1, view relkind was not set to 'v', so we must check if we
4248 * have a view by looking for a rule in pg_rewrite.
4250 appendPQExpBuffer(query,
4252 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4253 "oid, relname, relacl, "
4254 "CASE WHEN relhasrules and relkind = 'r' "
4255 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4256 " r.ev_class = c.oid AND r.ev_type = '1') "
4257 "THEN '%c'::\"char\" "
4258 "ELSE relkind END AS relkind,"
4259 "0::oid AS relnamespace, "
4260 "(%s relowner) AS rolname, "
4261 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4262 "relhasindex, relhasrules, "
4263 "'t'::bool AS relhasoids, "
4264 "0 as relfrozenxid, "
4267 "'p' AS relpersistence, "
4268 "NULL AS reloftype, "
4269 "NULL::oid AS owning_tab, "
4270 "NULL::int4 AS owning_col, "
4271 "NULL AS reltablespace, "
4272 "NULL AS reloptions, "
4273 "NULL AS toast_reloptions "
4275 "WHERE relkind IN ('%c', '%c') "
4279 RELKIND_RELATION, RELKIND_SEQUENCE);
4282 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4284 ntups = PQntuples(res);
4289 * Extract data from result and lock dumpable tables. We do the locking
4290 * before anything else, to minimize the window wherein a table could
4291 * disappear under us.
4293 * Note that we have to save info about all tables here, even when dumping
4294 * only one, because we don't yet know which tables might be inheritance
4295 * ancestors of the target table.
4297 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4299 i_reltableoid = PQfnumber(res, "tableoid");
4300 i_reloid = PQfnumber(res, "oid");
4301 i_relname = PQfnumber(res, "relname");
4302 i_relnamespace = PQfnumber(res, "relnamespace");
4303 i_relacl = PQfnumber(res, "relacl");
4304 i_relkind = PQfnumber(res, "relkind");
4305 i_rolname = PQfnumber(res, "rolname");
4306 i_relchecks = PQfnumber(res, "relchecks");
4307 i_relhastriggers = PQfnumber(res, "relhastriggers");
4308 i_relhasindex = PQfnumber(res, "relhasindex");
4309 i_relhasrules = PQfnumber(res, "relhasrules");
4310 i_relhasoids = PQfnumber(res, "relhasoids");
4311 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4312 i_toastoid = PQfnumber(res, "toid");
4313 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4314 i_relpersistence = PQfnumber(res, "relpersistence");
4315 i_owning_tab = PQfnumber(res, "owning_tab");
4316 i_owning_col = PQfnumber(res, "owning_col");
4317 i_reltablespace = PQfnumber(res, "reltablespace");
4318 i_reloptions = PQfnumber(res, "reloptions");
4319 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4320 i_reloftype = PQfnumber(res, "reloftype");
4322 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4325 * Arrange to fail instead of waiting forever for a table lock.
4327 * NB: this coding assumes that the only queries issued within the
4328 * following loop are LOCK TABLEs; else the timeout may be undesirably
4329 * applied to other things too.
4331 resetPQExpBuffer(query);
4332 appendPQExpBuffer(query, "SET statement_timeout = ");
4333 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
4334 ExecuteSqlStatement(fout, query->data);
4337 for (i = 0; i < ntups; i++)
4339 tblinfo[i].dobj.objType = DO_TABLE;
4340 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4341 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4342 AssignDumpId(&tblinfo[i].dobj);
4343 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4344 tblinfo[i].dobj.namespace =
4346 atooid(PQgetvalue(res, i, i_relnamespace)),
4347 tblinfo[i].dobj.catId.oid);
4348 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4349 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4350 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4351 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4352 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4353 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4354 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4355 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4356 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4357 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4358 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4359 if (PQgetisnull(res, i, i_reloftype))
4360 tblinfo[i].reloftype = NULL;
4362 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4363 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4364 if (PQgetisnull(res, i, i_owning_tab))
4366 tblinfo[i].owning_tab = InvalidOid;
4367 tblinfo[i].owning_col = 0;
4371 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4372 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4374 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4375 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4376 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4378 /* other fields were zeroed above */
4381 * Decide whether we want to dump this table.
4383 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4384 tblinfo[i].dobj.dump = false;
4386 selectDumpableTable(&tblinfo[i]);
4387 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4390 * Read-lock target tables to make sure they aren't DROPPED or altered
4391 * in schema before we get around to dumping them.
4393 * Note that we don't explicitly lock parents of the target tables; we
4394 * assume our lock on the child is enough to prevent schema
4395 * alterations to parent tables.
4397 * NOTE: it'd be kinda nice to lock other relations too, not only
4398 * plain tables, but the backend doesn't presently allow that.
4400 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4402 resetPQExpBuffer(query);
4403 appendPQExpBuffer(query,
4404 "LOCK TABLE %s IN ACCESS SHARE MODE",
4405 fmtQualifiedId(fout,
4406 tblinfo[i].dobj.namespace->dobj.name,
4407 tblinfo[i].dobj.name));
4408 ExecuteSqlStatement(fout, query->data);
4411 /* Emit notice if join for owner failed */
4412 if (strlen(tblinfo[i].rolname) == 0)
4413 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4414 tblinfo[i].dobj.name);
4417 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4419 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4425 * Force sequences that are "owned" by table columns to be dumped whenever
4426 * their owning table is being dumped.
4428 for (i = 0; i < ntups; i++)
4430 TableInfo *seqinfo = &tblinfo[i];
4433 if (!OidIsValid(seqinfo->owning_tab))
4434 continue; /* not an owned sequence */
4435 if (seqinfo->dobj.dump)
4436 continue; /* no need to search */
4438 /* can't use findTableByOid yet, unfortunately */
4439 for (j = 0; j < ntups; j++)
4441 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4443 if (tblinfo[j].dobj.dump)
4445 seqinfo->interesting = true;
4446 seqinfo->dobj.dump = true;
4453 destroyPQExpBuffer(query);
4460 * read all the inheritance information
4461 * from the system catalogs return them in the InhInfo* structure
4463 * numInherits is set to the number of pairs read in
4466 getInherits(Archive *fout, int *numInherits)
4471 PQExpBuffer query = createPQExpBuffer();
4477 /* Make sure we are in proper schema */
4478 selectSourceSchema(fout, "pg_catalog");
4480 /* find all the inheritance information */
4482 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4484 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4486 ntups = PQntuples(res);
4488 *numInherits = ntups;
4490 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4492 i_inhrelid = PQfnumber(res, "inhrelid");
4493 i_inhparent = PQfnumber(res, "inhparent");
4495 for (i = 0; i < ntups; i++)
4497 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4498 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4503 destroyPQExpBuffer(query);
4510 * get information about every index on a dumpable table
4512 * Note: index data is not returned directly to the caller, but it
4513 * does get entered into the DumpableObject tables.
4516 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4520 PQExpBuffer query = createPQExpBuffer();
4523 ConstraintInfo *constrinfo;
4542 for (i = 0; i < numTables; i++)
4544 TableInfo *tbinfo = &tblinfo[i];
4546 /* Only plain tables have indexes */
4547 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4550 /* Ignore indexes of tables not to be dumped */
4551 if (!tbinfo->dobj.dump)
4555 write_msg(NULL, "reading indexes for table \"%s\"\n",
4558 /* Make sure we are in proper schema so indexdef is right */
4559 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4562 * The point of the messy-looking outer join is to find a constraint
4563 * that is related by an internal dependency link to the index. If we
4564 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4565 * assume an index won't have more than one internal dependency.
4567 * As of 9.0 we don't need to look at pg_depend but can check for a
4568 * match to pg_constraint.conindid. The check on conrelid is
4569 * redundant but useful because that column is indexed while conindid
4572 resetPQExpBuffer(query);
4573 if (fout->remoteVersion >= 90000)
4575 appendPQExpBuffer(query,
4576 "SELECT t.tableoid, t.oid, "
4577 "t.relname AS indexname, "
4578 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4579 "t.relnatts AS indnkeys, "
4580 "i.indkey, i.indisclustered, "
4581 "c.contype, c.conname, "
4582 "c.condeferrable, c.condeferred, "
4583 "c.tableoid AS contableoid, "
4585 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4586 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4587 "array_to_string(t.reloptions, ', ') AS options "
4588 "FROM pg_catalog.pg_index i "
4589 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4590 "LEFT JOIN pg_catalog.pg_constraint c "
4591 "ON (i.indrelid = c.conrelid AND "
4592 "i.indexrelid = c.conindid AND "
4593 "c.contype IN ('p','u','x')) "
4594 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4595 "ORDER BY indexname",
4596 tbinfo->dobj.catId.oid);
4598 else if (fout->remoteVersion >= 80200)
4600 appendPQExpBuffer(query,
4601 "SELECT t.tableoid, t.oid, "
4602 "t.relname AS indexname, "
4603 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4604 "t.relnatts AS indnkeys, "
4605 "i.indkey, i.indisclustered, "
4606 "c.contype, c.conname, "
4607 "c.condeferrable, c.condeferred, "
4608 "c.tableoid AS contableoid, "
4611 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4612 "array_to_string(t.reloptions, ', ') AS options "
4613 "FROM pg_catalog.pg_index i "
4614 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4615 "LEFT JOIN pg_catalog.pg_depend d "
4616 "ON (d.classid = t.tableoid "
4617 "AND d.objid = t.oid "
4618 "AND d.deptype = 'i') "
4619 "LEFT JOIN pg_catalog.pg_constraint c "
4620 "ON (d.refclassid = c.tableoid "
4621 "AND d.refobjid = c.oid) "
4622 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4623 "ORDER BY indexname",
4624 tbinfo->dobj.catId.oid);
4626 else if (fout->remoteVersion >= 80000)
4628 appendPQExpBuffer(query,
4629 "SELECT t.tableoid, t.oid, "
4630 "t.relname AS indexname, "
4631 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4632 "t.relnatts AS indnkeys, "
4633 "i.indkey, i.indisclustered, "
4634 "c.contype, c.conname, "
4635 "c.condeferrable, c.condeferred, "
4636 "c.tableoid AS contableoid, "
4639 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4641 "FROM pg_catalog.pg_index i "
4642 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4643 "LEFT JOIN pg_catalog.pg_depend d "
4644 "ON (d.classid = t.tableoid "
4645 "AND d.objid = t.oid "
4646 "AND d.deptype = 'i') "
4647 "LEFT JOIN pg_catalog.pg_constraint c "
4648 "ON (d.refclassid = c.tableoid "
4649 "AND d.refobjid = c.oid) "
4650 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4651 "ORDER BY indexname",
4652 tbinfo->dobj.catId.oid);
4654 else if (fout->remoteVersion >= 70300)
4656 appendPQExpBuffer(query,
4657 "SELECT t.tableoid, t.oid, "
4658 "t.relname AS indexname, "
4659 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4660 "t.relnatts AS indnkeys, "
4661 "i.indkey, i.indisclustered, "
4662 "c.contype, c.conname, "
4663 "c.condeferrable, c.condeferred, "
4664 "c.tableoid AS contableoid, "
4667 "NULL AS tablespace, "
4669 "FROM pg_catalog.pg_index i "
4670 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4671 "LEFT JOIN pg_catalog.pg_depend d "
4672 "ON (d.classid = t.tableoid "
4673 "AND d.objid = t.oid "
4674 "AND d.deptype = 'i') "
4675 "LEFT JOIN pg_catalog.pg_constraint c "
4676 "ON (d.refclassid = c.tableoid "
4677 "AND d.refobjid = c.oid) "
4678 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4679 "ORDER BY indexname",
4680 tbinfo->dobj.catId.oid);
4682 else if (fout->remoteVersion >= 70100)
4684 appendPQExpBuffer(query,
4685 "SELECT t.tableoid, t.oid, "
4686 "t.relname AS indexname, "
4687 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4688 "t.relnatts AS indnkeys, "
4689 "i.indkey, false AS indisclustered, "
4690 "CASE WHEN i.indisprimary THEN 'p'::char "
4691 "ELSE '0'::char END AS contype, "
4692 "t.relname AS conname, "
4693 "false AS condeferrable, "
4694 "false AS condeferred, "
4695 "0::oid AS contableoid, "
4698 "NULL AS tablespace, "
4700 "FROM pg_index i, pg_class t "
4701 "WHERE t.oid = i.indexrelid "
4702 "AND i.indrelid = '%u'::oid "
4703 "ORDER BY indexname",
4704 tbinfo->dobj.catId.oid);
4708 appendPQExpBuffer(query,
4710 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4712 "t.relname AS indexname, "
4713 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4714 "t.relnatts AS indnkeys, "
4715 "i.indkey, false AS indisclustered, "
4716 "CASE WHEN i.indisprimary THEN 'p'::char "
4717 "ELSE '0'::char END AS contype, "
4718 "t.relname AS conname, "
4719 "false AS condeferrable, "
4720 "false AS condeferred, "
4721 "0::oid AS contableoid, "
4724 "NULL AS tablespace, "
4726 "FROM pg_index i, pg_class t "
4727 "WHERE t.oid = i.indexrelid "
4728 "AND i.indrelid = '%u'::oid "
4729 "ORDER BY indexname",
4730 tbinfo->dobj.catId.oid);
4733 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4735 ntups = PQntuples(res);
4737 i_tableoid = PQfnumber(res, "tableoid");
4738 i_oid = PQfnumber(res, "oid");
4739 i_indexname = PQfnumber(res, "indexname");
4740 i_indexdef = PQfnumber(res, "indexdef");
4741 i_indnkeys = PQfnumber(res, "indnkeys");
4742 i_indkey = PQfnumber(res, "indkey");
4743 i_indisclustered = PQfnumber(res, "indisclustered");
4744 i_contype = PQfnumber(res, "contype");
4745 i_conname = PQfnumber(res, "conname");
4746 i_condeferrable = PQfnumber(res, "condeferrable");
4747 i_condeferred = PQfnumber(res, "condeferred");
4748 i_contableoid = PQfnumber(res, "contableoid");
4749 i_conoid = PQfnumber(res, "conoid");
4750 i_condef = PQfnumber(res, "condef");
4751 i_tablespace = PQfnumber(res, "tablespace");
4752 i_options = PQfnumber(res, "options");
4754 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4755 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4757 for (j = 0; j < ntups; j++)
4761 indxinfo[j].dobj.objType = DO_INDEX;
4762 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4763 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4764 AssignDumpId(&indxinfo[j].dobj);
4765 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4766 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4767 indxinfo[j].indextable = tbinfo;
4768 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4769 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4770 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4771 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4774 * In pre-7.4 releases, indkeys may contain more entries than
4775 * indnkeys says (since indnkeys will be 1 for a functional
4776 * index). We don't actually care about this case since we don't
4777 * examine indkeys except for indexes associated with PRIMARY and
4778 * UNIQUE constraints, which are never functional indexes. But we
4779 * have to allocate enough space to keep parseOidArray from
4782 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4783 parseOidArray(PQgetvalue(res, j, i_indkey),
4784 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4785 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4786 contype = *(PQgetvalue(res, j, i_contype));
4788 if (contype == 'p' || contype == 'u' || contype == 'x')
4791 * If we found a constraint matching the index, create an
4794 * In a pre-7.3 database, we take this path iff the index was
4795 * marked indisprimary.
4797 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4798 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4799 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4800 AssignDumpId(&constrinfo[j].dobj);
4801 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4802 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4803 constrinfo[j].contable = tbinfo;
4804 constrinfo[j].condomain = NULL;
4805 constrinfo[j].contype = contype;
4807 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4809 constrinfo[j].condef = NULL;
4810 constrinfo[j].confrelid = InvalidOid;
4811 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4812 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4813 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4814 constrinfo[j].conislocal = true;
4815 constrinfo[j].separate = true;
4817 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4819 /* If pre-7.3 DB, better make sure table comes first */
4820 addObjectDependency(&constrinfo[j].dobj,
4821 tbinfo->dobj.dumpId);
4825 /* Plain secondary index */
4826 indxinfo[j].indexconstraint = 0;
4833 destroyPQExpBuffer(query);
4839 * Get info about constraints on dumpable tables.
4841 * Currently handles foreign keys only.
4842 * Unique and primary key constraints are handled with indexes,
4843 * while check constraints are processed in getTableAttrs().
4846 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4850 ConstraintInfo *constrinfo;
4860 /* pg_constraint was created in 7.3, so nothing to do if older */
4861 if (fout->remoteVersion < 70300)
4864 query = createPQExpBuffer();
4866 for (i = 0; i < numTables; i++)
4868 TableInfo *tbinfo = &tblinfo[i];
4870 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4874 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4878 * select table schema to ensure constraint expr is qualified if
4881 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4883 resetPQExpBuffer(query);
4884 appendPQExpBuffer(query,
4885 "SELECT tableoid, oid, conname, confrelid, "
4886 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4887 "FROM pg_catalog.pg_constraint "
4888 "WHERE conrelid = '%u'::pg_catalog.oid "
4889 "AND contype = 'f'",
4890 tbinfo->dobj.catId.oid);
4891 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4893 ntups = PQntuples(res);
4895 i_contableoid = PQfnumber(res, "tableoid");
4896 i_conoid = PQfnumber(res, "oid");
4897 i_conname = PQfnumber(res, "conname");
4898 i_confrelid = PQfnumber(res, "confrelid");
4899 i_condef = PQfnumber(res, "condef");
4901 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4903 for (j = 0; j < ntups; j++)
4905 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4906 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4907 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4908 AssignDumpId(&constrinfo[j].dobj);
4909 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4910 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4911 constrinfo[j].contable = tbinfo;
4912 constrinfo[j].condomain = NULL;
4913 constrinfo[j].contype = 'f';
4914 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4915 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4916 constrinfo[j].conindex = 0;
4917 constrinfo[j].condeferrable = false;
4918 constrinfo[j].condeferred = false;
4919 constrinfo[j].conislocal = true;
4920 constrinfo[j].separate = true;
4926 destroyPQExpBuffer(query);
4930 * getDomainConstraints
4932 * Get info about constraints on a domain.
4935 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4938 ConstraintInfo *constrinfo;
4947 /* pg_constraint was created in 7.3, so nothing to do if older */
4948 if (fout->remoteVersion < 70300)
4952 * select appropriate schema to ensure names in constraint are properly
4955 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4957 query = createPQExpBuffer();
4959 if (fout->remoteVersion >= 90100)
4960 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4961 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4963 "FROM pg_catalog.pg_constraint "
4964 "WHERE contypid = '%u'::pg_catalog.oid "
4966 tyinfo->dobj.catId.oid);
4968 else if (fout->remoteVersion >= 70400)
4969 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4970 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4971 "true as convalidated "
4972 "FROM pg_catalog.pg_constraint "
4973 "WHERE contypid = '%u'::pg_catalog.oid "
4975 tyinfo->dobj.catId.oid);
4977 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4978 "'CHECK (' || consrc || ')' AS consrc, "
4979 "true as convalidated "
4980 "FROM pg_catalog.pg_constraint "
4981 "WHERE contypid = '%u'::pg_catalog.oid "
4983 tyinfo->dobj.catId.oid);
4985 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4987 ntups = PQntuples(res);
4989 i_tableoid = PQfnumber(res, "tableoid");
4990 i_oid = PQfnumber(res, "oid");
4991 i_conname = PQfnumber(res, "conname");
4992 i_consrc = PQfnumber(res, "consrc");
4994 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4996 tyinfo->nDomChecks = ntups;
4997 tyinfo->domChecks = constrinfo;
4999 for (i = 0; i < ntups; i++)
5001 bool validated = PQgetvalue(res, i, 4)[0] == 't';
5003 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5004 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5005 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5006 AssignDumpId(&constrinfo[i].dobj);
5007 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5008 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5009 constrinfo[i].contable = NULL;
5010 constrinfo[i].condomain = tyinfo;
5011 constrinfo[i].contype = 'c';
5012 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5013 constrinfo[i].confrelid = InvalidOid;
5014 constrinfo[i].conindex = 0;
5015 constrinfo[i].condeferrable = false;
5016 constrinfo[i].condeferred = false;
5017 constrinfo[i].conislocal = true;
5019 constrinfo[i].separate = !validated;
5022 * Make the domain depend on the constraint, ensuring it won't be
5023 * output till any constraint dependencies are OK. If the constraint
5024 * has not been validated, it's going to be dumped after the domain
5025 * anyway, so this doesn't matter.
5028 addObjectDependency(&tyinfo->dobj,
5029 constrinfo[i].dobj.dumpId);
5034 destroyPQExpBuffer(query);
5039 * get basic information about every rule in the system
5041 * numRules is set to the number of rules read in
5044 getRules(Archive *fout, int *numRules)
5049 PQExpBuffer query = createPQExpBuffer();
5059 /* Make sure we are in proper schema */
5060 selectSourceSchema(fout, "pg_catalog");
5062 if (fout->remoteVersion >= 80300)
5064 appendPQExpBuffer(query, "SELECT "
5065 "tableoid, oid, rulename, "
5066 "ev_class AS ruletable, ev_type, is_instead, "
5071 else if (fout->remoteVersion >= 70100)
5073 appendPQExpBuffer(query, "SELECT "
5074 "tableoid, oid, rulename, "
5075 "ev_class AS ruletable, ev_type, is_instead, "
5076 "'O'::char AS ev_enabled "
5082 appendPQExpBuffer(query, "SELECT "
5083 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5085 "ev_class AS ruletable, ev_type, is_instead, "
5086 "'O'::char AS ev_enabled "
5091 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5093 ntups = PQntuples(res);
5097 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5099 i_tableoid = PQfnumber(res, "tableoid");
5100 i_oid = PQfnumber(res, "oid");
5101 i_rulename = PQfnumber(res, "rulename");
5102 i_ruletable = PQfnumber(res, "ruletable");
5103 i_ev_type = PQfnumber(res, "ev_type");
5104 i_is_instead = PQfnumber(res, "is_instead");
5105 i_ev_enabled = PQfnumber(res, "ev_enabled");
5107 for (i = 0; i < ntups; i++)
5111 ruleinfo[i].dobj.objType = DO_RULE;
5112 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5113 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5114 AssignDumpId(&ruleinfo[i].dobj);
5115 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5116 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5117 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5118 if (ruleinfo[i].ruletable == NULL)
5120 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5122 ruleinfo[i].dobj.catId.oid);
5125 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5126 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5127 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5128 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5129 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5130 if (ruleinfo[i].ruletable)
5133 * If the table is a view, force its ON SELECT rule to be sorted
5134 * before the view itself --- this ensures that any dependencies
5135 * for the rule affect the table's positioning. Other rules are
5136 * forced to appear after their table.
5138 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5139 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5141 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5142 ruleinfo[i].dobj.dumpId);
5143 /* We'll merge the rule into CREATE VIEW, if possible */
5144 ruleinfo[i].separate = false;
5148 addObjectDependency(&ruleinfo[i].dobj,
5149 ruleinfo[i].ruletable->dobj.dumpId);
5150 ruleinfo[i].separate = true;
5154 ruleinfo[i].separate = true;
5159 destroyPQExpBuffer(query);
5166 * get information about every trigger on a dumpable table
5168 * Note: trigger data is not returned directly to the caller, but it
5169 * does get entered into the DumpableObject tables.
5172 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5176 PQExpBuffer query = createPQExpBuffer();
5178 TriggerInfo *tginfo;
5196 for (i = 0; i < numTables; i++)
5198 TableInfo *tbinfo = &tblinfo[i];
5200 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5204 write_msg(NULL, "reading triggers for table \"%s\"\n",
5208 * select table schema to ensure regproc name is qualified if needed
5210 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5212 resetPQExpBuffer(query);
5213 if (fout->remoteVersion >= 90000)
5216 * NB: think not to use pretty=true in pg_get_triggerdef. It
5217 * could result in non-forward-compatible dumps of WHEN clauses
5218 * due to under-parenthesization.
5220 appendPQExpBuffer(query,
5222 "tgfoid::pg_catalog.regproc AS tgfname, "
5223 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5224 "tgenabled, tableoid, oid "
5225 "FROM pg_catalog.pg_trigger t "
5226 "WHERE tgrelid = '%u'::pg_catalog.oid "
5227 "AND NOT tgisinternal",
5228 tbinfo->dobj.catId.oid);
5230 else if (fout->remoteVersion >= 80300)
5233 * We ignore triggers that are tied to a foreign-key constraint
5235 appendPQExpBuffer(query,
5237 "tgfoid::pg_catalog.regproc AS tgfname, "
5238 "tgtype, tgnargs, tgargs, tgenabled, "
5239 "tgisconstraint, tgconstrname, tgdeferrable, "
5240 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5241 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5242 "FROM pg_catalog.pg_trigger t "
5243 "WHERE tgrelid = '%u'::pg_catalog.oid "
5244 "AND tgconstraint = 0",
5245 tbinfo->dobj.catId.oid);
5247 else if (fout->remoteVersion >= 70300)
5250 * We ignore triggers that are tied to a foreign-key constraint,
5251 * but in these versions we have to grovel through pg_constraint
5254 appendPQExpBuffer(query,
5256 "tgfoid::pg_catalog.regproc AS tgfname, "
5257 "tgtype, tgnargs, tgargs, tgenabled, "
5258 "tgisconstraint, tgconstrname, tgdeferrable, "
5259 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5260 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5261 "FROM pg_catalog.pg_trigger t "
5262 "WHERE tgrelid = '%u'::pg_catalog.oid "
5263 "AND (NOT tgisconstraint "
5265 " (SELECT 1 FROM pg_catalog.pg_depend d "
5266 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5267 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5268 tbinfo->dobj.catId.oid);
5270 else if (fout->remoteVersion >= 70100)
5272 appendPQExpBuffer(query,
5273 "SELECT tgname, tgfoid::regproc AS tgfname, "
5274 "tgtype, tgnargs, tgargs, tgenabled, "
5275 "tgisconstraint, tgconstrname, tgdeferrable, "
5276 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5277 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5278 " AS tgconstrrelname "
5280 "WHERE tgrelid = '%u'::oid",
5281 tbinfo->dobj.catId.oid);
5285 appendPQExpBuffer(query,
5286 "SELECT tgname, tgfoid::regproc AS tgfname, "
5287 "tgtype, tgnargs, tgargs, tgenabled, "
5288 "tgisconstraint, tgconstrname, tgdeferrable, "
5289 "tgconstrrelid, tginitdeferred, "
5290 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5292 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5293 " AS tgconstrrelname "
5295 "WHERE tgrelid = '%u'::oid",
5296 tbinfo->dobj.catId.oid);
5298 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5300 ntups = PQntuples(res);
5302 i_tableoid = PQfnumber(res, "tableoid");
5303 i_oid = PQfnumber(res, "oid");
5304 i_tgname = PQfnumber(res, "tgname");
5305 i_tgfname = PQfnumber(res, "tgfname");
5306 i_tgtype = PQfnumber(res, "tgtype");
5307 i_tgnargs = PQfnumber(res, "tgnargs");
5308 i_tgargs = PQfnumber(res, "tgargs");
5309 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5310 i_tgconstrname = PQfnumber(res, "tgconstrname");
5311 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5312 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5313 i_tgenabled = PQfnumber(res, "tgenabled");
5314 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5315 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5316 i_tgdef = PQfnumber(res, "tgdef");
5318 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5320 for (j = 0; j < ntups; j++)
5322 tginfo[j].dobj.objType = DO_TRIGGER;
5323 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5324 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5325 AssignDumpId(&tginfo[j].dobj);
5326 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5327 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5328 tginfo[j].tgtable = tbinfo;
5329 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5332 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5334 /* remaining fields are not valid if we have tgdef */
5335 tginfo[j].tgfname = NULL;
5336 tginfo[j].tgtype = 0;
5337 tginfo[j].tgnargs = 0;
5338 tginfo[j].tgargs = NULL;
5339 tginfo[j].tgisconstraint = false;
5340 tginfo[j].tgdeferrable = false;
5341 tginfo[j].tginitdeferred = false;
5342 tginfo[j].tgconstrname = NULL;
5343 tginfo[j].tgconstrrelid = InvalidOid;
5344 tginfo[j].tgconstrrelname = NULL;
5348 tginfo[j].tgdef = NULL;
5350 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5351 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5352 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5353 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5354 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5355 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5356 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5358 if (tginfo[j].tgisconstraint)
5360 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5361 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5362 if (OidIsValid(tginfo[j].tgconstrrelid))
5364 if (PQgetisnull(res, j, i_tgconstrrelname))
5366 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5367 tginfo[j].dobj.name, tbinfo->dobj.name,
5368 tginfo[j].tgconstrrelid);
5371 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5374 tginfo[j].tgconstrrelname = NULL;
5378 tginfo[j].tgconstrname = NULL;
5379 tginfo[j].tgconstrrelid = InvalidOid;
5380 tginfo[j].tgconstrrelname = NULL;
5388 destroyPQExpBuffer(query);
5393 * get basic information about every procedural language in the system
5395 * numProcLangs is set to the number of langs read in
5397 * NB: this must run after getFuncs() because we assume we can do
5401 getProcLangs(Archive *fout, int *numProcLangs)
5406 PQExpBuffer query = createPQExpBuffer();
5407 ProcLangInfo *planginfo;
5412 int i_lanplcallfoid;
5418 /* Make sure we are in proper schema */
5419 selectSourceSchema(fout, "pg_catalog");
5421 if (fout->remoteVersion >= 90000)
5423 /* pg_language has a laninline column */
5424 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5425 "lanname, lanpltrusted, lanplcallfoid, "
5426 "laninline, lanvalidator, lanacl, "
5427 "(%s lanowner) AS lanowner "
5433 else if (fout->remoteVersion >= 80300)
5435 /* pg_language has a lanowner column */
5436 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5437 "lanname, lanpltrusted, lanplcallfoid, "
5438 "lanvalidator, lanacl, "
5439 "(%s lanowner) AS lanowner "
5445 else if (fout->remoteVersion >= 80100)
5447 /* Languages are owned by the bootstrap superuser, OID 10 */
5448 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5449 "(%s '10') AS lanowner "
5455 else if (fout->remoteVersion >= 70400)
5457 /* Languages are owned by the bootstrap superuser, sysid 1 */
5458 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5459 "(%s '1') AS lanowner "
5465 else if (fout->remoteVersion >= 70100)
5467 /* No clear notion of an owner at all before 7.4 ... */
5468 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5474 appendPQExpBuffer(query, "SELECT "
5475 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5476 "oid, * FROM pg_language "
5481 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5483 ntups = PQntuples(res);
5485 *numProcLangs = ntups;
5487 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5489 i_tableoid = PQfnumber(res, "tableoid");
5490 i_oid = PQfnumber(res, "oid");
5491 i_lanname = PQfnumber(res, "lanname");
5492 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5493 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5494 /* these may fail and return -1: */
5495 i_laninline = PQfnumber(res, "laninline");
5496 i_lanvalidator = PQfnumber(res, "lanvalidator");
5497 i_lanacl = PQfnumber(res, "lanacl");
5498 i_lanowner = PQfnumber(res, "lanowner");
5500 for (i = 0; i < ntups; i++)
5502 planginfo[i].dobj.objType = DO_PROCLANG;
5503 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5504 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5505 AssignDumpId(&planginfo[i].dobj);
5507 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5508 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5509 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5510 if (i_laninline >= 0)
5511 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5513 planginfo[i].laninline = InvalidOid;
5514 if (i_lanvalidator >= 0)
5515 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5517 planginfo[i].lanvalidator = InvalidOid;
5519 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5521 planginfo[i].lanacl = pg_strdup("{=U}");
5522 if (i_lanowner >= 0)
5523 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5525 planginfo[i].lanowner = pg_strdup("");
5527 if (fout->remoteVersion < 70300)
5530 * We need to make a dependency to ensure the function will be
5531 * dumped first. (In 7.3 and later the regular dependency
5532 * mechanism will handle this for us.)
5534 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5537 addObjectDependency(&planginfo[i].dobj,
5538 funcInfo->dobj.dumpId);
5544 destroyPQExpBuffer(query);
5551 * get basic information about every cast in the system
5553 * numCasts is set to the number of casts read in
5556 getCasts(Archive *fout, int *numCasts)
5561 PQExpBuffer query = createPQExpBuffer();
5571 /* Make sure we are in proper schema */
5572 selectSourceSchema(fout, "pg_catalog");
5574 if (fout->remoteVersion >= 80400)
5576 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5577 "castsource, casttarget, castfunc, castcontext, "
5579 "FROM pg_cast ORDER BY 3,4");
5581 else if (fout->remoteVersion >= 70300)
5583 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5584 "castsource, casttarget, castfunc, castcontext, "
5585 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5586 "FROM pg_cast ORDER BY 3,4");
5590 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5591 "t1.oid AS castsource, t2.oid AS casttarget, "
5592 "p.oid AS castfunc, 'e' AS castcontext, "
5593 "'f' AS castmethod "
5594 "FROM pg_type t1, pg_type t2, pg_proc p "
5595 "WHERE p.pronargs = 1 AND "
5596 "p.proargtypes[0] = t1.oid AND "
5597 "p.prorettype = t2.oid AND p.proname = t2.typname "
5601 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5603 ntups = PQntuples(res);
5607 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5609 i_tableoid = PQfnumber(res, "tableoid");
5610 i_oid = PQfnumber(res, "oid");
5611 i_castsource = PQfnumber(res, "castsource");
5612 i_casttarget = PQfnumber(res, "casttarget");
5613 i_castfunc = PQfnumber(res, "castfunc");
5614 i_castcontext = PQfnumber(res, "castcontext");
5615 i_castmethod = PQfnumber(res, "castmethod");
5617 for (i = 0; i < ntups; i++)
5619 PQExpBufferData namebuf;
5620 TypeInfo *sTypeInfo;
5621 TypeInfo *tTypeInfo;
5623 castinfo[i].dobj.objType = DO_CAST;
5624 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5625 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5626 AssignDumpId(&castinfo[i].dobj);
5627 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5628 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5629 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5630 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5631 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5634 * Try to name cast as concatenation of typnames. This is only used
5635 * for purposes of sorting. If we fail to find either type, the name
5636 * will be an empty string.
5638 initPQExpBuffer(&namebuf);
5639 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5640 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5641 if (sTypeInfo && tTypeInfo)
5642 appendPQExpBuffer(&namebuf, "%s %s",
5643 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5644 castinfo[i].dobj.name = namebuf.data;
5646 if (OidIsValid(castinfo[i].castfunc))
5649 * We need to make a dependency to ensure the function will be
5650 * dumped first. (In 7.3 and later the regular dependency
5651 * mechanism will handle this for us.)
5655 funcInfo = findFuncByOid(castinfo[i].castfunc);
5657 addObjectDependency(&castinfo[i].dobj,
5658 funcInfo->dobj.dumpId);
5664 destroyPQExpBuffer(query);
5671 * for each interesting table, read info about its attributes
5672 * (names, types, default values, CHECK constraints, etc)
5674 * This is implemented in a very inefficient way right now, looping
5675 * through the tblinfo and doing a join per table to find the attrs and their
5676 * types. However, because we want type names and so forth to be named
5677 * relative to the schema of each table, we couldn't do it in just one
5678 * query. (Maybe one query per schema?)
5683 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5687 PQExpBuffer q = createPQExpBuffer();
5692 int i_attstattarget;
5703 int i_attfdwoptions;
5708 for (i = 0; i < numTables; i++)
5710 TableInfo *tbinfo = &tblinfo[i];
5712 /* Don't bother to collect info for sequences */
5713 if (tbinfo->relkind == RELKIND_SEQUENCE)
5716 /* Don't bother with uninteresting tables, either */
5717 if (!tbinfo->interesting)
5721 * Make sure we are in proper schema for this table; this allows
5722 * correct retrieval of formatted type names and default exprs
5724 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5726 /* find all the user attributes and their types */
5729 * we must read the attribute names in attribute number order! because
5730 * we will use the attnum to index into the attnames array later. We
5731 * actually ask to order by "attrelid, attnum" because (at least up to
5732 * 7.3) the planner is not smart enough to realize it needn't re-sort
5733 * the output of an indexscan on pg_attribute_relid_attnum_index.
5736 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5739 resetPQExpBuffer(q);
5741 if (fout->remoteVersion >= 90200)
5744 * attfdwoptions is new in 9.2.
5746 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5747 "a.attstattarget, a.attstorage, t.typstorage, "
5748 "a.attnotnull, a.atthasdef, a.attisdropped, "
5749 "a.attlen, a.attalign, a.attislocal, "
5750 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5751 "array_to_string(a.attoptions, ', ') AS attoptions, "
5752 "CASE WHEN a.attcollation <> t.typcollation "
5753 "THEN a.attcollation ELSE 0 END AS attcollation, "
5754 "pg_catalog.array_to_string(ARRAY("
5755 "SELECT pg_catalog.quote_ident(option_name) || "
5756 "' ' || pg_catalog.quote_literal(option_value) "
5757 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5758 "ORDER BY option_name"
5759 "), E',\n ') AS attfdwoptions "
5760 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5761 "ON a.atttypid = t.oid "
5762 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5763 "AND a.attnum > 0::pg_catalog.int2 "
5764 "ORDER BY a.attrelid, a.attnum",
5765 tbinfo->dobj.catId.oid);
5767 else if (fout->remoteVersion >= 90100)
5770 * attcollation is new in 9.1. Since we only want to dump COLLATE
5771 * clauses for attributes whose collation is different from their
5772 * type's default, we use a CASE here to suppress uninteresting
5773 * attcollations cheaply.
5775 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5776 "a.attstattarget, a.attstorage, t.typstorage, "
5777 "a.attnotnull, a.atthasdef, a.attisdropped, "
5778 "a.attlen, a.attalign, a.attislocal, "
5779 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5780 "array_to_string(a.attoptions, ', ') AS attoptions, "
5781 "CASE WHEN a.attcollation <> t.typcollation "
5782 "THEN a.attcollation ELSE 0 END AS attcollation, "
5783 "NULL AS attfdwoptions "
5784 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5785 "ON a.atttypid = t.oid "
5786 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5787 "AND a.attnum > 0::pg_catalog.int2 "
5788 "ORDER BY a.attrelid, a.attnum",
5789 tbinfo->dobj.catId.oid);
5791 else if (fout->remoteVersion >= 90000)
5793 /* attoptions is new in 9.0 */
5794 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5795 "a.attstattarget, a.attstorage, t.typstorage, "
5796 "a.attnotnull, a.atthasdef, a.attisdropped, "
5797 "a.attlen, a.attalign, a.attislocal, "
5798 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5799 "array_to_string(a.attoptions, ', ') AS attoptions, "
5800 "0 AS attcollation, "
5801 "NULL AS attfdwoptions "
5802 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5803 "ON a.atttypid = t.oid "
5804 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5805 "AND a.attnum > 0::pg_catalog.int2 "
5806 "ORDER BY a.attrelid, a.attnum",
5807 tbinfo->dobj.catId.oid);
5809 else if (fout->remoteVersion >= 70300)
5811 /* need left join here to not fail on dropped columns ... */
5812 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5813 "a.attstattarget, a.attstorage, t.typstorage, "
5814 "a.attnotnull, a.atthasdef, a.attisdropped, "
5815 "a.attlen, a.attalign, a.attislocal, "
5816 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5817 "'' AS attoptions, 0 AS attcollation, "
5818 "NULL AS attfdwoptions "
5819 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5820 "ON a.atttypid = t.oid "
5821 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5822 "AND a.attnum > 0::pg_catalog.int2 "
5823 "ORDER BY a.attrelid, a.attnum",
5824 tbinfo->dobj.catId.oid);
5826 else if (fout->remoteVersion >= 70100)
5829 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5830 * we don't dump it because we can't tell whether it's been
5831 * explicitly set or was just a default.
5833 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5834 "-1 AS attstattarget, a.attstorage, "
5835 "t.typstorage, a.attnotnull, a.atthasdef, "
5836 "false AS attisdropped, a.attlen, "
5837 "a.attalign, false AS attislocal, "
5838 "format_type(t.oid,a.atttypmod) AS atttypname, "
5839 "'' AS attoptions, 0 AS attcollation, "
5840 "NULL AS attfdwoptions "
5841 "FROM pg_attribute a LEFT JOIN pg_type t "
5842 "ON a.atttypid = t.oid "
5843 "WHERE a.attrelid = '%u'::oid "
5844 "AND a.attnum > 0::int2 "
5845 "ORDER BY a.attrelid, a.attnum",
5846 tbinfo->dobj.catId.oid);
5850 /* format_type not available before 7.1 */
5851 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5852 "-1 AS attstattarget, "
5853 "attstorage, attstorage AS typstorage, "
5854 "attnotnull, atthasdef, false AS attisdropped, "
5855 "attlen, attalign, "
5856 "false AS attislocal, "
5857 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5858 "'' AS attoptions, 0 AS attcollation, "
5859 "NULL AS attfdwoptions "
5860 "FROM pg_attribute a "
5861 "WHERE attrelid = '%u'::oid "
5862 "AND attnum > 0::int2 "
5863 "ORDER BY attrelid, attnum",
5864 tbinfo->dobj.catId.oid);
5867 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5869 ntups = PQntuples(res);
5871 i_attnum = PQfnumber(res, "attnum");
5872 i_attname = PQfnumber(res, "attname");
5873 i_atttypname = PQfnumber(res, "atttypname");
5874 i_atttypmod = PQfnumber(res, "atttypmod");
5875 i_attstattarget = PQfnumber(res, "attstattarget");
5876 i_attstorage = PQfnumber(res, "attstorage");
5877 i_typstorage = PQfnumber(res, "typstorage");
5878 i_attnotnull = PQfnumber(res, "attnotnull");
5879 i_atthasdef = PQfnumber(res, "atthasdef");
5880 i_attisdropped = PQfnumber(res, "attisdropped");
5881 i_attlen = PQfnumber(res, "attlen");
5882 i_attalign = PQfnumber(res, "attalign");
5883 i_attislocal = PQfnumber(res, "attislocal");
5884 i_attoptions = PQfnumber(res, "attoptions");
5885 i_attcollation = PQfnumber(res, "attcollation");
5886 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5888 tbinfo->numatts = ntups;
5889 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5890 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5891 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5892 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5893 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5894 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5895 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5896 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5897 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5898 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5899 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5900 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5901 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5902 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5903 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5904 tbinfo->inhAttrs = (bool *) pg_malloc(ntups * sizeof(bool));
5905 tbinfo->inhAttrDef = (bool *) pg_malloc(ntups * sizeof(bool));
5906 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5907 hasdefaults = false;
5909 for (j = 0; j < ntups; j++)
5911 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5913 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5917 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5918 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5919 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5920 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5921 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5922 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5923 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5924 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5925 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5926 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5927 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5928 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5929 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5930 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5931 tbinfo->attrdefs[j] = NULL; /* fix below */
5932 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5934 /* these flags will be set in flagInhAttrs() */
5935 tbinfo->inhAttrs[j] = false;
5936 tbinfo->inhAttrDef[j] = false;
5937 tbinfo->inhNotNull[j] = false;
5943 * Get info about column defaults
5947 AttrDefInfo *attrdefs;
5951 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5954 resetPQExpBuffer(q);
5955 if (fout->remoteVersion >= 70300)
5957 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5958 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5959 "FROM pg_catalog.pg_attrdef "
5960 "WHERE adrelid = '%u'::pg_catalog.oid",
5961 tbinfo->dobj.catId.oid);
5963 else if (fout->remoteVersion >= 70200)
5965 /* 7.2 did not have OIDs in pg_attrdef */
5966 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5967 "pg_get_expr(adbin, adrelid) AS adsrc "
5969 "WHERE adrelid = '%u'::oid",
5970 tbinfo->dobj.catId.oid);
5972 else if (fout->remoteVersion >= 70100)
5974 /* no pg_get_expr, so must rely on adsrc */
5975 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5977 "WHERE adrelid = '%u'::oid",
5978 tbinfo->dobj.catId.oid);
5982 /* no pg_get_expr, no tableoid either */
5983 appendPQExpBuffer(q, "SELECT "
5984 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5985 "oid, adnum, adsrc "
5987 "WHERE adrelid = '%u'::oid",
5988 tbinfo->dobj.catId.oid);
5990 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5992 numDefaults = PQntuples(res);
5993 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5995 for (j = 0; j < numDefaults; j++)
5999 attrdefs[j].dobj.objType = DO_ATTRDEF;
6000 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6001 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6002 AssignDumpId(&attrdefs[j].dobj);
6003 attrdefs[j].adtable = tbinfo;
6004 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
6005 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6007 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6008 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6010 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6013 * Defaults on a VIEW must always be dumped as separate ALTER
6014 * TABLE commands. Defaults on regular tables are dumped as
6015 * part of the CREATE TABLE if possible. To check if it's
6016 * safe, we mark the default as needing to appear before the
6019 if (tbinfo->relkind == RELKIND_VIEW)
6021 attrdefs[j].separate = true;
6022 /* needed in case pre-7.3 DB: */
6023 addObjectDependency(&attrdefs[j].dobj,
6024 tbinfo->dobj.dumpId);
6028 attrdefs[j].separate = false;
6029 addObjectDependency(&tbinfo->dobj,
6030 attrdefs[j].dobj.dumpId);
6033 if (adnum <= 0 || adnum > ntups)
6035 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
6036 adnum, tbinfo->dobj.name);
6039 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6045 * Get info about table CHECK constraints
6047 if (tbinfo->ncheck > 0)
6049 ConstraintInfo *constrs;
6053 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6056 resetPQExpBuffer(q);
6057 if (fout->remoteVersion >= 90200)
6060 * conisonly and convalidated are new in 9.2 (actually, the latter
6061 * is there in 9.1, but it wasn't ever false for check constraints
6064 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6065 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6066 "conislocal, convalidated, conisonly "
6067 "FROM pg_catalog.pg_constraint "
6068 "WHERE conrelid = '%u'::pg_catalog.oid "
6069 " AND contype = 'c' "
6071 tbinfo->dobj.catId.oid);
6073 else if (fout->remoteVersion >= 80400)
6075 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6076 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6077 "conislocal, true AS convalidated, "
6078 "false as conisonly "
6079 "FROM pg_catalog.pg_constraint "
6080 "WHERE conrelid = '%u'::pg_catalog.oid "
6081 " AND contype = 'c' "
6083 tbinfo->dobj.catId.oid);
6085 else if (fout->remoteVersion >= 70400)
6087 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6088 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6089 "true AS conislocal, true AS convalidated, "
6090 "false as conisonly "
6091 "FROM pg_catalog.pg_constraint "
6092 "WHERE conrelid = '%u'::pg_catalog.oid "
6093 " AND contype = 'c' "
6095 tbinfo->dobj.catId.oid);
6097 else if (fout->remoteVersion >= 70300)
6099 /* no pg_get_constraintdef, must use consrc */
6100 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6101 "'CHECK (' || consrc || ')' AS consrc, "
6102 "true AS conislocal, true AS convalidated, "
6103 "false as conisonly "
6104 "FROM pg_catalog.pg_constraint "
6105 "WHERE conrelid = '%u'::pg_catalog.oid "
6106 " AND contype = 'c' "
6108 tbinfo->dobj.catId.oid);
6110 else if (fout->remoteVersion >= 70200)
6112 /* 7.2 did not have OIDs in pg_relcheck */
6113 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6114 "rcname AS conname, "
6115 "'CHECK (' || rcsrc || ')' AS consrc, "
6116 "true AS conislocal, true AS convalidated, "
6117 "false as conisonly "
6119 "WHERE rcrelid = '%u'::oid "
6121 tbinfo->dobj.catId.oid);
6123 else if (fout->remoteVersion >= 70100)
6125 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6126 "rcname AS conname, "
6127 "'CHECK (' || rcsrc || ')' AS consrc, "
6128 "true AS conislocal, true AS convalidated, "
6129 "false as conisonly "
6131 "WHERE rcrelid = '%u'::oid "
6133 tbinfo->dobj.catId.oid);
6137 /* no tableoid in 7.0 */
6138 appendPQExpBuffer(q, "SELECT "
6139 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6140 "oid, rcname AS conname, "
6141 "'CHECK (' || rcsrc || ')' AS consrc, "
6142 "true AS conislocal, true AS convalidated, "
6143 "false as conisonly "
6145 "WHERE rcrelid = '%u'::oid "
6147 tbinfo->dobj.catId.oid);
6149 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6151 numConstrs = PQntuples(res);
6152 if (numConstrs != tbinfo->ncheck)
6154 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6155 "expected %d check constraints on table \"%s\" but found %d\n",
6157 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6158 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6162 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6163 tbinfo->checkexprs = constrs;
6165 for (j = 0; j < numConstrs; j++)
6167 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6168 bool isonly = PQgetvalue(res, j, 6)[0] == 't';
6170 constrs[j].dobj.objType = DO_CONSTRAINT;
6171 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6172 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6173 AssignDumpId(&constrs[j].dobj);
6174 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6175 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6176 constrs[j].contable = tbinfo;
6177 constrs[j].condomain = NULL;
6178 constrs[j].contype = 'c';
6179 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6180 constrs[j].confrelid = InvalidOid;
6181 constrs[j].conindex = 0;
6182 constrs[j].condeferrable = false;
6183 constrs[j].condeferred = false;
6184 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6185 constrs[j].conisonly = isonly;
6187 * An unvalidated constraint needs to be dumped separately, so
6188 * that potentially-violating existing data is loaded before
6189 * the constraint. An ONLY constraint needs to be dumped
6192 constrs[j].separate = !validated || isonly;
6194 constrs[j].dobj.dump = tbinfo->dobj.dump;
6197 * Mark the constraint as needing to appear before the table
6198 * --- this is so that any other dependencies of the
6199 * constraint will be emitted before we try to create the
6200 * table. If the constraint is to be dumped separately, it will be
6201 * dumped after data is loaded anyway, so don't do it. (There's
6202 * an automatic dependency in the opposite direction anyway, so
6203 * don't need to add one manually here.)
6205 if (!constrs[j].separate)
6206 addObjectDependency(&tbinfo->dobj,
6207 constrs[j].dobj.dumpId);
6210 * If the constraint is inherited, this will be detected later
6211 * (in pre-8.4 databases). We also detect later if the
6212 * constraint must be split out from the table definition.
6219 destroyPQExpBuffer(q);
6225 * read all text search parsers in the system catalogs and return them
6226 * in the TSParserInfo* structure
6228 * numTSParsers is set to the number of parsers read in
6231 getTSParsers(Archive *fout, int *numTSParsers)
6236 PQExpBuffer query = createPQExpBuffer();
6237 TSParserInfo *prsinfo;
6248 /* Before 8.3, there is no built-in text search support */
6249 if (fout->remoteVersion < 80300)
6256 * find all text search objects, including builtin ones; we filter out
6257 * system-defined objects at dump-out time.
6260 /* Make sure we are in proper schema */
6261 selectSourceSchema(fout, "pg_catalog");
6263 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6264 "prsstart::oid, prstoken::oid, "
6265 "prsend::oid, prsheadline::oid, prslextype::oid "
6266 "FROM pg_ts_parser");
6268 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6270 ntups = PQntuples(res);
6271 *numTSParsers = ntups;
6273 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6275 i_tableoid = PQfnumber(res, "tableoid");
6276 i_oid = PQfnumber(res, "oid");
6277 i_prsname = PQfnumber(res, "prsname");
6278 i_prsnamespace = PQfnumber(res, "prsnamespace");
6279 i_prsstart = PQfnumber(res, "prsstart");
6280 i_prstoken = PQfnumber(res, "prstoken");
6281 i_prsend = PQfnumber(res, "prsend");
6282 i_prsheadline = PQfnumber(res, "prsheadline");
6283 i_prslextype = PQfnumber(res, "prslextype");
6285 for (i = 0; i < ntups; i++)
6287 prsinfo[i].dobj.objType = DO_TSPARSER;
6288 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6289 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6290 AssignDumpId(&prsinfo[i].dobj);
6291 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6292 prsinfo[i].dobj.namespace =
6294 atooid(PQgetvalue(res, i, i_prsnamespace)),
6295 prsinfo[i].dobj.catId.oid);
6296 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6297 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6298 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6299 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6300 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6302 /* Decide whether we want to dump it */
6303 selectDumpableObject(&(prsinfo[i].dobj));
6308 destroyPQExpBuffer(query);
6314 * getTSDictionaries:
6315 * read all text search dictionaries in the system catalogs and return them
6316 * in the TSDictInfo* structure
6318 * numTSDicts is set to the number of dictionaries read in
6321 getTSDictionaries(Archive *fout, int *numTSDicts)
6326 PQExpBuffer query = createPQExpBuffer();
6327 TSDictInfo *dictinfo;
6331 int i_dictnamespace;
6334 int i_dictinitoption;
6336 /* Before 8.3, there is no built-in text search support */
6337 if (fout->remoteVersion < 80300)
6343 /* Make sure we are in proper schema */
6344 selectSourceSchema(fout, "pg_catalog");
6346 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6347 "dictnamespace, (%s dictowner) AS rolname, "
6348 "dicttemplate, dictinitoption "
6352 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6354 ntups = PQntuples(res);
6355 *numTSDicts = ntups;
6357 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6359 i_tableoid = PQfnumber(res, "tableoid");
6360 i_oid = PQfnumber(res, "oid");
6361 i_dictname = PQfnumber(res, "dictname");
6362 i_dictnamespace = PQfnumber(res, "dictnamespace");
6363 i_rolname = PQfnumber(res, "rolname");
6364 i_dictinitoption = PQfnumber(res, "dictinitoption");
6365 i_dicttemplate = PQfnumber(res, "dicttemplate");
6367 for (i = 0; i < ntups; i++)
6369 dictinfo[i].dobj.objType = DO_TSDICT;
6370 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6371 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6372 AssignDumpId(&dictinfo[i].dobj);
6373 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6374 dictinfo[i].dobj.namespace =
6376 atooid(PQgetvalue(res, i, i_dictnamespace)),
6377 dictinfo[i].dobj.catId.oid);
6378 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6379 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6380 if (PQgetisnull(res, i, i_dictinitoption))
6381 dictinfo[i].dictinitoption = NULL;
6383 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6385 /* Decide whether we want to dump it */
6386 selectDumpableObject(&(dictinfo[i].dobj));
6391 destroyPQExpBuffer(query);
6398 * read all text search templates in the system catalogs and return them
6399 * in the TSTemplateInfo* structure
6401 * numTSTemplates is set to the number of templates read in
6404 getTSTemplates(Archive *fout, int *numTSTemplates)
6409 PQExpBuffer query = createPQExpBuffer();
6410 TSTemplateInfo *tmplinfo;
6414 int i_tmplnamespace;
6418 /* Before 8.3, there is no built-in text search support */
6419 if (fout->remoteVersion < 80300)
6421 *numTSTemplates = 0;
6425 /* Make sure we are in proper schema */
6426 selectSourceSchema(fout, "pg_catalog");
6428 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6429 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6430 "FROM pg_ts_template");
6432 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6434 ntups = PQntuples(res);
6435 *numTSTemplates = ntups;
6437 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6439 i_tableoid = PQfnumber(res, "tableoid");
6440 i_oid = PQfnumber(res, "oid");
6441 i_tmplname = PQfnumber(res, "tmplname");
6442 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6443 i_tmplinit = PQfnumber(res, "tmplinit");
6444 i_tmpllexize = PQfnumber(res, "tmpllexize");
6446 for (i = 0; i < ntups; i++)
6448 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6449 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6450 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6451 AssignDumpId(&tmplinfo[i].dobj);
6452 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6453 tmplinfo[i].dobj.namespace =
6455 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6456 tmplinfo[i].dobj.catId.oid);
6457 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6458 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6460 /* Decide whether we want to dump it */
6461 selectDumpableObject(&(tmplinfo[i].dobj));
6466 destroyPQExpBuffer(query);
6472 * getTSConfigurations:
6473 * read all text search configurations in the system catalogs and return
6474 * them in the TSConfigInfo* structure
6476 * numTSConfigs is set to the number of configurations read in
6479 getTSConfigurations(Archive *fout, int *numTSConfigs)
6484 PQExpBuffer query = createPQExpBuffer();
6485 TSConfigInfo *cfginfo;
6493 /* Before 8.3, there is no built-in text search support */
6494 if (fout->remoteVersion < 80300)
6500 /* Make sure we are in proper schema */
6501 selectSourceSchema(fout, "pg_catalog");
6503 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6504 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6505 "FROM pg_ts_config",
6508 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6510 ntups = PQntuples(res);
6511 *numTSConfigs = ntups;
6513 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6515 i_tableoid = PQfnumber(res, "tableoid");
6516 i_oid = PQfnumber(res, "oid");
6517 i_cfgname = PQfnumber(res, "cfgname");
6518 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6519 i_rolname = PQfnumber(res, "rolname");
6520 i_cfgparser = PQfnumber(res, "cfgparser");
6522 for (i = 0; i < ntups; i++)
6524 cfginfo[i].dobj.objType = DO_TSCONFIG;
6525 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6526 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6527 AssignDumpId(&cfginfo[i].dobj);
6528 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6529 cfginfo[i].dobj.namespace =
6531 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6532 cfginfo[i].dobj.catId.oid);
6533 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6534 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6536 /* Decide whether we want to dump it */
6537 selectDumpableObject(&(cfginfo[i].dobj));
6542 destroyPQExpBuffer(query);
6548 * getForeignDataWrappers:
6549 * read all foreign-data wrappers in the system catalogs and return
6550 * them in the FdwInfo* structure
6552 * numForeignDataWrappers is set to the number of fdws read in
6555 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6560 PQExpBuffer query = createPQExpBuffer();
6571 /* Before 8.4, there are no foreign-data wrappers */
6572 if (fout->remoteVersion < 80400)
6574 *numForeignDataWrappers = 0;
6578 /* Make sure we are in proper schema */
6579 selectSourceSchema(fout, "pg_catalog");
6581 if (fout->remoteVersion >= 90100)
6583 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6584 "(%s fdwowner) AS rolname, "
6585 "fdwhandler::pg_catalog.regproc, "
6586 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6587 "array_to_string(ARRAY("
6588 "SELECT quote_ident(option_name) || ' ' || "
6589 "quote_literal(option_value) "
6590 "FROM pg_options_to_table(fdwoptions) "
6591 "ORDER BY option_name"
6592 "), E',\n ') AS fdwoptions "
6593 "FROM pg_foreign_data_wrapper",
6598 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6599 "(%s fdwowner) AS rolname, "
6600 "'-' AS fdwhandler, "
6601 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6602 "array_to_string(ARRAY("
6603 "SELECT quote_ident(option_name) || ' ' || "
6604 "quote_literal(option_value) "
6605 "FROM pg_options_to_table(fdwoptions) "
6606 "ORDER BY option_name"
6607 "), E',\n ') AS fdwoptions "
6608 "FROM pg_foreign_data_wrapper",
6612 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6614 ntups = PQntuples(res);
6615 *numForeignDataWrappers = ntups;
6617 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6619 i_tableoid = PQfnumber(res, "tableoid");
6620 i_oid = PQfnumber(res, "oid");
6621 i_fdwname = PQfnumber(res, "fdwname");
6622 i_rolname = PQfnumber(res, "rolname");
6623 i_fdwhandler = PQfnumber(res, "fdwhandler");
6624 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6625 i_fdwacl = PQfnumber(res, "fdwacl");
6626 i_fdwoptions = PQfnumber(res, "fdwoptions");
6628 for (i = 0; i < ntups; i++)
6630 fdwinfo[i].dobj.objType = DO_FDW;
6631 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6632 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6633 AssignDumpId(&fdwinfo[i].dobj);
6634 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6635 fdwinfo[i].dobj.namespace = NULL;
6636 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6637 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6638 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6639 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6640 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6642 /* Decide whether we want to dump it */
6643 selectDumpableObject(&(fdwinfo[i].dobj));
6648 destroyPQExpBuffer(query);
6654 * getForeignServers:
6655 * read all foreign servers in the system catalogs and return
6656 * them in the ForeignServerInfo * structure
6658 * numForeignServers is set to the number of servers read in
6661 getForeignServers(Archive *fout, int *numForeignServers)
6666 PQExpBuffer query = createPQExpBuffer();
6667 ForeignServerInfo *srvinfo;
6678 /* Before 8.4, there are no foreign servers */
6679 if (fout->remoteVersion < 80400)
6681 *numForeignServers = 0;
6685 /* Make sure we are in proper schema */
6686 selectSourceSchema(fout,"pg_catalog");
6688 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6689 "(%s srvowner) AS rolname, "
6690 "srvfdw, srvtype, srvversion, srvacl,"
6691 "array_to_string(ARRAY("
6692 "SELECT quote_ident(option_name) || ' ' || "
6693 "quote_literal(option_value) "
6694 "FROM pg_options_to_table(srvoptions) "
6695 "ORDER BY option_name"
6696 "), E',\n ') AS srvoptions "
6697 "FROM pg_foreign_server",
6700 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6702 ntups = PQntuples(res);
6703 *numForeignServers = ntups;
6705 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6707 i_tableoid = PQfnumber(res, "tableoid");
6708 i_oid = PQfnumber(res, "oid");
6709 i_srvname = PQfnumber(res, "srvname");
6710 i_rolname = PQfnumber(res, "rolname");
6711 i_srvfdw = PQfnumber(res, "srvfdw");
6712 i_srvtype = PQfnumber(res, "srvtype");
6713 i_srvversion = PQfnumber(res, "srvversion");
6714 i_srvacl = PQfnumber(res, "srvacl");
6715 i_srvoptions = PQfnumber(res, "srvoptions");
6717 for (i = 0; i < ntups; i++)
6719 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6720 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6721 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6722 AssignDumpId(&srvinfo[i].dobj);
6723 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6724 srvinfo[i].dobj.namespace = NULL;
6725 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6726 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6727 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6728 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6729 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6730 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6732 /* Decide whether we want to dump it */
6733 selectDumpableObject(&(srvinfo[i].dobj));
6738 destroyPQExpBuffer(query);
6745 * read all default ACL information in the system catalogs and return
6746 * them in the DefaultACLInfo structure
6748 * numDefaultACLs is set to the number of ACLs read in
6751 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6753 DefaultACLInfo *daclinfo;
6759 int i_defaclnamespace;
6760 int i_defaclobjtype;
6765 if (fout->remoteVersion < 90000)
6767 *numDefaultACLs = 0;
6771 query = createPQExpBuffer();
6773 /* Make sure we are in proper schema */
6774 selectSourceSchema(fout, "pg_catalog");
6776 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6777 "(%s defaclrole) AS defaclrole, "
6781 "FROM pg_default_acl",
6784 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6786 ntups = PQntuples(res);
6787 *numDefaultACLs = ntups;
6789 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6791 i_oid = PQfnumber(res, "oid");
6792 i_tableoid = PQfnumber(res, "tableoid");
6793 i_defaclrole = PQfnumber(res, "defaclrole");
6794 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6795 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6796 i_defaclacl = PQfnumber(res, "defaclacl");
6798 for (i = 0; i < ntups; i++)
6800 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6802 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6803 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6804 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6805 AssignDumpId(&daclinfo[i].dobj);
6806 /* cheesy ... is it worth coming up with a better object name? */
6807 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6809 if (nspid != InvalidOid)
6810 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6811 daclinfo[i].dobj.catId.oid);
6813 daclinfo[i].dobj.namespace = NULL;
6815 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6816 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6817 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6819 /* Decide whether we want to dump it */
6820 selectDumpableDefaultACL(&(daclinfo[i]));
6825 destroyPQExpBuffer(query);
6833 * This routine is used to dump any comments associated with the
6834 * object handed to this routine. The routine takes a constant character
6835 * string for the target part of the comment-creation command, plus
6836 * the namespace and owner of the object (for labeling the ArchiveEntry),
6837 * plus catalog ID and subid which are the lookup key for pg_description,
6838 * plus the dump ID for the object (for setting a dependency).
6839 * If a matching pg_description entry is found, it is dumped.
6841 * Note: although this routine takes a dumpId for dependency purposes,
6842 * that purpose is just to mark the dependency in the emitted dump file
6843 * for possible future use by pg_restore. We do NOT use it for determining
6844 * ordering of the comment in the dump file, because this routine is called
6845 * after dependency sorting occurs. This routine should be called just after
6846 * calling ArchiveEntry() for the specified object.
6849 dumpComment(Archive *fout, const char *target,
6850 const char *namespace, const char *owner,
6851 CatalogId catalogId, int subid, DumpId dumpId)
6853 CommentItem *comments;
6856 /* Comments are schema not data ... except blob comments are data */
6857 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6868 /* Search for comments associated with catalogId, using table */
6869 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6872 /* Is there one matching the subid? */
6873 while (ncomments > 0)
6875 if (comments->objsubid == subid)
6881 /* If a comment exists, build COMMENT ON statement */
6884 PQExpBuffer query = createPQExpBuffer();
6886 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6887 appendStringLiteralAH(query, comments->descr, fout);
6888 appendPQExpBuffer(query, ";\n");
6891 * We mark comments as SECTION_NONE because they really belong in the
6892 * same section as their parent, whether that is pre-data or
6895 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6896 target, namespace, NULL, owner,
6897 false, "COMMENT", SECTION_NONE,
6898 query->data, "", NULL,
6902 destroyPQExpBuffer(query);
6907 * dumpTableComment --
6909 * As above, but dump comments for both the specified table (or view)
6913 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6914 const char *reltypename)
6916 CommentItem *comments;
6921 /* Comments are SCHEMA not data */
6925 /* Search for comments associated with relation, using table */
6926 ncomments = findComments(fout,
6927 tbinfo->dobj.catId.tableoid,
6928 tbinfo->dobj.catId.oid,
6931 /* If comments exist, build COMMENT ON statements */
6935 query = createPQExpBuffer();
6936 target = createPQExpBuffer();
6938 while (ncomments > 0)
6940 const char *descr = comments->descr;
6941 int objsubid = comments->objsubid;
6945 resetPQExpBuffer(target);
6946 appendPQExpBuffer(target, "%s %s", reltypename,
6947 fmtId(tbinfo->dobj.name));
6949 resetPQExpBuffer(query);
6950 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6951 appendStringLiteralAH(query, descr, fout);
6952 appendPQExpBuffer(query, ";\n");
6954 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6956 tbinfo->dobj.namespace->dobj.name,
6957 NULL, tbinfo->rolname,
6958 false, "COMMENT", SECTION_NONE,
6959 query->data, "", NULL,
6960 &(tbinfo->dobj.dumpId), 1,
6963 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6965 resetPQExpBuffer(target);
6966 appendPQExpBuffer(target, "COLUMN %s.",
6967 fmtId(tbinfo->dobj.name));
6968 appendPQExpBuffer(target, "%s",
6969 fmtId(tbinfo->attnames[objsubid - 1]));
6971 resetPQExpBuffer(query);
6972 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6973 appendStringLiteralAH(query, descr, fout);
6974 appendPQExpBuffer(query, ";\n");
6976 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6978 tbinfo->dobj.namespace->dobj.name,
6979 NULL, tbinfo->rolname,
6980 false, "COMMENT", SECTION_NONE,
6981 query->data, "", NULL,
6982 &(tbinfo->dobj.dumpId), 1,
6990 destroyPQExpBuffer(query);
6991 destroyPQExpBuffer(target);
6997 * Find the comment(s), if any, associated with the given object. All the
6998 * objsubid values associated with the given classoid/objoid are found with
7002 findComments(Archive *fout, Oid classoid, Oid objoid,
7003 CommentItem **items)
7005 /* static storage for table of comments */
7006 static CommentItem *comments = NULL;
7007 static int ncomments = -1;
7009 CommentItem *middle = NULL;
7014 /* Get comments if we didn't already */
7016 ncomments = collectComments(fout, &comments);
7019 * Pre-7.2, pg_description does not contain classoid, so collectComments
7020 * just stores a zero. If there's a collision on object OID, well, you
7021 * get duplicate comments.
7023 if (fout->remoteVersion < 70200)
7027 * Do binary search to find some item matching the object.
7030 high = &comments[ncomments - 1];
7033 middle = low + (high - low) / 2;
7035 if (classoid < middle->classoid)
7037 else if (classoid > middle->classoid)
7039 else if (objoid < middle->objoid)
7041 else if (objoid > middle->objoid)
7044 break; /* found a match */
7047 if (low > high) /* no matches */
7054 * Now determine how many items match the object. The search loop
7055 * invariant still holds: only items between low and high inclusive could
7059 while (middle > low)
7061 if (classoid != middle[-1].classoid ||
7062 objoid != middle[-1].objoid)
7071 while (middle <= high)
7073 if (classoid != middle->classoid ||
7074 objoid != middle->objoid)
7084 * collectComments --
7086 * Construct a table of all comments available for database objects.
7087 * We used to do per-object queries for the comments, but it's much faster
7088 * to pull them all over at once, and on most databases the memory cost
7091 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7094 collectComments(Archive *fout, CommentItem **items)
7104 CommentItem *comments;
7107 * Note we do NOT change source schema here; preserve the caller's
7111 query = createPQExpBuffer();
7113 if (fout->remoteVersion >= 70300)
7115 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7116 "FROM pg_catalog.pg_description "
7117 "ORDER BY classoid, objoid, objsubid");
7119 else if (fout->remoteVersion >= 70200)
7121 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7122 "FROM pg_description "
7123 "ORDER BY classoid, objoid, objsubid");
7127 /* Note: this will fail to find attribute comments in pre-7.2... */
7128 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7129 "FROM pg_description "
7133 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7135 /* Construct lookup table containing OIDs in numeric form */
7137 i_description = PQfnumber(res, "description");
7138 i_classoid = PQfnumber(res, "classoid");
7139 i_objoid = PQfnumber(res, "objoid");
7140 i_objsubid = PQfnumber(res, "objsubid");
7142 ntups = PQntuples(res);
7144 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7146 for (i = 0; i < ntups; i++)
7148 comments[i].descr = PQgetvalue(res, i, i_description);
7149 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7150 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7151 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7154 /* Do NOT free the PGresult since we are keeping pointers into it */
7155 destroyPQExpBuffer(query);
7162 * dumpDumpableObject
7164 * This routine and its subsidiaries are responsible for creating
7165 * ArchiveEntries (TOC objects) for each object to be dumped.
7168 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7173 switch (dobj->objType)
7178 case DO_FK_CONSTRAINT:
7180 skip = !(dumpSections & DUMP_POST_DATA);
7183 skip = !(dumpSections & DUMP_DATA);
7186 skip = !(dumpSections & DUMP_PRE_DATA);
7192 switch (dobj->objType)
7195 dumpNamespace(fout, (NamespaceInfo *) dobj);
7198 dumpExtension(fout, (ExtensionInfo *) dobj);
7201 dumpType(fout, (TypeInfo *) dobj);
7204 dumpShellType(fout, (ShellTypeInfo *) dobj);
7207 dumpFunc(fout, (FuncInfo *) dobj);
7210 dumpAgg(fout, (AggInfo *) dobj);
7213 dumpOpr(fout, (OprInfo *) dobj);
7216 dumpOpclass(fout, (OpclassInfo *) dobj);
7219 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7222 dumpCollation(fout, (CollInfo *) dobj);
7225 dumpConversion(fout, (ConvInfo *) dobj);
7228 dumpTable(fout, (TableInfo *) dobj);
7231 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7234 dumpIndex(fout, (IndxInfo *) dobj);
7237 dumpRule(fout, (RuleInfo *) dobj);
7240 dumpTrigger(fout, (TriggerInfo *) dobj);
7243 dumpConstraint(fout, (ConstraintInfo *) dobj);
7245 case DO_FK_CONSTRAINT:
7246 dumpConstraint(fout, (ConstraintInfo *) dobj);
7249 dumpProcLang(fout, (ProcLangInfo *) dobj);
7252 dumpCast(fout, (CastInfo *) dobj);
7255 dumpTableData(fout, (TableDataInfo *) dobj);
7258 /* table rowtypes and array types are never dumped separately */
7261 dumpTSParser(fout, (TSParserInfo *) dobj);
7264 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7267 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7270 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7273 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7275 case DO_FOREIGN_SERVER:
7276 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7278 case DO_DEFAULT_ACL:
7279 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7282 dumpBlob(fout, (BlobInfo *) dobj);
7285 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7286 dobj->name, NULL, NULL, "",
7287 false, "BLOBS", SECTION_DATA,
7289 dobj->dependencies, dobj->nDeps,
7297 * writes out to fout the queries to recreate a user-defined namespace
7300 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7307 /* Skip if not to be dumped */
7308 if (!nspinfo->dobj.dump || dataOnly)
7311 /* don't dump dummy namespace from pre-7.3 source */
7312 if (strlen(nspinfo->dobj.name) == 0)
7315 q = createPQExpBuffer();
7316 delq = createPQExpBuffer();
7317 labelq = createPQExpBuffer();
7319 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7321 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7323 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7325 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7328 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7330 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7334 false, "SCHEMA", SECTION_PRE_DATA,
7335 q->data, delq->data, NULL,
7336 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7339 /* Dump Schema Comments and Security Labels */
7340 dumpComment(fout, labelq->data,
7341 NULL, nspinfo->rolname,
7342 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7343 dumpSecLabel(fout, labelq->data,
7344 NULL, nspinfo->rolname,
7345 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7347 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7348 qnspname, NULL, nspinfo->dobj.name, NULL,
7349 nspinfo->rolname, nspinfo->nspacl);
7353 destroyPQExpBuffer(q);
7354 destroyPQExpBuffer(delq);
7355 destroyPQExpBuffer(labelq);
7360 * writes out to fout the queries to recreate an extension
7363 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7370 /* Skip if not to be dumped */
7371 if (!extinfo->dobj.dump || dataOnly)
7374 q = createPQExpBuffer();
7375 delq = createPQExpBuffer();
7376 labelq = createPQExpBuffer();
7378 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7380 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7382 if (!binary_upgrade)
7385 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7386 * problem if the extension already exists in the target database;
7387 * this is essential for installed-by-default extensions such as
7390 * In binary-upgrade mode, that doesn't work well, so instead we skip
7391 * built-in extensions based on their OIDs; see
7392 * selectDumpableExtension.
7394 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7395 qextname, fmtId(extinfo->namespace));
7402 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7403 appendPQExpBuffer(q,
7404 "SELECT binary_upgrade.create_empty_extension(");
7405 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7406 appendPQExpBuffer(q, ", ");
7407 appendStringLiteralAH(q, extinfo->namespace, fout);
7408 appendPQExpBuffer(q, ", ");
7409 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7410 appendStringLiteralAH(q, extinfo->extversion, fout);
7411 appendPQExpBuffer(q, ", ");
7414 * Note that we're pushing extconfig (an OID array) back into
7415 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7416 * preserved in binary upgrade.
7418 if (strlen(extinfo->extconfig) > 2)
7419 appendStringLiteralAH(q, extinfo->extconfig, fout);
7421 appendPQExpBuffer(q, "NULL");
7422 appendPQExpBuffer(q, ", ");
7423 if (strlen(extinfo->extcondition) > 2)
7424 appendStringLiteralAH(q, extinfo->extcondition, fout);
7426 appendPQExpBuffer(q, "NULL");
7427 appendPQExpBuffer(q, ", ");
7428 appendPQExpBuffer(q, "ARRAY[");
7430 for (i = 0; i < extinfo->dobj.nDeps; i++)
7432 DumpableObject *extobj;
7434 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7435 if (extobj && extobj->objType == DO_EXTENSION)
7438 appendPQExpBuffer(q, ",");
7439 appendStringLiteralAH(q, extobj->name, fout);
7442 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7443 appendPQExpBuffer(q, ");\n");
7446 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7448 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7452 false, "EXTENSION", SECTION_PRE_DATA,
7453 q->data, delq->data, NULL,
7454 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7457 /* Dump Extension Comments and Security Labels */
7458 dumpComment(fout, labelq->data,
7460 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7461 dumpSecLabel(fout, labelq->data,
7463 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7467 destroyPQExpBuffer(q);
7468 destroyPQExpBuffer(delq);
7469 destroyPQExpBuffer(labelq);
7474 * writes out to fout the queries to recreate a user-defined type
7477 dumpType(Archive *fout, TypeInfo *tyinfo)
7479 /* Skip if not to be dumped */
7480 if (!tyinfo->dobj.dump || dataOnly)
7483 /* Dump out in proper style */
7484 if (tyinfo->typtype == TYPTYPE_BASE)
7485 dumpBaseType(fout, tyinfo);
7486 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7487 dumpDomain(fout, tyinfo);
7488 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7489 dumpCompositeType(fout, tyinfo);
7490 else if (tyinfo->typtype == TYPTYPE_ENUM)
7491 dumpEnumType(fout, tyinfo);
7492 else if (tyinfo->typtype == TYPTYPE_RANGE)
7493 dumpRangeType(fout, tyinfo);
7495 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7501 * writes out to fout the queries to recreate a user-defined enum type
7504 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7506 PQExpBuffer q = createPQExpBuffer();
7507 PQExpBuffer delq = createPQExpBuffer();
7508 PQExpBuffer labelq = createPQExpBuffer();
7509 PQExpBuffer query = createPQExpBuffer();
7516 /* Set proper schema search path */
7517 selectSourceSchema(fout, "pg_catalog");
7519 if (fout->remoteVersion >= 90100)
7520 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7521 "FROM pg_catalog.pg_enum "
7522 "WHERE enumtypid = '%u'"
7523 "ORDER BY enumsortorder",
7524 tyinfo->dobj.catId.oid);
7526 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7527 "FROM pg_catalog.pg_enum "
7528 "WHERE enumtypid = '%u'"
7530 tyinfo->dobj.catId.oid);
7532 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7534 num = PQntuples(res);
7537 * DROP must be fully qualified in case same name appears in pg_catalog.
7538 * CASCADE shouldn't be required here as for normal types since the I/O
7539 * functions are generic and do not get dropped.
7541 appendPQExpBuffer(delq, "DROP TYPE %s.",
7542 fmtId(tyinfo->dobj.namespace->dobj.name));
7543 appendPQExpBuffer(delq, "%s;\n",
7544 fmtId(tyinfo->dobj.name));
7547 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7548 tyinfo->dobj.catId.oid);
7550 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7551 fmtId(tyinfo->dobj.name));
7553 if (!binary_upgrade)
7555 /* Labels with server-assigned oids */
7556 for (i = 0; i < num; i++)
7558 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7560 appendPQExpBuffer(q, ",");
7561 appendPQExpBuffer(q, "\n ");
7562 appendStringLiteralAH(q, label, fout);
7566 appendPQExpBuffer(q, "\n);\n");
7570 /* Labels with dump-assigned (preserved) oids */
7571 for (i = 0; i < num; i++)
7573 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7574 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7577 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7578 appendPQExpBuffer(q,
7579 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7581 appendPQExpBuffer(q, "ALTER TYPE %s.",
7582 fmtId(tyinfo->dobj.namespace->dobj.name));
7583 appendPQExpBuffer(q, "%s ADD VALUE ",
7584 fmtId(tyinfo->dobj.name));
7585 appendStringLiteralAH(q, label, fout);
7586 appendPQExpBuffer(q, ";\n\n");
7590 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7593 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7595 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7597 tyinfo->dobj.namespace->dobj.name,
7599 tyinfo->rolname, false,
7600 "TYPE", SECTION_PRE_DATA,
7601 q->data, delq->data, NULL,
7602 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7605 /* Dump Type Comments and Security Labels */
7606 dumpComment(fout, labelq->data,
7607 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7608 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7609 dumpSecLabel(fout, labelq->data,
7610 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7611 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7614 destroyPQExpBuffer(q);
7615 destroyPQExpBuffer(delq);
7616 destroyPQExpBuffer(labelq);
7617 destroyPQExpBuffer(query);
7622 * writes out to fout the queries to recreate a user-defined range type
7625 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7627 PQExpBuffer q = createPQExpBuffer();
7628 PQExpBuffer delq = createPQExpBuffer();
7629 PQExpBuffer labelq = createPQExpBuffer();
7630 PQExpBuffer query = createPQExpBuffer();
7636 * select appropriate schema to ensure names in CREATE are properly
7639 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7641 appendPQExpBuffer(query,
7642 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7643 "opc.opcname AS opcname, "
7644 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7645 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7647 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7648 " ELSE rngcollation END AS collation, "
7649 "rngcanonical, rngsubdiff "
7650 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7651 " pg_catalog.pg_opclass opc "
7652 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7654 tyinfo->dobj.catId.oid);
7656 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7657 if (PQntuples(res) != 1)
7659 write_msg(NULL, "query returned %d pg_range entries for range type \"%s\"\n",
7660 PQntuples(res), tyinfo->dobj.name);
7665 * DROP must be fully qualified in case same name appears in pg_catalog.
7666 * CASCADE shouldn't be required here as for normal types since the I/O
7667 * functions are generic and do not get dropped.
7669 appendPQExpBuffer(delq, "DROP TYPE %s.",
7670 fmtId(tyinfo->dobj.namespace->dobj.name));
7671 appendPQExpBuffer(delq, "%s;\n",
7672 fmtId(tyinfo->dobj.name));
7675 binary_upgrade_set_type_oids_by_type_oid(fout,
7676 q, tyinfo->dobj.catId.oid);
7678 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7679 fmtId(tyinfo->dobj.name));
7681 appendPQExpBuffer(q, "\n subtype = %s",
7682 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7684 /* print subtype_opclass only if not default for subtype */
7685 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7687 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7688 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7690 /* always schema-qualify, don't try to be smart */
7691 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7693 appendPQExpBuffer(q, "%s", fmtId(opcname));
7696 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7697 if (OidIsValid(collationOid))
7699 CollInfo *coll = findCollationByOid(collationOid);
7703 /* always schema-qualify, don't try to be smart */
7704 appendPQExpBuffer(q, ",\n collation = %s.",
7705 fmtId(coll->dobj.namespace->dobj.name));
7706 appendPQExpBuffer(q, "%s",
7707 fmtId(coll->dobj.name));
7711 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7712 if (strcmp(procname, "-") != 0)
7713 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7715 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7716 if (strcmp(procname, "-") != 0)
7717 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7719 appendPQExpBuffer(q, "\n);\n");
7721 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7724 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7726 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7728 tyinfo->dobj.namespace->dobj.name,
7730 tyinfo->rolname, false,
7731 "TYPE", SECTION_PRE_DATA,
7732 q->data, delq->data, NULL,
7733 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7736 /* Dump Type Comments and Security Labels */
7737 dumpComment(fout, labelq->data,
7738 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7739 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7740 dumpSecLabel(fout, labelq->data,
7741 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7742 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7745 destroyPQExpBuffer(q);
7746 destroyPQExpBuffer(delq);
7747 destroyPQExpBuffer(labelq);
7748 destroyPQExpBuffer(query);
7753 * writes out to fout the queries to recreate a user-defined base type
7756 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7758 PQExpBuffer q = createPQExpBuffer();
7759 PQExpBuffer delq = createPQExpBuffer();
7760 PQExpBuffer labelq = createPQExpBuffer();
7761 PQExpBuffer query = createPQExpBuffer();
7778 char *typispreferred;
7783 char *typcollatable;
7785 bool typdefault_is_literal = false;
7787 /* Set proper schema search path so regproc references list correctly */
7788 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7790 /* Fetch type-specific details */
7791 if (fout->remoteVersion >= 90100)
7793 appendPQExpBuffer(query, "SELECT typlen, "
7794 "typinput, typoutput, typreceive, typsend, "
7795 "typmodin, typmodout, typanalyze, "
7796 "typreceive::pg_catalog.oid AS typreceiveoid, "
7797 "typsend::pg_catalog.oid AS typsendoid, "
7798 "typmodin::pg_catalog.oid AS typmodinoid, "
7799 "typmodout::pg_catalog.oid AS typmodoutoid, "
7800 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7801 "typcategory, typispreferred, "
7802 "typdelim, typbyval, typalign, typstorage, "
7803 "(typcollation <> 0) AS typcollatable, "
7804 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7805 "FROM pg_catalog.pg_type "
7806 "WHERE oid = '%u'::pg_catalog.oid",
7807 tyinfo->dobj.catId.oid);
7809 else if (fout->remoteVersion >= 80400)
7811 appendPQExpBuffer(query, "SELECT typlen, "
7812 "typinput, typoutput, typreceive, typsend, "
7813 "typmodin, typmodout, typanalyze, "
7814 "typreceive::pg_catalog.oid AS typreceiveoid, "
7815 "typsend::pg_catalog.oid AS typsendoid, "
7816 "typmodin::pg_catalog.oid AS typmodinoid, "
7817 "typmodout::pg_catalog.oid AS typmodoutoid, "
7818 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7819 "typcategory, typispreferred, "
7820 "typdelim, typbyval, typalign, typstorage, "
7821 "false AS typcollatable, "
7822 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7823 "FROM pg_catalog.pg_type "
7824 "WHERE oid = '%u'::pg_catalog.oid",
7825 tyinfo->dobj.catId.oid);
7827 else if (fout->remoteVersion >= 80300)
7829 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7830 appendPQExpBuffer(query, "SELECT typlen, "
7831 "typinput, typoutput, typreceive, typsend, "
7832 "typmodin, typmodout, typanalyze, "
7833 "typreceive::pg_catalog.oid AS typreceiveoid, "
7834 "typsend::pg_catalog.oid AS typsendoid, "
7835 "typmodin::pg_catalog.oid AS typmodinoid, "
7836 "typmodout::pg_catalog.oid AS typmodoutoid, "
7837 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7838 "'U' AS typcategory, false AS typispreferred, "
7839 "typdelim, typbyval, typalign, typstorage, "
7840 "false AS typcollatable, "
7841 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7842 "FROM pg_catalog.pg_type "
7843 "WHERE oid = '%u'::pg_catalog.oid",
7844 tyinfo->dobj.catId.oid);
7846 else if (fout->remoteVersion >= 80000)
7848 appendPQExpBuffer(query, "SELECT typlen, "
7849 "typinput, typoutput, typreceive, typsend, "
7850 "'-' AS typmodin, '-' AS typmodout, "
7852 "typreceive::pg_catalog.oid AS typreceiveoid, "
7853 "typsend::pg_catalog.oid AS typsendoid, "
7854 "0 AS typmodinoid, 0 AS typmodoutoid, "
7855 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7856 "'U' AS typcategory, false AS typispreferred, "
7857 "typdelim, typbyval, typalign, typstorage, "
7858 "false AS typcollatable, "
7859 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7860 "FROM pg_catalog.pg_type "
7861 "WHERE oid = '%u'::pg_catalog.oid",
7862 tyinfo->dobj.catId.oid);
7864 else if (fout->remoteVersion >= 70400)
7866 appendPQExpBuffer(query, "SELECT typlen, "
7867 "typinput, typoutput, typreceive, typsend, "
7868 "'-' AS typmodin, '-' AS typmodout, "
7869 "'-' AS typanalyze, "
7870 "typreceive::pg_catalog.oid AS typreceiveoid, "
7871 "typsend::pg_catalog.oid AS typsendoid, "
7872 "0 AS typmodinoid, 0 AS typmodoutoid, "
7873 "0 AS typanalyzeoid, "
7874 "'U' AS typcategory, false AS typispreferred, "
7875 "typdelim, typbyval, typalign, typstorage, "
7876 "false AS typcollatable, "
7877 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7878 "FROM pg_catalog.pg_type "
7879 "WHERE oid = '%u'::pg_catalog.oid",
7880 tyinfo->dobj.catId.oid);
7882 else if (fout->remoteVersion >= 70300)
7884 appendPQExpBuffer(query, "SELECT typlen, "
7885 "typinput, typoutput, "
7886 "'-' AS typreceive, '-' AS typsend, "
7887 "'-' AS typmodin, '-' AS typmodout, "
7888 "'-' AS typanalyze, "
7889 "0 AS typreceiveoid, 0 AS typsendoid, "
7890 "0 AS typmodinoid, 0 AS typmodoutoid, "
7891 "0 AS typanalyzeoid, "
7892 "'U' AS typcategory, false AS typispreferred, "
7893 "typdelim, typbyval, typalign, typstorage, "
7894 "false AS typcollatable, "
7895 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7896 "FROM pg_catalog.pg_type "
7897 "WHERE oid = '%u'::pg_catalog.oid",
7898 tyinfo->dobj.catId.oid);
7900 else if (fout->remoteVersion >= 70200)
7903 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7904 * ignore them because they are not right.
7906 appendPQExpBuffer(query, "SELECT typlen, "
7907 "typinput, typoutput, "
7908 "'-' AS typreceive, '-' AS typsend, "
7909 "'-' AS typmodin, '-' AS typmodout, "
7910 "'-' AS typanalyze, "
7911 "0 AS typreceiveoid, 0 AS typsendoid, "
7912 "0 AS typmodinoid, 0 AS typmodoutoid, "
7913 "0 AS typanalyzeoid, "
7914 "'U' AS typcategory, false AS typispreferred, "
7915 "typdelim, typbyval, typalign, typstorage, "
7916 "false AS typcollatable, "
7917 "NULL AS typdefaultbin, typdefault "
7919 "WHERE oid = '%u'::oid",
7920 tyinfo->dobj.catId.oid);
7922 else if (fout->remoteVersion >= 70100)
7925 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7928 appendPQExpBuffer(query, "SELECT typlen, "
7929 "typinput, typoutput, "
7930 "'-' AS typreceive, '-' AS typsend, "
7931 "'-' AS typmodin, '-' AS typmodout, "
7932 "'-' AS typanalyze, "
7933 "0 AS typreceiveoid, 0 AS typsendoid, "
7934 "0 AS typmodinoid, 0 AS typmodoutoid, "
7935 "0 AS typanalyzeoid, "
7936 "'U' AS typcategory, false AS typispreferred, "
7937 "typdelim, typbyval, typalign, typstorage, "
7938 "false AS typcollatable, "
7939 "NULL AS typdefaultbin, NULL AS typdefault "
7941 "WHERE oid = '%u'::oid",
7942 tyinfo->dobj.catId.oid);
7946 appendPQExpBuffer(query, "SELECT typlen, "
7947 "typinput, typoutput, "
7948 "'-' AS typreceive, '-' AS typsend, "
7949 "'-' AS typmodin, '-' AS typmodout, "
7950 "'-' AS typanalyze, "
7951 "0 AS typreceiveoid, 0 AS typsendoid, "
7952 "0 AS typmodinoid, 0 AS typmodoutoid, "
7953 "0 AS typanalyzeoid, "
7954 "'U' AS typcategory, false AS typispreferred, "
7955 "typdelim, typbyval, typalign, "
7956 "'p'::char AS typstorage, "
7957 "false AS typcollatable, "
7958 "NULL AS typdefaultbin, NULL AS typdefault "
7960 "WHERE oid = '%u'::oid",
7961 tyinfo->dobj.catId.oid);
7964 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7966 /* Expecting a single result only */
7967 ntups = PQntuples(res);
7970 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7971 "query returned %d rows instead of one: %s\n",
7973 ntups, query->data);
7977 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7978 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7979 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7980 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7981 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7982 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7983 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7984 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7985 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7986 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7987 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7988 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7989 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7990 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7991 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7992 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7993 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7994 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7995 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7996 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7997 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7998 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7999 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8001 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8002 typdefault_is_literal = true; /* it needs quotes */
8008 * DROP must be fully qualified in case same name appears in pg_catalog.
8009 * The reason we include CASCADE is that the circular dependency between
8010 * the type and its I/O functions makes it impossible to drop the type any
8013 appendPQExpBuffer(delq, "DROP TYPE %s.",
8014 fmtId(tyinfo->dobj.namespace->dobj.name));
8015 appendPQExpBuffer(delq, "%s CASCADE;\n",
8016 fmtId(tyinfo->dobj.name));
8018 /* We might already have a shell type, but setting pg_type_oid is harmless */
8020 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8021 tyinfo->dobj.catId.oid);
8023 appendPQExpBuffer(q,
8024 "CREATE TYPE %s (\n"
8025 " INTERNALLENGTH = %s",
8026 fmtId(tyinfo->dobj.name),
8027 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8029 if (fout->remoteVersion >= 70300)
8031 /* regproc result is correctly quoted as of 7.3 */
8032 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8033 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8034 if (OidIsValid(typreceiveoid))
8035 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8036 if (OidIsValid(typsendoid))
8037 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8038 if (OidIsValid(typmodinoid))
8039 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8040 if (OidIsValid(typmodoutoid))
8041 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8042 if (OidIsValid(typanalyzeoid))
8043 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8047 /* regproc delivers an unquoted name before 7.3 */
8048 /* cannot combine these because fmtId uses static result area */
8049 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8050 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8051 /* receive/send/typmodin/typmodout/analyze need not be printed */
8054 if (strcmp(typcollatable, "t") == 0)
8055 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8057 if (typdefault != NULL)
8059 appendPQExpBuffer(q, ",\n DEFAULT = ");
8060 if (typdefault_is_literal)
8061 appendStringLiteralAH(q, typdefault, fout);
8063 appendPQExpBufferStr(q, typdefault);
8066 if (OidIsValid(tyinfo->typelem))
8070 /* reselect schema in case changed by function dump */
8071 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8072 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8073 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8077 if (strcmp(typcategory, "U") != 0)
8079 appendPQExpBuffer(q, ",\n CATEGORY = ");
8080 appendStringLiteralAH(q, typcategory, fout);
8083 if (strcmp(typispreferred, "t") == 0)
8084 appendPQExpBuffer(q, ",\n PREFERRED = true");
8086 if (typdelim && strcmp(typdelim, ",") != 0)
8088 appendPQExpBuffer(q, ",\n DELIMITER = ");
8089 appendStringLiteralAH(q, typdelim, fout);
8092 if (strcmp(typalign, "c") == 0)
8093 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8094 else if (strcmp(typalign, "s") == 0)
8095 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8096 else if (strcmp(typalign, "i") == 0)
8097 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8098 else if (strcmp(typalign, "d") == 0)
8099 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8101 if (strcmp(typstorage, "p") == 0)
8102 appendPQExpBuffer(q, ",\n STORAGE = plain");
8103 else if (strcmp(typstorage, "e") == 0)
8104 appendPQExpBuffer(q, ",\n STORAGE = external");
8105 else if (strcmp(typstorage, "x") == 0)
8106 appendPQExpBuffer(q, ",\n STORAGE = extended");
8107 else if (strcmp(typstorage, "m") == 0)
8108 appendPQExpBuffer(q, ",\n STORAGE = main");
8110 if (strcmp(typbyval, "t") == 0)
8111 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8113 appendPQExpBuffer(q, "\n);\n");
8115 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8118 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8120 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8122 tyinfo->dobj.namespace->dobj.name,
8124 tyinfo->rolname, false,
8125 "TYPE", SECTION_PRE_DATA,
8126 q->data, delq->data, NULL,
8127 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8130 /* Dump Type Comments and Security Labels */
8131 dumpComment(fout, labelq->data,
8132 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8133 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8134 dumpSecLabel(fout, labelq->data,
8135 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8136 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8139 destroyPQExpBuffer(q);
8140 destroyPQExpBuffer(delq);
8141 destroyPQExpBuffer(labelq);
8142 destroyPQExpBuffer(query);
8147 * writes out to fout the queries to recreate a user-defined domain
8150 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8152 PQExpBuffer q = createPQExpBuffer();
8153 PQExpBuffer delq = createPQExpBuffer();
8154 PQExpBuffer labelq = createPQExpBuffer();
8155 PQExpBuffer query = createPQExpBuffer();
8163 bool typdefault_is_literal = false;
8165 /* Set proper schema search path so type references list correctly */
8166 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8168 /* Fetch domain specific details */
8169 if (fout->remoteVersion >= 90100)
8171 /* typcollation is new in 9.1 */
8172 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8173 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8174 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8176 "CASE WHEN t.typcollation <> u.typcollation "
8177 "THEN t.typcollation ELSE 0 END AS typcollation "
8178 "FROM pg_catalog.pg_type t "
8179 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8180 "WHERE t.oid = '%u'::pg_catalog.oid",
8181 tyinfo->dobj.catId.oid);
8185 /* We assume here that remoteVersion must be at least 70300 */
8186 appendPQExpBuffer(query, "SELECT typnotnull, "
8187 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8188 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8189 "typdefault, 0 AS typcollation "
8190 "FROM pg_catalog.pg_type "
8191 "WHERE oid = '%u'::pg_catalog.oid",
8192 tyinfo->dobj.catId.oid);
8195 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8197 /* Expecting a single result only */
8198 ntups = PQntuples(res);
8201 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8202 "query returned %d rows instead of one: %s\n",
8204 ntups, query->data);
8208 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8209 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8210 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8211 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8212 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8214 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8215 typdefault_is_literal = true; /* it needs quotes */
8219 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8222 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8223 tyinfo->dobj.catId.oid);
8225 appendPQExpBuffer(q,
8226 "CREATE DOMAIN %s AS %s",
8227 fmtId(tyinfo->dobj.name),
8230 /* Print collation only if different from base type's collation */
8231 if (OidIsValid(typcollation))
8235 coll = findCollationByOid(typcollation);
8238 /* always schema-qualify, don't try to be smart */
8239 appendPQExpBuffer(q, " COLLATE %s.",
8240 fmtId(coll->dobj.namespace->dobj.name));
8241 appendPQExpBuffer(q, "%s",
8242 fmtId(coll->dobj.name));
8246 if (typnotnull[0] == 't')
8247 appendPQExpBuffer(q, " NOT NULL");
8249 if (typdefault != NULL)
8251 appendPQExpBuffer(q, " DEFAULT ");
8252 if (typdefault_is_literal)
8253 appendStringLiteralAH(q, typdefault, fout);
8255 appendPQExpBufferStr(q, typdefault);
8261 * Add any CHECK constraints for the domain
8263 for (i = 0; i < tyinfo->nDomChecks; i++)
8265 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8267 if (!domcheck->separate)
8268 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8269 fmtId(domcheck->dobj.name), domcheck->condef);
8272 appendPQExpBuffer(q, ";\n");
8275 * DROP must be fully qualified in case same name appears in pg_catalog
8277 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8278 fmtId(tyinfo->dobj.namespace->dobj.name));
8279 appendPQExpBuffer(delq, "%s;\n",
8280 fmtId(tyinfo->dobj.name));
8282 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8285 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8287 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8289 tyinfo->dobj.namespace->dobj.name,
8291 tyinfo->rolname, false,
8292 "DOMAIN", SECTION_PRE_DATA,
8293 q->data, delq->data, NULL,
8294 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8297 /* Dump Domain Comments and Security Labels */
8298 dumpComment(fout, labelq->data,
8299 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8300 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8301 dumpSecLabel(fout, labelq->data,
8302 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8303 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8305 destroyPQExpBuffer(q);
8306 destroyPQExpBuffer(delq);
8307 destroyPQExpBuffer(labelq);
8308 destroyPQExpBuffer(query);
8313 * writes out to fout the queries to recreate a user-defined stand-alone
8317 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8319 PQExpBuffer q = createPQExpBuffer();
8320 PQExpBuffer dropped = createPQExpBuffer();
8321 PQExpBuffer delq = createPQExpBuffer();
8322 PQExpBuffer labelq = createPQExpBuffer();
8323 PQExpBuffer query = createPQExpBuffer();
8336 /* Set proper schema search path so type references list correctly */
8337 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8339 /* Fetch type specific details */
8340 if (fout->remoteVersion >= 90100)
8343 * attcollation is new in 9.1. Since we only want to dump COLLATE
8344 * clauses for attributes whose collation is different from their
8345 * type's default, we use a CASE here to suppress uninteresting
8346 * attcollations cheaply. atttypid will be 0 for dropped columns;
8347 * collation does not matter for those.
8349 appendPQExpBuffer(query, "SELECT a.attname, "
8350 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8351 "a.attlen, a.attalign, a.attisdropped, "
8352 "CASE WHEN a.attcollation <> at.typcollation "
8353 "THEN a.attcollation ELSE 0 END AS attcollation, "
8355 "FROM pg_catalog.pg_type ct "
8356 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8357 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8358 "WHERE ct.oid = '%u'::pg_catalog.oid "
8359 "ORDER BY a.attnum ",
8360 tyinfo->dobj.catId.oid);
8365 * We assume here that remoteVersion must be at least 70300. Since
8366 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8369 appendPQExpBuffer(query, "SELECT a.attname, "
8370 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8371 "a.attlen, a.attalign, a.attisdropped, "
8372 "0 AS attcollation, "
8374 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8375 "WHERE ct.oid = '%u'::pg_catalog.oid "
8376 "AND a.attrelid = ct.typrelid "
8377 "ORDER BY a.attnum ",
8378 tyinfo->dobj.catId.oid);
8381 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8383 ntups = PQntuples(res);
8385 i_attname = PQfnumber(res, "attname");
8386 i_atttypdefn = PQfnumber(res, "atttypdefn");
8387 i_attlen = PQfnumber(res, "attlen");
8388 i_attalign = PQfnumber(res, "attalign");
8389 i_attisdropped = PQfnumber(res, "attisdropped");
8390 i_attcollation = PQfnumber(res, "attcollation");
8391 i_typrelid = PQfnumber(res, "typrelid");
8395 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8397 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8398 tyinfo->dobj.catId.oid);
8399 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8402 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8403 fmtId(tyinfo->dobj.name));
8406 for (i = 0; i < ntups; i++)
8415 attname = PQgetvalue(res, i, i_attname);
8416 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8417 attlen = PQgetvalue(res, i, i_attlen);
8418 attalign = PQgetvalue(res, i, i_attalign);
8419 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8420 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8422 if (attisdropped && !binary_upgrade)
8425 /* Format properly if not first attr */
8426 if (actual_atts++ > 0)
8427 appendPQExpBuffer(q, ",");
8428 appendPQExpBuffer(q, "\n\t");
8432 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8434 /* Add collation if not default for the column type */
8435 if (OidIsValid(attcollation))
8439 coll = findCollationByOid(attcollation);
8442 /* always schema-qualify, don't try to be smart */
8443 appendPQExpBuffer(q, " COLLATE %s.",
8444 fmtId(coll->dobj.namespace->dobj.name));
8445 appendPQExpBuffer(q, "%s",
8446 fmtId(coll->dobj.name));
8453 * This is a dropped attribute and we're in binary_upgrade mode.
8454 * Insert a placeholder for it in the CREATE TYPE command, and set
8455 * length and alignment with direct UPDATE to the catalogs
8456 * afterwards. See similar code in dumpTableSchema().
8458 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8460 /* stash separately for insertion after the CREATE TYPE */
8461 appendPQExpBuffer(dropped,
8462 "\n-- For binary upgrade, recreate dropped column.\n");
8463 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8465 "attalign = '%s', attbyval = false\n"
8466 "WHERE attname = ", attlen, attalign);
8467 appendStringLiteralAH(dropped, attname, fout);
8468 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8469 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8470 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8472 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8473 fmtId(tyinfo->dobj.name));
8474 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8478 appendPQExpBuffer(q, "\n);\n");
8479 appendPQExpBufferStr(q, dropped->data);
8482 * DROP must be fully qualified in case same name appears in pg_catalog
8484 appendPQExpBuffer(delq, "DROP TYPE %s.",
8485 fmtId(tyinfo->dobj.namespace->dobj.name));
8486 appendPQExpBuffer(delq, "%s;\n",
8487 fmtId(tyinfo->dobj.name));
8489 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8492 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8494 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8496 tyinfo->dobj.namespace->dobj.name,
8498 tyinfo->rolname, false,
8499 "TYPE", SECTION_PRE_DATA,
8500 q->data, delq->data, NULL,
8501 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8505 /* Dump Type Comments and Security Labels */
8506 dumpComment(fout, labelq->data,
8507 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8508 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8509 dumpSecLabel(fout, labelq->data,
8510 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8511 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8514 destroyPQExpBuffer(q);
8515 destroyPQExpBuffer(dropped);
8516 destroyPQExpBuffer(delq);
8517 destroyPQExpBuffer(labelq);
8518 destroyPQExpBuffer(query);
8520 /* Dump any per-column comments */
8521 dumpCompositeTypeColComments(fout, tyinfo);
8525 * dumpCompositeTypeColComments
8526 * writes out to fout the queries to recreate comments on the columns of
8527 * a user-defined stand-alone composite type
8530 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8532 CommentItem *comments;
8543 query = createPQExpBuffer();
8545 /* We assume here that remoteVersion must be at least 70300 */
8546 appendPQExpBuffer(query,
8547 "SELECT c.tableoid, a.attname, a.attnum "
8548 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8549 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8550 " AND NOT a.attisdropped "
8551 "ORDER BY a.attnum ",
8554 /* Fetch column attnames */
8555 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8557 ntups = PQntuples(res);
8561 destroyPQExpBuffer(query);
8565 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8567 /* Search for comments associated with type's pg_class OID */
8568 ncomments = findComments(fout,
8573 /* If no comments exist, we're done */
8577 destroyPQExpBuffer(query);
8581 /* Build COMMENT ON statements */
8582 target = createPQExpBuffer();
8584 i_attnum = PQfnumber(res, "attnum");
8585 i_attname = PQfnumber(res, "attname");
8586 while (ncomments > 0)
8588 const char *attname;
8591 for (i = 0; i < ntups; i++)
8593 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8595 attname = PQgetvalue(res, i, i_attname);
8599 if (attname) /* just in case we don't find it */
8601 const char *descr = comments->descr;
8603 resetPQExpBuffer(target);
8604 appendPQExpBuffer(target, "COLUMN %s.",
8605 fmtId(tyinfo->dobj.name));
8606 appendPQExpBuffer(target, "%s",
8609 resetPQExpBuffer(query);
8610 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8611 appendStringLiteralAH(query, descr, fout);
8612 appendPQExpBuffer(query, ";\n");
8614 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8616 tyinfo->dobj.namespace->dobj.name,
8617 NULL, tyinfo->rolname,
8618 false, "COMMENT", SECTION_NONE,
8619 query->data, "", NULL,
8620 &(tyinfo->dobj.dumpId), 1,
8629 destroyPQExpBuffer(query);
8630 destroyPQExpBuffer(target);
8635 * writes out to fout the queries to create a shell type
8637 * We dump a shell definition in advance of the I/O functions for the type.
8640 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8644 /* Skip if not to be dumped */
8645 if (!stinfo->dobj.dump || dataOnly)
8648 q = createPQExpBuffer();
8651 * Note the lack of a DROP command for the shell type; any required DROP
8652 * is driven off the base type entry, instead. This interacts with
8653 * _printTocEntry()'s use of the presence of a DROP command to decide
8654 * whether an entry needs an ALTER OWNER command. We don't want to alter
8655 * the shell type's owner immediately on creation; that should happen only
8656 * after it's filled in, otherwise the backend complains.
8660 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8661 stinfo->baseType->dobj.catId.oid);
8663 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8664 fmtId(stinfo->dobj.name));
8666 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8668 stinfo->dobj.namespace->dobj.name,
8670 stinfo->baseType->rolname, false,
8671 "SHELL TYPE", SECTION_PRE_DATA,
8673 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8676 destroyPQExpBuffer(q);
8680 * Determine whether we want to dump definitions for procedural languages.
8681 * Since the languages themselves don't have schemas, we can't rely on
8682 * the normal schema-based selection mechanism. We choose to dump them
8683 * whenever neither --schema nor --table was given. (Before 8.1, we used
8684 * the dump flag of the PL's call handler function, but in 8.1 this will
8685 * probably always be false since call handlers are created in pg_catalog.)
8687 * For some backwards compatibility with the older behavior, we forcibly
8688 * dump a PL if its handler function (and validator if any) are in a
8689 * dumpable namespace. That case is not checked here.
8691 * Also, if the PL belongs to an extension, we do not use this heuristic.
8692 * That case isn't checked here either.
8695 shouldDumpProcLangs(void)
8697 if (!include_everything)
8699 /* And they're schema not data */
8707 * writes out to fout the queries to recreate a user-defined
8708 * procedural language
8711 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8720 FuncInfo *inlineInfo = NULL;
8721 FuncInfo *validatorInfo = NULL;
8723 /* Skip if not to be dumped */
8724 if (!plang->dobj.dump || dataOnly)
8728 * Try to find the support function(s). It is not an error if we don't
8729 * find them --- if the functions are in the pg_catalog schema, as is
8730 * standard in 8.1 and up, then we won't have loaded them. (In this case
8731 * we will emit a parameterless CREATE LANGUAGE command, which will
8732 * require PL template knowledge in the backend to reload.)
8735 funcInfo = findFuncByOid(plang->lanplcallfoid);
8736 if (funcInfo != NULL && !funcInfo->dobj.dump)
8737 funcInfo = NULL; /* treat not-dumped same as not-found */
8739 if (OidIsValid(plang->laninline))
8741 inlineInfo = findFuncByOid(plang->laninline);
8742 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8746 if (OidIsValid(plang->lanvalidator))
8748 validatorInfo = findFuncByOid(plang->lanvalidator);
8749 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8750 validatorInfo = NULL;
8754 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8755 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8758 * However, for a language that belongs to an extension, we must not use
8759 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8760 * told to (via dobj.dump). Generally the support functions will belong
8761 * to the same extension and so have the same dump flags ... if they
8762 * don't, this might not work terribly nicely.
8764 useParams = (funcInfo != NULL &&
8765 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8766 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8768 if (!plang->dobj.ext_member)
8770 if (!useParams && !shouldDumpProcLangs())
8774 defqry = createPQExpBuffer();
8775 delqry = createPQExpBuffer();
8776 labelq = createPQExpBuffer();
8778 qlanname = pg_strdup(fmtId(plang->dobj.name));
8781 * If dumping a HANDLER clause, treat the language as being in the handler
8782 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8783 * it doesn't really have a schema.
8786 lanschema = funcInfo->dobj.namespace->dobj.name;
8790 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8795 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8796 plang->lanpltrusted ? "TRUSTED " : "",
8798 appendPQExpBuffer(defqry, " HANDLER %s",
8799 fmtId(funcInfo->dobj.name));
8800 if (OidIsValid(plang->laninline))
8802 appendPQExpBuffer(defqry, " INLINE ");
8803 /* Cope with possibility that inline is in different schema */
8804 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8805 appendPQExpBuffer(defqry, "%s.",
8806 fmtId(inlineInfo->dobj.namespace->dobj.name));
8807 appendPQExpBuffer(defqry, "%s",
8808 fmtId(inlineInfo->dobj.name));
8810 if (OidIsValid(plang->lanvalidator))
8812 appendPQExpBuffer(defqry, " VALIDATOR ");
8813 /* Cope with possibility that validator is in different schema */
8814 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8815 appendPQExpBuffer(defqry, "%s.",
8816 fmtId(validatorInfo->dobj.namespace->dobj.name));
8817 appendPQExpBuffer(defqry, "%s",
8818 fmtId(validatorInfo->dobj.name));
8824 * If not dumping parameters, then use CREATE OR REPLACE so that the
8825 * command will not fail if the language is preinstalled in the target
8826 * database. We restrict the use of REPLACE to this case so as to
8827 * eliminate the risk of replacing a language with incompatible
8828 * parameter settings: this command will only succeed at all if there
8829 * is a pg_pltemplate entry, and if there is one, the existing entry
8830 * must match it too.
8832 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8835 appendPQExpBuffer(defqry, ";\n");
8837 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8840 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8842 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8844 lanschema, NULL, plang->lanowner,
8845 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8846 defqry->data, delqry->data, NULL,
8847 plang->dobj.dependencies, plang->dobj.nDeps,
8850 /* Dump Proc Lang Comments and Security Labels */
8851 dumpComment(fout, labelq->data,
8853 plang->dobj.catId, 0, plang->dobj.dumpId);
8854 dumpSecLabel(fout, labelq->data,
8856 plang->dobj.catId, 0, plang->dobj.dumpId);
8858 if (plang->lanpltrusted)
8859 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8860 qlanname, NULL, plang->dobj.name,
8862 plang->lanowner, plang->lanacl);
8866 destroyPQExpBuffer(defqry);
8867 destroyPQExpBuffer(delqry);
8868 destroyPQExpBuffer(labelq);
8872 * format_function_arguments: generate function name and argument list
8874 * This is used when we can rely on pg_get_function_arguments to format
8875 * the argument list.
8878 format_function_arguments(FuncInfo *finfo, char *funcargs)
8882 initPQExpBuffer(&fn);
8883 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8888 * format_function_arguments_old: generate function name and argument list
8890 * The argument type names are qualified if needed. The function name
8891 * is never qualified.
8893 * This is used only with pre-8.4 servers, so we aren't expecting to see
8894 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8896 * Any or all of allargtypes, argmodes, argnames may be NULL.
8899 format_function_arguments_old(Archive *fout,
8900 FuncInfo *finfo, int nallargs,
8908 initPQExpBuffer(&fn);
8909 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8910 for (j = 0; j < nallargs; j++)
8914 const char *argmode;
8915 const char *argname;
8917 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8918 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8922 switch (argmodes[j][0])
8927 case PROARGMODE_OUT:
8930 case PROARGMODE_INOUT:
8934 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8942 argname = argnames ? argnames[j] : (char *) NULL;
8943 if (argname && argname[0] == '\0')
8946 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8947 (j > 0) ? ", " : "",
8949 argname ? fmtId(argname) : "",
8954 appendPQExpBuffer(&fn, ")");
8959 * format_function_signature: generate function name and argument list
8961 * This is like format_function_arguments_old except that only a minimal
8962 * list of input argument types is generated; this is sufficient to
8963 * reference the function, but not to define it.
8965 * If honor_quotes is false then the function name is never quoted.
8966 * This is appropriate for use in TOC tags, but not in SQL commands.
8969 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
8974 initPQExpBuffer(&fn);
8976 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8978 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8979 for (j = 0; j < finfo->nargs; j++)
8983 typname = getFormattedTypeName(fout, finfo->argtypes[j],
8986 appendPQExpBuffer(&fn, "%s%s",
8987 (j > 0) ? ", " : "",
8991 appendPQExpBuffer(&fn, ")");
8998 * dump out one function
9001 dumpFunc(Archive *fout, FuncInfo *finfo)
9009 char *funcsig; /* identity signature */
9010 char *funcfullsig; /* full signature */
9019 char *proallargtypes;
9032 char **allargtypes = NULL;
9033 char **argmodes = NULL;
9034 char **argnames = NULL;
9035 char **configitems = NULL;
9036 int nconfigitems = 0;
9039 /* Skip if not to be dumped */
9040 if (!finfo->dobj.dump || dataOnly)
9043 query = createPQExpBuffer();
9044 q = createPQExpBuffer();
9045 delqry = createPQExpBuffer();
9046 labelq = createPQExpBuffer();
9047 asPart = createPQExpBuffer();
9049 /* Set proper schema search path so type references list correctly */
9050 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9052 /* Fetch function-specific details */
9053 if (fout->remoteVersion >= 80400)
9056 * In 8.4 and up we rely on pg_get_function_arguments and
9057 * pg_get_function_result instead of examining proallargtypes etc.
9059 appendPQExpBuffer(query,
9060 "SELECT proretset, prosrc, probin, "
9061 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9062 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9063 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9064 "proiswindow, provolatile, proisstrict, prosecdef, "
9065 "proconfig, procost, prorows, "
9066 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9067 "FROM pg_catalog.pg_proc "
9068 "WHERE oid = '%u'::pg_catalog.oid",
9069 finfo->dobj.catId.oid);
9071 else if (fout->remoteVersion >= 80300)
9073 appendPQExpBuffer(query,
9074 "SELECT proretset, prosrc, probin, "
9075 "proallargtypes, proargmodes, proargnames, "
9076 "false AS proiswindow, "
9077 "provolatile, proisstrict, prosecdef, "
9078 "proconfig, procost, prorows, "
9079 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9080 "FROM pg_catalog.pg_proc "
9081 "WHERE oid = '%u'::pg_catalog.oid",
9082 finfo->dobj.catId.oid);
9084 else if (fout->remoteVersion >= 80100)
9086 appendPQExpBuffer(query,
9087 "SELECT proretset, prosrc, probin, "
9088 "proallargtypes, proargmodes, proargnames, "
9089 "false AS proiswindow, "
9090 "provolatile, proisstrict, prosecdef, "
9091 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9092 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9093 "FROM pg_catalog.pg_proc "
9094 "WHERE oid = '%u'::pg_catalog.oid",
9095 finfo->dobj.catId.oid);
9097 else if (fout->remoteVersion >= 80000)
9099 appendPQExpBuffer(query,
9100 "SELECT proretset, prosrc, probin, "
9101 "null AS proallargtypes, "
9102 "null AS proargmodes, "
9104 "false AS proiswindow, "
9105 "provolatile, proisstrict, prosecdef, "
9106 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9107 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9108 "FROM pg_catalog.pg_proc "
9109 "WHERE oid = '%u'::pg_catalog.oid",
9110 finfo->dobj.catId.oid);
9112 else if (fout->remoteVersion >= 70300)
9114 appendPQExpBuffer(query,
9115 "SELECT proretset, prosrc, probin, "
9116 "null AS proallargtypes, "
9117 "null AS proargmodes, "
9118 "null AS proargnames, "
9119 "false AS proiswindow, "
9120 "provolatile, proisstrict, prosecdef, "
9121 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9122 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9123 "FROM pg_catalog.pg_proc "
9124 "WHERE oid = '%u'::pg_catalog.oid",
9125 finfo->dobj.catId.oid);
9127 else if (fout->remoteVersion >= 70100)
9129 appendPQExpBuffer(query,
9130 "SELECT proretset, prosrc, probin, "
9131 "null AS proallargtypes, "
9132 "null AS proargmodes, "
9133 "null AS proargnames, "
9134 "false AS proiswindow, "
9135 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9137 "false AS prosecdef, "
9138 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9139 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9141 "WHERE oid = '%u'::oid",
9142 finfo->dobj.catId.oid);
9146 appendPQExpBuffer(query,
9147 "SELECT proretset, prosrc, probin, "
9148 "null AS proallargtypes, "
9149 "null AS proargmodes, "
9150 "null AS proargnames, "
9151 "false AS proiswindow, "
9152 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9153 "false AS proisstrict, "
9154 "false AS prosecdef, "
9155 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9156 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9158 "WHERE oid = '%u'::oid",
9159 finfo->dobj.catId.oid);
9162 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9164 /* Expecting a single result only */
9165 ntups = PQntuples(res);
9168 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9169 "query returned %d rows instead of one: %s\n",
9171 ntups, query->data);
9175 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9176 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9177 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9178 if (fout->remoteVersion >= 80400)
9180 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9181 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9182 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9183 proallargtypes = proargmodes = proargnames = NULL;
9187 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9188 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9189 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9190 funcargs = funciargs = funcresult = NULL;
9192 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9193 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9194 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9195 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9196 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9197 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9198 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9199 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9202 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9203 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9204 * versions would set it to "-". There are no known cases in which prosrc
9205 * is unused, so the tests below for "-" are probably useless.
9207 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9209 appendPQExpBuffer(asPart, "AS ");
9210 appendStringLiteralAH(asPart, probin, fout);
9211 if (strcmp(prosrc, "-") != 0)
9213 appendPQExpBuffer(asPart, ", ");
9216 * where we have bin, use dollar quoting if allowed and src
9217 * contains quote or backslash; else use regular quoting.
9219 if (disable_dollar_quoting ||
9220 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9221 appendStringLiteralAH(asPart, prosrc, fout);
9223 appendStringLiteralDQ(asPart, prosrc, NULL);
9228 if (strcmp(prosrc, "-") != 0)
9230 appendPQExpBuffer(asPart, "AS ");
9231 /* with no bin, dollar quote src unconditionally if allowed */
9232 if (disable_dollar_quoting)
9233 appendStringLiteralAH(asPart, prosrc, fout);
9235 appendStringLiteralDQ(asPart, prosrc, NULL);
9239 nallargs = finfo->nargs; /* unless we learn different from allargs */
9241 if (proallargtypes && *proallargtypes)
9245 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9246 nitems < finfo->nargs)
9248 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9257 if (proargmodes && *proargmodes)
9261 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9264 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9271 if (proargnames && *proargnames)
9275 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9278 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9285 if (proconfig && *proconfig)
9287 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9289 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9299 /* 8.4 or later; we rely on server-side code for most of the work */
9300 funcfullsig = format_function_arguments(finfo, funcargs);
9301 funcsig = format_function_arguments(finfo, funciargs);
9305 /* pre-8.4, do it ourselves */
9306 funcsig = format_function_arguments_old(fout,
9307 finfo, nallargs, allargtypes,
9308 argmodes, argnames);
9309 funcfullsig = funcsig;
9312 funcsig_tag = format_function_signature(fout, finfo, false);
9315 * DROP must be fully qualified in case same name appears in pg_catalog
9317 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9318 fmtId(finfo->dobj.namespace->dobj.name),
9321 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9323 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9326 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9328 appendPQExpBuffer(q, "RETURNS %s%s",
9329 (proretset[0] == 't') ? "SETOF " : "",
9334 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9336 if (proiswindow[0] == 't')
9337 appendPQExpBuffer(q, " WINDOW");
9339 if (provolatile[0] != PROVOLATILE_VOLATILE)
9341 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9342 appendPQExpBuffer(q, " IMMUTABLE");
9343 else if (provolatile[0] == PROVOLATILE_STABLE)
9344 appendPQExpBuffer(q, " STABLE");
9345 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9347 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
9353 if (proisstrict[0] == 't')
9354 appendPQExpBuffer(q, " STRICT");
9356 if (prosecdef[0] == 't')
9357 appendPQExpBuffer(q, " SECURITY DEFINER");
9360 * COST and ROWS are emitted only if present and not default, so as not to
9361 * break backwards-compatibility of the dump without need. Keep this code
9362 * in sync with the defaults in functioncmds.c.
9364 if (strcmp(procost, "0") != 0)
9366 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9368 /* default cost is 1 */
9369 if (strcmp(procost, "1") != 0)
9370 appendPQExpBuffer(q, " COST %s", procost);
9374 /* default cost is 100 */
9375 if (strcmp(procost, "100") != 0)
9376 appendPQExpBuffer(q, " COST %s", procost);
9379 if (proretset[0] == 't' &&
9380 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9381 appendPQExpBuffer(q, " ROWS %s", prorows);
9383 for (i = 0; i < nconfigitems; i++)
9385 /* we feel free to scribble on configitems[] here */
9386 char *configitem = configitems[i];
9389 pos = strchr(configitem, '=');
9393 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9396 * Some GUC variable names are 'LIST' type and hence must not be
9399 if (pg_strcasecmp(configitem, "DateStyle") == 0
9400 || pg_strcasecmp(configitem, "search_path") == 0)
9401 appendPQExpBuffer(q, "%s", pos);
9403 appendStringLiteralAH(q, pos, fout);
9406 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9408 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9411 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9413 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9415 finfo->dobj.namespace->dobj.name,
9417 finfo->rolname, false,
9418 "FUNCTION", SECTION_PRE_DATA,
9419 q->data, delqry->data, NULL,
9420 finfo->dobj.dependencies, finfo->dobj.nDeps,
9423 /* Dump Function Comments and Security Labels */
9424 dumpComment(fout, labelq->data,
9425 finfo->dobj.namespace->dobj.name, finfo->rolname,
9426 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9427 dumpSecLabel(fout, labelq->data,
9428 finfo->dobj.namespace->dobj.name, finfo->rolname,
9429 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9431 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9432 funcsig, NULL, funcsig_tag,
9433 finfo->dobj.namespace->dobj.name,
9434 finfo->rolname, finfo->proacl);
9438 destroyPQExpBuffer(query);
9439 destroyPQExpBuffer(q);
9440 destroyPQExpBuffer(delqry);
9441 destroyPQExpBuffer(labelq);
9442 destroyPQExpBuffer(asPart);
9457 * Dump a user-defined cast
9460 dumpCast(Archive *fout, CastInfo *cast)
9465 FuncInfo *funcInfo = NULL;
9467 /* Skip if not to be dumped */
9468 if (!cast->dobj.dump || dataOnly)
9471 /* Cannot dump if we don't have the cast function's info */
9472 if (OidIsValid(cast->castfunc))
9474 funcInfo = findFuncByOid(cast->castfunc);
9475 if (funcInfo == NULL)
9480 * As per discussion we dump casts if one or more of the underlying
9481 * objects (the conversion function and the two data types) are not
9482 * builtin AND if all of the non-builtin objects are included in the dump.
9483 * Builtin meaning, the namespace name does not start with "pg_".
9485 * However, for a cast that belongs to an extension, we must not use this
9486 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9488 if (!cast->dobj.ext_member)
9490 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9491 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9493 if (sourceInfo == NULL || targetInfo == NULL)
9497 * Skip this cast if all objects are from pg_
9499 if ((funcInfo == NULL ||
9500 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9501 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9502 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9506 * Skip cast if function isn't from pg_ and is not to be dumped.
9509 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9510 !funcInfo->dobj.dump)
9514 * Same for the source type
9516 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9517 !sourceInfo->dobj.dump)
9521 * and the target type.
9523 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9524 !targetInfo->dobj.dump)
9528 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9529 selectSourceSchema(fout, "pg_catalog");
9531 defqry = createPQExpBuffer();
9532 delqry = createPQExpBuffer();
9533 labelq = createPQExpBuffer();
9535 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9536 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9537 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9539 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9540 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9541 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9543 switch (cast->castmethod)
9545 case COERCION_METHOD_BINARY:
9546 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9548 case COERCION_METHOD_INOUT:
9549 appendPQExpBuffer(defqry, "WITH INOUT");
9551 case COERCION_METHOD_FUNCTION:
9554 * Always qualify the function name, in case it is not in
9555 * pg_catalog schema (format_function_signature won't qualify it).
9557 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
9558 fmtId(funcInfo->dobj.namespace->dobj.name));
9559 appendPQExpBuffer(defqry, "%s",
9560 format_function_signature(fout, funcInfo, true));
9563 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9566 if (cast->castcontext == 'a')
9567 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9568 else if (cast->castcontext == 'i')
9569 appendPQExpBuffer(defqry, " AS IMPLICIT");
9570 appendPQExpBuffer(defqry, ";\n");
9572 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9573 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9574 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9577 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9579 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9581 "pg_catalog", NULL, "",
9582 false, "CAST", SECTION_PRE_DATA,
9583 defqry->data, delqry->data, NULL,
9584 cast->dobj.dependencies, cast->dobj.nDeps,
9587 /* Dump Cast Comments */
9588 dumpComment(fout, labelq->data,
9590 cast->dobj.catId, 0, cast->dobj.dumpId);
9592 destroyPQExpBuffer(defqry);
9593 destroyPQExpBuffer(delqry);
9594 destroyPQExpBuffer(labelq);
9599 * write out a single operator definition
9602 dumpOpr(Archive *fout, OprInfo *oprinfo)
9609 PQExpBuffer details;
9634 /* Skip if not to be dumped */
9635 if (!oprinfo->dobj.dump || dataOnly)
9639 * some operators are invalid because they were the result of user
9640 * defining operators before commutators exist
9642 if (!OidIsValid(oprinfo->oprcode))
9645 query = createPQExpBuffer();
9646 q = createPQExpBuffer();
9647 delq = createPQExpBuffer();
9648 labelq = createPQExpBuffer();
9649 oprid = createPQExpBuffer();
9650 details = createPQExpBuffer();
9652 /* Make sure we are in proper schema so regoperator works correctly */
9653 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9655 if (fout->remoteVersion >= 80300)
9657 appendPQExpBuffer(query, "SELECT oprkind, "
9658 "oprcode::pg_catalog.regprocedure, "
9659 "oprleft::pg_catalog.regtype, "
9660 "oprright::pg_catalog.regtype, "
9661 "oprcom::pg_catalog.regoperator, "
9662 "oprnegate::pg_catalog.regoperator, "
9663 "oprrest::pg_catalog.regprocedure, "
9664 "oprjoin::pg_catalog.regprocedure, "
9665 "oprcanmerge, oprcanhash "
9666 "FROM pg_catalog.pg_operator "
9667 "WHERE oid = '%u'::pg_catalog.oid",
9668 oprinfo->dobj.catId.oid);
9670 else if (fout->remoteVersion >= 70300)
9672 appendPQExpBuffer(query, "SELECT oprkind, "
9673 "oprcode::pg_catalog.regprocedure, "
9674 "oprleft::pg_catalog.regtype, "
9675 "oprright::pg_catalog.regtype, "
9676 "oprcom::pg_catalog.regoperator, "
9677 "oprnegate::pg_catalog.regoperator, "
9678 "oprrest::pg_catalog.regprocedure, "
9679 "oprjoin::pg_catalog.regprocedure, "
9680 "(oprlsortop != 0) AS oprcanmerge, "
9682 "FROM pg_catalog.pg_operator "
9683 "WHERE oid = '%u'::pg_catalog.oid",
9684 oprinfo->dobj.catId.oid);
9686 else if (fout->remoteVersion >= 70100)
9688 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9689 "CASE WHEN oprleft = 0 THEN '-' "
9690 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9691 "CASE WHEN oprright = 0 THEN '-' "
9692 "ELSE format_type(oprright, NULL) END AS oprright, "
9693 "oprcom, oprnegate, oprrest, oprjoin, "
9694 "(oprlsortop != 0) AS oprcanmerge, "
9697 "WHERE oid = '%u'::oid",
9698 oprinfo->dobj.catId.oid);
9702 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9703 "CASE WHEN oprleft = 0 THEN '-'::name "
9704 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9705 "CASE WHEN oprright = 0 THEN '-'::name "
9706 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9707 "oprcom, oprnegate, oprrest, oprjoin, "
9708 "(oprlsortop != 0) AS oprcanmerge, "
9711 "WHERE oid = '%u'::oid",
9712 oprinfo->dobj.catId.oid);
9715 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9717 /* Expecting a single result only */
9718 ntups = PQntuples(res);
9721 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9722 "query returned %d rows instead of one: %s\n",
9724 ntups, query->data);
9728 i_oprkind = PQfnumber(res, "oprkind");
9729 i_oprcode = PQfnumber(res, "oprcode");
9730 i_oprleft = PQfnumber(res, "oprleft");
9731 i_oprright = PQfnumber(res, "oprright");
9732 i_oprcom = PQfnumber(res, "oprcom");
9733 i_oprnegate = PQfnumber(res, "oprnegate");
9734 i_oprrest = PQfnumber(res, "oprrest");
9735 i_oprjoin = PQfnumber(res, "oprjoin");
9736 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9737 i_oprcanhash = PQfnumber(res, "oprcanhash");
9739 oprkind = PQgetvalue(res, 0, i_oprkind);
9740 oprcode = PQgetvalue(res, 0, i_oprcode);
9741 oprleft = PQgetvalue(res, 0, i_oprleft);
9742 oprright = PQgetvalue(res, 0, i_oprright);
9743 oprcom = PQgetvalue(res, 0, i_oprcom);
9744 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9745 oprrest = PQgetvalue(res, 0, i_oprrest);
9746 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9747 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9748 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9750 appendPQExpBuffer(details, " PROCEDURE = %s",
9751 convertRegProcReference(fout, oprcode));
9753 appendPQExpBuffer(oprid, "%s (",
9754 oprinfo->dobj.name);
9757 * right unary means there's a left arg and left unary means there's a
9760 if (strcmp(oprkind, "r") == 0 ||
9761 strcmp(oprkind, "b") == 0)
9763 if (fout->remoteVersion >= 70100)
9766 name = fmtId(oprleft);
9767 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9768 appendPQExpBuffer(oprid, "%s", name);
9771 appendPQExpBuffer(oprid, "NONE");
9773 if (strcmp(oprkind, "l") == 0 ||
9774 strcmp(oprkind, "b") == 0)
9776 if (fout->remoteVersion >= 70100)
9779 name = fmtId(oprright);
9780 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9781 appendPQExpBuffer(oprid, ", %s)", name);
9784 appendPQExpBuffer(oprid, ", NONE)");
9786 name = convertOperatorReference(fout, oprcom);
9788 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9790 name = convertOperatorReference(fout, oprnegate);
9792 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9794 if (strcmp(oprcanmerge, "t") == 0)
9795 appendPQExpBuffer(details, ",\n MERGES");
9797 if (strcmp(oprcanhash, "t") == 0)
9798 appendPQExpBuffer(details, ",\n HASHES");
9800 name = convertRegProcReference(fout, oprrest);
9802 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9804 name = convertRegProcReference(fout, oprjoin);
9806 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9809 * DROP must be fully qualified in case same name appears in pg_catalog
9811 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9812 fmtId(oprinfo->dobj.namespace->dobj.name),
9815 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9816 oprinfo->dobj.name, details->data);
9818 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9821 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9823 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9825 oprinfo->dobj.namespace->dobj.name,
9828 false, "OPERATOR", SECTION_PRE_DATA,
9829 q->data, delq->data, NULL,
9830 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9833 /* Dump Operator Comments */
9834 dumpComment(fout, labelq->data,
9835 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9836 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9840 destroyPQExpBuffer(query);
9841 destroyPQExpBuffer(q);
9842 destroyPQExpBuffer(delq);
9843 destroyPQExpBuffer(labelq);
9844 destroyPQExpBuffer(oprid);
9845 destroyPQExpBuffer(details);
9849 * Convert a function reference obtained from pg_operator
9851 * Returns what to print, or NULL if function references is InvalidOid
9853 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9854 * argument-types part. In prior versions, the input is a REGPROC display.
9857 convertRegProcReference(Archive *fout, const char *proc)
9859 /* In all cases "-" means a null reference */
9860 if (strcmp(proc, "-") == 0)
9863 if (fout->remoteVersion >= 70300)
9869 name = pg_strdup(proc);
9870 /* find non-double-quoted left paren */
9872 for (paren = name; *paren; paren++)
9874 if (*paren == '(' && !inquote)
9885 /* REGPROC before 7.3 does not quote its result */
9890 * Convert an operator cross-reference obtained from pg_operator
9892 * Returns what to print, or NULL to print nothing
9894 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9895 * argument-types part, and add OPERATOR() decoration if the name is
9896 * schema-qualified. In older versions, the input is just a numeric OID,
9897 * which we search our operator list for.
9900 convertOperatorReference(Archive *fout, const char *opr)
9904 /* In all cases "0" means a null reference */
9905 if (strcmp(opr, "0") == 0)
9908 if (fout->remoteVersion >= 70300)
9916 name = pg_strdup(opr);
9917 /* find non-double-quoted left paren, and check for non-quoted dot */
9920 for (ptr = name; *ptr; ptr++)
9924 else if (*ptr == '.' && !inquote)
9926 else if (*ptr == '(' && !inquote)
9932 /* If not schema-qualified, don't need to add OPERATOR() */
9935 oname = pg_malloc(strlen(name) + 11);
9936 sprintf(oname, "OPERATOR(%s)", name);
9941 oprInfo = findOprByOid(atooid(opr));
9942 if (oprInfo == NULL)
9944 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9948 return oprInfo->dobj.name;
9952 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9954 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9955 * argument lists of these functions are predetermined. Note that the
9956 * caller should ensure we are in the proper schema, because the results
9957 * are search path dependent!
9960 convertTSFunction(Archive *fout, Oid funcOid)
9967 snprintf(query, sizeof(query),
9968 "SELECT '%u'::pg_catalog.regproc", funcOid);
9969 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
9971 ntups = PQntuples(res);
9974 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9975 "query returned %d rows instead of one: %s\n",
9981 result = pg_strdup(PQgetvalue(res, 0, 0));
9991 * write out a single operator class definition
9994 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10006 int i_opcfamilyname;
10007 int i_opcfamilynsp;
10009 int i_amopstrategy;
10010 int i_amopreqcheck;
10013 int i_sortfamilynsp;
10016 int i_amproclefttype;
10017 int i_amprocrighttype;
10022 char *opcfamilyname;
10023 char *opcfamilynsp;
10025 char *amopstrategy;
10026 char *amopreqcheck;
10029 char *sortfamilynsp;
10032 char *amproclefttype;
10033 char *amprocrighttype;
10037 /* Skip if not to be dumped */
10038 if (!opcinfo->dobj.dump || dataOnly)
10042 * XXX currently we do not implement dumping of operator classes from
10043 * pre-7.3 databases. This could be done but it seems not worth the
10046 if (fout->remoteVersion < 70300)
10049 query = createPQExpBuffer();
10050 q = createPQExpBuffer();
10051 delq = createPQExpBuffer();
10052 labelq = createPQExpBuffer();
10054 /* Make sure we are in proper schema so regoperator works correctly */
10055 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10057 /* Get additional fields from the pg_opclass row */
10058 if (fout->remoteVersion >= 80300)
10060 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10061 "opckeytype::pg_catalog.regtype, "
10062 "opcdefault, opcfamily, "
10063 "opfname AS opcfamilyname, "
10064 "nspname AS opcfamilynsp, "
10065 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10066 "FROM pg_catalog.pg_opclass c "
10067 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10068 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10069 "WHERE c.oid = '%u'::pg_catalog.oid",
10070 opcinfo->dobj.catId.oid);
10074 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10075 "opckeytype::pg_catalog.regtype, "
10076 "opcdefault, NULL AS opcfamily, "
10077 "NULL AS opcfamilyname, "
10078 "NULL AS opcfamilynsp, "
10079 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10080 "FROM pg_catalog.pg_opclass "
10081 "WHERE oid = '%u'::pg_catalog.oid",
10082 opcinfo->dobj.catId.oid);
10085 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10087 /* Expecting a single result only */
10088 ntups = PQntuples(res);
10091 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10092 "query returned %d rows instead of one: %s\n",
10094 ntups, query->data);
10098 i_opcintype = PQfnumber(res, "opcintype");
10099 i_opckeytype = PQfnumber(res, "opckeytype");
10100 i_opcdefault = PQfnumber(res, "opcdefault");
10101 i_opcfamily = PQfnumber(res, "opcfamily");
10102 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10103 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10104 i_amname = PQfnumber(res, "amname");
10106 opcintype = PQgetvalue(res, 0, i_opcintype);
10107 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10108 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10109 /* opcfamily will still be needed after we PQclear res */
10110 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10111 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10112 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10113 /* amname will still be needed after we PQclear res */
10114 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10117 * DROP must be fully qualified in case same name appears in pg_catalog
10119 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10120 fmtId(opcinfo->dobj.namespace->dobj.name));
10121 appendPQExpBuffer(delq, ".%s",
10122 fmtId(opcinfo->dobj.name));
10123 appendPQExpBuffer(delq, " USING %s;\n",
10126 /* Build the fixed portion of the CREATE command */
10127 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10128 fmtId(opcinfo->dobj.name));
10129 if (strcmp(opcdefault, "t") == 0)
10130 appendPQExpBuffer(q, "DEFAULT ");
10131 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10134 if (strlen(opcfamilyname) > 0 &&
10135 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10136 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10138 appendPQExpBuffer(q, " FAMILY ");
10139 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10140 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10141 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10143 appendPQExpBuffer(q, " AS\n ");
10147 if (strcmp(opckeytype, "-") != 0)
10149 appendPQExpBuffer(q, "STORAGE %s",
10157 * Now fetch and print the OPERATOR entries (pg_amop rows).
10159 * Print only those opfamily members that are tied to the opclass by
10160 * pg_depend entries.
10162 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10163 * older server's opclass in which it is used. This is to avoid
10164 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10165 * older server and then reload into that old version. This can go away
10166 * once 8.3 is so old as to not be of interest to anyone.
10168 resetPQExpBuffer(query);
10170 if (fout->remoteVersion >= 90100)
10172 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10173 "amopopr::pg_catalog.regoperator, "
10174 "opfname AS sortfamily, "
10175 "nspname AS sortfamilynsp "
10176 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10177 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10178 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10179 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10180 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10181 "AND refobjid = '%u'::pg_catalog.oid "
10182 "AND amopfamily = '%s'::pg_catalog.oid "
10183 "ORDER BY amopstrategy",
10184 opcinfo->dobj.catId.oid,
10187 else if (fout->remoteVersion >= 80400)
10189 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10190 "amopopr::pg_catalog.regoperator, "
10191 "NULL AS sortfamily, "
10192 "NULL AS sortfamilynsp "
10193 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10194 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10195 "AND refobjid = '%u'::pg_catalog.oid "
10196 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10197 "AND objid = ao.oid "
10198 "ORDER BY amopstrategy",
10199 opcinfo->dobj.catId.oid);
10201 else if (fout->remoteVersion >= 80300)
10203 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10204 "amopopr::pg_catalog.regoperator, "
10205 "NULL AS sortfamily, "
10206 "NULL AS sortfamilynsp "
10207 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10208 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10209 "AND refobjid = '%u'::pg_catalog.oid "
10210 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10211 "AND objid = ao.oid "
10212 "ORDER BY amopstrategy",
10213 opcinfo->dobj.catId.oid);
10218 * Here, we print all entries since there are no opfamilies and hence
10219 * no loose operators to worry about.
10221 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10222 "amopopr::pg_catalog.regoperator, "
10223 "NULL AS sortfamily, "
10224 "NULL AS sortfamilynsp "
10225 "FROM pg_catalog.pg_amop "
10226 "WHERE amopclaid = '%u'::pg_catalog.oid "
10227 "ORDER BY amopstrategy",
10228 opcinfo->dobj.catId.oid);
10231 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10233 ntups = PQntuples(res);
10235 i_amopstrategy = PQfnumber(res, "amopstrategy");
10236 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10237 i_amopopr = PQfnumber(res, "amopopr");
10238 i_sortfamily = PQfnumber(res, "sortfamily");
10239 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10241 for (i = 0; i < ntups; i++)
10243 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10244 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10245 amopopr = PQgetvalue(res, i, i_amopopr);
10246 sortfamily = PQgetvalue(res, i, i_sortfamily);
10247 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10250 appendPQExpBuffer(q, " ,\n ");
10252 appendPQExpBuffer(q, "OPERATOR %s %s",
10253 amopstrategy, amopopr);
10255 if (strlen(sortfamily) > 0)
10257 appendPQExpBuffer(q, " FOR ORDER BY ");
10258 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10259 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10260 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10263 if (strcmp(amopreqcheck, "t") == 0)
10264 appendPQExpBuffer(q, " RECHECK");
10272 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10274 * Print only those opfamily members that are tied to the opclass by
10275 * pg_depend entries.
10277 * We print the amproclefttype/amprocrighttype even though in most cases
10278 * the backend could deduce the right values, because of the corner case
10279 * of a btree sort support function for a cross-type comparison. That's
10280 * only allowed in 9.2 and later, but for simplicity print them in all
10281 * versions that have the columns.
10283 resetPQExpBuffer(query);
10285 if (fout->remoteVersion >= 80300)
10287 appendPQExpBuffer(query, "SELECT amprocnum, "
10288 "amproc::pg_catalog.regprocedure, "
10289 "amproclefttype::pg_catalog.regtype, "
10290 "amprocrighttype::pg_catalog.regtype "
10291 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10292 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10293 "AND refobjid = '%u'::pg_catalog.oid "
10294 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10295 "AND objid = ap.oid "
10296 "ORDER BY amprocnum",
10297 opcinfo->dobj.catId.oid);
10301 appendPQExpBuffer(query, "SELECT amprocnum, "
10302 "amproc::pg_catalog.regprocedure, "
10303 "'' AS amproclefttype, "
10304 "'' AS amprocrighttype "
10305 "FROM pg_catalog.pg_amproc "
10306 "WHERE amopclaid = '%u'::pg_catalog.oid "
10307 "ORDER BY amprocnum",
10308 opcinfo->dobj.catId.oid);
10311 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10313 ntups = PQntuples(res);
10315 i_amprocnum = PQfnumber(res, "amprocnum");
10316 i_amproc = PQfnumber(res, "amproc");
10317 i_amproclefttype = PQfnumber(res, "amproclefttype");
10318 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10320 for (i = 0; i < ntups; i++)
10322 amprocnum = PQgetvalue(res, i, i_amprocnum);
10323 amproc = PQgetvalue(res, i, i_amproc);
10324 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10325 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10328 appendPQExpBuffer(q, " ,\n ");
10330 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10332 if (*amproclefttype && *amprocrighttype)
10333 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10335 appendPQExpBuffer(q, " %s", amproc);
10342 appendPQExpBuffer(q, ";\n");
10344 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10345 fmtId(opcinfo->dobj.name));
10346 appendPQExpBuffer(labelq, " USING %s",
10349 if (binary_upgrade)
10350 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10352 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10353 opcinfo->dobj.name,
10354 opcinfo->dobj.namespace->dobj.name,
10357 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10358 q->data, delq->data, NULL,
10359 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10362 /* Dump Operator Class Comments */
10363 dumpComment(fout, labelq->data,
10364 NULL, opcinfo->rolname,
10365 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10368 destroyPQExpBuffer(query);
10369 destroyPQExpBuffer(q);
10370 destroyPQExpBuffer(delq);
10371 destroyPQExpBuffer(labelq);
10376 * write out a single operator family definition
10378 * Note: this also dumps any "loose" operator members that aren't bound to a
10379 * specific opclass within the opfamily.
10382 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10387 PQExpBuffer labelq;
10390 PGresult *res_procs;
10393 int i_amopstrategy;
10394 int i_amopreqcheck;
10397 int i_sortfamilynsp;
10400 int i_amproclefttype;
10401 int i_amprocrighttype;
10403 char *amopstrategy;
10404 char *amopreqcheck;
10407 char *sortfamilynsp;
10410 char *amproclefttype;
10411 char *amprocrighttype;
10415 /* Skip if not to be dumped */
10416 if (!opfinfo->dobj.dump || dataOnly)
10420 * We want to dump the opfamily only if (1) it contains "loose" operators
10421 * or functions, or (2) it contains an opclass with a different name or
10422 * owner. Otherwise it's sufficient to let it be created during creation
10423 * of the contained opclass, and not dumping it improves portability of
10424 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10428 query = createPQExpBuffer();
10429 q = createPQExpBuffer();
10430 delq = createPQExpBuffer();
10431 labelq = createPQExpBuffer();
10433 /* Make sure we are in proper schema so regoperator works correctly */
10434 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10437 * Fetch only those opfamily members that are tied directly to the
10438 * opfamily by pg_depend entries.
10440 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10441 * older server's opclass in which it is used. This is to avoid
10442 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10443 * older server and then reload into that old version. This can go away
10444 * once 8.3 is so old as to not be of interest to anyone.
10446 if (fout->remoteVersion >= 90100)
10448 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10449 "amopopr::pg_catalog.regoperator, "
10450 "opfname AS sortfamily, "
10451 "nspname AS sortfamilynsp "
10452 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10453 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10454 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10455 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10456 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10457 "AND refobjid = '%u'::pg_catalog.oid "
10458 "AND amopfamily = '%u'::pg_catalog.oid "
10459 "ORDER BY amopstrategy",
10460 opfinfo->dobj.catId.oid,
10461 opfinfo->dobj.catId.oid);
10463 else if (fout->remoteVersion >= 80400)
10465 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10466 "amopopr::pg_catalog.regoperator, "
10467 "NULL AS sortfamily, "
10468 "NULL AS sortfamilynsp "
10469 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10470 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10471 "AND refobjid = '%u'::pg_catalog.oid "
10472 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10473 "AND objid = ao.oid "
10474 "ORDER BY amopstrategy",
10475 opfinfo->dobj.catId.oid);
10479 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10480 "amopopr::pg_catalog.regoperator, "
10481 "NULL AS sortfamily, "
10482 "NULL AS sortfamilynsp "
10483 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10484 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10485 "AND refobjid = '%u'::pg_catalog.oid "
10486 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10487 "AND objid = ao.oid "
10488 "ORDER BY amopstrategy",
10489 opfinfo->dobj.catId.oid);
10492 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10494 resetPQExpBuffer(query);
10496 appendPQExpBuffer(query, "SELECT amprocnum, "
10497 "amproc::pg_catalog.regprocedure, "
10498 "amproclefttype::pg_catalog.regtype, "
10499 "amprocrighttype::pg_catalog.regtype "
10500 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10501 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10502 "AND refobjid = '%u'::pg_catalog.oid "
10503 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10504 "AND objid = ap.oid "
10505 "ORDER BY amprocnum",
10506 opfinfo->dobj.catId.oid);
10508 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10510 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10512 /* No loose members, so check contained opclasses */
10513 resetPQExpBuffer(query);
10515 appendPQExpBuffer(query, "SELECT 1 "
10516 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10517 "WHERE f.oid = '%u'::pg_catalog.oid "
10518 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10519 "AND refobjid = f.oid "
10520 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10521 "AND objid = c.oid "
10522 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10524 opfinfo->dobj.catId.oid);
10526 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10528 if (PQntuples(res) == 0)
10530 /* no need to dump it, so bail out */
10533 PQclear(res_procs);
10534 destroyPQExpBuffer(query);
10535 destroyPQExpBuffer(q);
10536 destroyPQExpBuffer(delq);
10537 destroyPQExpBuffer(labelq);
10544 /* Get additional fields from the pg_opfamily row */
10545 resetPQExpBuffer(query);
10547 appendPQExpBuffer(query, "SELECT "
10548 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10549 "FROM pg_catalog.pg_opfamily "
10550 "WHERE oid = '%u'::pg_catalog.oid",
10551 opfinfo->dobj.catId.oid);
10553 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10555 /* Expecting a single result only */
10556 ntups = PQntuples(res);
10559 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10560 "query returned %d rows instead of one: %s\n",
10562 ntups, query->data);
10566 i_amname = PQfnumber(res, "amname");
10568 /* amname will still be needed after we PQclear res */
10569 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10572 * DROP must be fully qualified in case same name appears in pg_catalog
10574 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10575 fmtId(opfinfo->dobj.namespace->dobj.name));
10576 appendPQExpBuffer(delq, ".%s",
10577 fmtId(opfinfo->dobj.name));
10578 appendPQExpBuffer(delq, " USING %s;\n",
10581 /* Build the fixed portion of the CREATE command */
10582 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10583 fmtId(opfinfo->dobj.name));
10584 appendPQExpBuffer(q, " USING %s;\n",
10589 /* Do we need an ALTER to add loose members? */
10590 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10592 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10593 fmtId(opfinfo->dobj.name));
10594 appendPQExpBuffer(q, " USING %s ADD\n ",
10600 * Now fetch and print the OPERATOR entries (pg_amop rows).
10602 ntups = PQntuples(res_ops);
10604 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10605 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10606 i_amopopr = PQfnumber(res_ops, "amopopr");
10607 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10608 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10610 for (i = 0; i < ntups; i++)
10612 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10613 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10614 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10615 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10616 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10619 appendPQExpBuffer(q, " ,\n ");
10621 appendPQExpBuffer(q, "OPERATOR %s %s",
10622 amopstrategy, amopopr);
10624 if (strlen(sortfamily) > 0)
10626 appendPQExpBuffer(q, " FOR ORDER BY ");
10627 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10628 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10629 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10632 if (strcmp(amopreqcheck, "t") == 0)
10633 appendPQExpBuffer(q, " RECHECK");
10639 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10641 ntups = PQntuples(res_procs);
10643 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10644 i_amproc = PQfnumber(res_procs, "amproc");
10645 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10646 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10648 for (i = 0; i < ntups; i++)
10650 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10651 amproc = PQgetvalue(res_procs, i, i_amproc);
10652 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10653 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10656 appendPQExpBuffer(q, " ,\n ");
10658 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10659 amprocnum, amproclefttype, amprocrighttype,
10665 appendPQExpBuffer(q, ";\n");
10668 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10669 fmtId(opfinfo->dobj.name));
10670 appendPQExpBuffer(labelq, " USING %s",
10673 if (binary_upgrade)
10674 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10676 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10677 opfinfo->dobj.name,
10678 opfinfo->dobj.namespace->dobj.name,
10681 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10682 q->data, delq->data, NULL,
10683 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10686 /* Dump Operator Family Comments */
10687 dumpComment(fout, labelq->data,
10688 NULL, opfinfo->rolname,
10689 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10693 PQclear(res_procs);
10694 destroyPQExpBuffer(query);
10695 destroyPQExpBuffer(q);
10696 destroyPQExpBuffer(delq);
10697 destroyPQExpBuffer(labelq);
10702 * write out a single collation definition
10705 dumpCollation(Archive *fout, CollInfo *collinfo)
10710 PQExpBuffer labelq;
10715 const char *collcollate;
10716 const char *collctype;
10718 /* Skip if not to be dumped */
10719 if (!collinfo->dobj.dump || dataOnly)
10722 query = createPQExpBuffer();
10723 q = createPQExpBuffer();
10724 delq = createPQExpBuffer();
10725 labelq = createPQExpBuffer();
10727 /* Make sure we are in proper schema */
10728 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10730 /* Get conversion-specific details */
10731 appendPQExpBuffer(query, "SELECT "
10734 "FROM pg_catalog.pg_collation c "
10735 "WHERE c.oid = '%u'::pg_catalog.oid",
10736 collinfo->dobj.catId.oid);
10738 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10740 /* Expecting a single result only */
10741 ntups = PQntuples(res);
10744 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10745 "query returned %d rows instead of one: %s\n",
10747 ntups, query->data);
10751 i_collcollate = PQfnumber(res, "collcollate");
10752 i_collctype = PQfnumber(res, "collctype");
10754 collcollate = PQgetvalue(res, 0, i_collcollate);
10755 collctype = PQgetvalue(res, 0, i_collctype);
10758 * DROP must be fully qualified in case same name appears in pg_catalog
10760 appendPQExpBuffer(delq, "DROP COLLATION %s",
10761 fmtId(collinfo->dobj.namespace->dobj.name));
10762 appendPQExpBuffer(delq, ".%s;\n",
10763 fmtId(collinfo->dobj.name));
10765 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10766 fmtId(collinfo->dobj.name));
10767 appendStringLiteralAH(q, collcollate, fout);
10768 appendPQExpBuffer(q, ", lc_ctype = ");
10769 appendStringLiteralAH(q, collctype, fout);
10770 appendPQExpBuffer(q, ");\n");
10772 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10774 if (binary_upgrade)
10775 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10777 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10778 collinfo->dobj.name,
10779 collinfo->dobj.namespace->dobj.name,
10782 false, "COLLATION", SECTION_PRE_DATA,
10783 q->data, delq->data, NULL,
10784 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10787 /* Dump Collation Comments */
10788 dumpComment(fout, labelq->data,
10789 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10790 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10794 destroyPQExpBuffer(query);
10795 destroyPQExpBuffer(q);
10796 destroyPQExpBuffer(delq);
10797 destroyPQExpBuffer(labelq);
10802 * write out a single conversion definition
10805 dumpConversion(Archive *fout, ConvInfo *convinfo)
10810 PQExpBuffer labelq;
10813 int i_conforencoding;
10814 int i_contoencoding;
10817 const char *conforencoding;
10818 const char *contoencoding;
10819 const char *conproc;
10822 /* Skip if not to be dumped */
10823 if (!convinfo->dobj.dump || dataOnly)
10826 query = createPQExpBuffer();
10827 q = createPQExpBuffer();
10828 delq = createPQExpBuffer();
10829 labelq = createPQExpBuffer();
10831 /* Make sure we are in proper schema */
10832 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10834 /* Get conversion-specific details */
10835 appendPQExpBuffer(query, "SELECT "
10836 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10837 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10838 "conproc, condefault "
10839 "FROM pg_catalog.pg_conversion c "
10840 "WHERE c.oid = '%u'::pg_catalog.oid",
10841 convinfo->dobj.catId.oid);
10843 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10845 /* Expecting a single result only */
10846 ntups = PQntuples(res);
10849 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10850 "query returned %d rows instead of one: %s\n",
10852 ntups, query->data);
10856 i_conforencoding = PQfnumber(res, "conforencoding");
10857 i_contoencoding = PQfnumber(res, "contoencoding");
10858 i_conproc = PQfnumber(res, "conproc");
10859 i_condefault = PQfnumber(res, "condefault");
10861 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10862 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10863 conproc = PQgetvalue(res, 0, i_conproc);
10864 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10867 * DROP must be fully qualified in case same name appears in pg_catalog
10869 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10870 fmtId(convinfo->dobj.namespace->dobj.name));
10871 appendPQExpBuffer(delq, ".%s;\n",
10872 fmtId(convinfo->dobj.name));
10874 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10875 (condefault) ? "DEFAULT " : "",
10876 fmtId(convinfo->dobj.name));
10877 appendStringLiteralAH(q, conforencoding, fout);
10878 appendPQExpBuffer(q, " TO ");
10879 appendStringLiteralAH(q, contoencoding, fout);
10880 /* regproc is automatically quoted in 7.3 and above */
10881 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10883 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10885 if (binary_upgrade)
10886 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10888 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10889 convinfo->dobj.name,
10890 convinfo->dobj.namespace->dobj.name,
10893 false, "CONVERSION", SECTION_PRE_DATA,
10894 q->data, delq->data, NULL,
10895 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10898 /* Dump Conversion Comments */
10899 dumpComment(fout, labelq->data,
10900 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10901 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10905 destroyPQExpBuffer(query);
10906 destroyPQExpBuffer(q);
10907 destroyPQExpBuffer(delq);
10908 destroyPQExpBuffer(labelq);
10912 * format_aggregate_signature: generate aggregate name and argument list
10914 * The argument type names are qualified if needed. The aggregate name
10915 * is never qualified.
10918 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10920 PQExpBufferData buf;
10923 initPQExpBuffer(&buf);
10925 appendPQExpBuffer(&buf, "%s",
10926 fmtId(agginfo->aggfn.dobj.name));
10928 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10930 if (agginfo->aggfn.nargs == 0)
10931 appendPQExpBuffer(&buf, "(*)");
10934 appendPQExpBuffer(&buf, "(");
10935 for (j = 0; j < agginfo->aggfn.nargs; j++)
10939 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
10942 appendPQExpBuffer(&buf, "%s%s",
10943 (j > 0) ? ", " : "",
10947 appendPQExpBuffer(&buf, ")");
10954 * write out a single aggregate definition
10957 dumpAgg(Archive *fout, AggInfo *agginfo)
10962 PQExpBuffer labelq;
10963 PQExpBuffer details;
10971 int i_aggtranstype;
10974 const char *aggtransfn;
10975 const char *aggfinalfn;
10976 const char *aggsortop;
10977 const char *aggtranstype;
10978 const char *agginitval;
10981 /* Skip if not to be dumped */
10982 if (!agginfo->aggfn.dobj.dump || dataOnly)
10985 query = createPQExpBuffer();
10986 q = createPQExpBuffer();
10987 delq = createPQExpBuffer();
10988 labelq = createPQExpBuffer();
10989 details = createPQExpBuffer();
10991 /* Make sure we are in proper schema */
10992 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
10994 /* Get aggregate-specific details */
10995 if (fout->remoteVersion >= 80100)
10997 appendPQExpBuffer(query, "SELECT aggtransfn, "
10998 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10999 "aggsortop::pg_catalog.regoperator, "
11001 "'t'::boolean AS convertok "
11002 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11003 "WHERE a.aggfnoid = p.oid "
11004 "AND p.oid = '%u'::pg_catalog.oid",
11005 agginfo->aggfn.dobj.catId.oid);
11007 else if (fout->remoteVersion >= 70300)
11009 appendPQExpBuffer(query, "SELECT aggtransfn, "
11010 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11013 "'t'::boolean AS convertok "
11014 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11015 "WHERE a.aggfnoid = p.oid "
11016 "AND p.oid = '%u'::pg_catalog.oid",
11017 agginfo->aggfn.dobj.catId.oid);
11019 else if (fout->remoteVersion >= 70100)
11021 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11022 "format_type(aggtranstype, NULL) AS aggtranstype, "
11025 "'t'::boolean AS convertok "
11026 "FROM pg_aggregate "
11027 "WHERE oid = '%u'::oid",
11028 agginfo->aggfn.dobj.catId.oid);
11032 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11034 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11036 "agginitval1 AS agginitval, "
11037 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11038 "FROM pg_aggregate "
11039 "WHERE oid = '%u'::oid",
11040 agginfo->aggfn.dobj.catId.oid);
11043 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11045 /* Expecting a single result only */
11046 ntups = PQntuples(res);
11049 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11050 "query returned %d rows instead of one: %s\n",
11052 ntups, query->data);
11056 i_aggtransfn = PQfnumber(res, "aggtransfn");
11057 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11058 i_aggsortop = PQfnumber(res, "aggsortop");
11059 i_aggtranstype = PQfnumber(res, "aggtranstype");
11060 i_agginitval = PQfnumber(res, "agginitval");
11061 i_convertok = PQfnumber(res, "convertok");
11063 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11064 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11065 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11066 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11067 agginitval = PQgetvalue(res, 0, i_agginitval);
11068 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11070 aggsig = format_aggregate_signature(agginfo, fout, true);
11071 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11075 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11080 if (fout->remoteVersion >= 70300)
11082 /* If using 7.3's regproc or regtype, data is already quoted */
11083 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11087 else if (fout->remoteVersion >= 70100)
11089 /* format_type quotes, regproc does not */
11090 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11096 /* need quotes all around */
11097 appendPQExpBuffer(details, " SFUNC = %s,\n",
11098 fmtId(aggtransfn));
11099 appendPQExpBuffer(details, " STYPE = %s",
11100 fmtId(aggtranstype));
11103 if (!PQgetisnull(res, 0, i_agginitval))
11105 appendPQExpBuffer(details, ",\n INITCOND = ");
11106 appendStringLiteralAH(details, agginitval, fout);
11109 if (strcmp(aggfinalfn, "-") != 0)
11111 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11115 aggsortop = convertOperatorReference(fout, aggsortop);
11118 appendPQExpBuffer(details, ",\n SORTOP = %s",
11123 * DROP must be fully qualified in case same name appears in pg_catalog
11125 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11126 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11129 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11130 aggsig, details->data);
11132 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11134 if (binary_upgrade)
11135 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11137 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11139 agginfo->aggfn.dobj.namespace->dobj.name,
11141 agginfo->aggfn.rolname,
11142 false, "AGGREGATE", SECTION_PRE_DATA,
11143 q->data, delq->data, NULL,
11144 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
11147 /* Dump Aggregate Comments */
11148 dumpComment(fout, labelq->data,
11149 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11150 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11151 dumpSecLabel(fout, labelq->data,
11152 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11153 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11156 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11157 * command look like a function's GRANT; in particular this affects the
11158 * syntax for zero-argument aggregates.
11163 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11164 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11166 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11168 aggsig, NULL, aggsig_tag,
11169 agginfo->aggfn.dobj.namespace->dobj.name,
11170 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11177 destroyPQExpBuffer(query);
11178 destroyPQExpBuffer(q);
11179 destroyPQExpBuffer(delq);
11180 destroyPQExpBuffer(labelq);
11181 destroyPQExpBuffer(details);
11186 * write out a single text search parser
11189 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11193 PQExpBuffer labelq;
11195 /* Skip if not to be dumped */
11196 if (!prsinfo->dobj.dump || dataOnly)
11199 q = createPQExpBuffer();
11200 delq = createPQExpBuffer();
11201 labelq = createPQExpBuffer();
11203 /* Make sure we are in proper schema */
11204 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11206 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11207 fmtId(prsinfo->dobj.name));
11209 appendPQExpBuffer(q, " START = %s,\n",
11210 convertTSFunction(fout, prsinfo->prsstart));
11211 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11212 convertTSFunction(fout, prsinfo->prstoken));
11213 appendPQExpBuffer(q, " END = %s,\n",
11214 convertTSFunction(fout, prsinfo->prsend));
11215 if (prsinfo->prsheadline != InvalidOid)
11216 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11217 convertTSFunction(fout, prsinfo->prsheadline));
11218 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11219 convertTSFunction(fout, prsinfo->prslextype));
11222 * DROP must be fully qualified in case same name appears in pg_catalog
11224 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11225 fmtId(prsinfo->dobj.namespace->dobj.name));
11226 appendPQExpBuffer(delq, ".%s;\n",
11227 fmtId(prsinfo->dobj.name));
11229 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11230 fmtId(prsinfo->dobj.name));
11232 if (binary_upgrade)
11233 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11235 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11236 prsinfo->dobj.name,
11237 prsinfo->dobj.namespace->dobj.name,
11240 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11241 q->data, delq->data, NULL,
11242 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11245 /* Dump Parser Comments */
11246 dumpComment(fout, labelq->data,
11248 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11250 destroyPQExpBuffer(q);
11251 destroyPQExpBuffer(delq);
11252 destroyPQExpBuffer(labelq);
11257 * write out a single text search dictionary
11260 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11264 PQExpBuffer labelq;
11271 /* Skip if not to be dumped */
11272 if (!dictinfo->dobj.dump || dataOnly)
11275 q = createPQExpBuffer();
11276 delq = createPQExpBuffer();
11277 labelq = createPQExpBuffer();
11278 query = createPQExpBuffer();
11280 /* Fetch name and namespace of the dictionary's template */
11281 selectSourceSchema(fout, "pg_catalog");
11282 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11283 "FROM pg_ts_template p, pg_namespace n "
11284 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11285 dictinfo->dicttemplate);
11286 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11287 ntups = PQntuples(res);
11290 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11291 "query returned %d rows instead of one: %s\n",
11293 ntups, query->data);
11296 nspname = PQgetvalue(res, 0, 0);
11297 tmplname = PQgetvalue(res, 0, 1);
11299 /* Make sure we are in proper schema */
11300 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11302 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11303 fmtId(dictinfo->dobj.name));
11305 appendPQExpBuffer(q, " TEMPLATE = ");
11306 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11307 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11308 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11312 /* the dictinitoption can be dumped straight into the command */
11313 if (dictinfo->dictinitoption)
11314 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11316 appendPQExpBuffer(q, " );\n");
11319 * DROP must be fully qualified in case same name appears in pg_catalog
11321 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11322 fmtId(dictinfo->dobj.namespace->dobj.name));
11323 appendPQExpBuffer(delq, ".%s;\n",
11324 fmtId(dictinfo->dobj.name));
11326 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11327 fmtId(dictinfo->dobj.name));
11329 if (binary_upgrade)
11330 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11332 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11333 dictinfo->dobj.name,
11334 dictinfo->dobj.namespace->dobj.name,
11337 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11338 q->data, delq->data, NULL,
11339 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11342 /* Dump Dictionary Comments */
11343 dumpComment(fout, labelq->data,
11344 NULL, dictinfo->rolname,
11345 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11347 destroyPQExpBuffer(q);
11348 destroyPQExpBuffer(delq);
11349 destroyPQExpBuffer(labelq);
11350 destroyPQExpBuffer(query);
11355 * write out a single text search template
11358 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11362 PQExpBuffer labelq;
11364 /* Skip if not to be dumped */
11365 if (!tmplinfo->dobj.dump || dataOnly)
11368 q = createPQExpBuffer();
11369 delq = createPQExpBuffer();
11370 labelq = createPQExpBuffer();
11372 /* Make sure we are in proper schema */
11373 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11375 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11376 fmtId(tmplinfo->dobj.name));
11378 if (tmplinfo->tmplinit != InvalidOid)
11379 appendPQExpBuffer(q, " INIT = %s,\n",
11380 convertTSFunction(fout, tmplinfo->tmplinit));
11381 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11382 convertTSFunction(fout, tmplinfo->tmpllexize));
11385 * DROP must be fully qualified in case same name appears in pg_catalog
11387 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11388 fmtId(tmplinfo->dobj.namespace->dobj.name));
11389 appendPQExpBuffer(delq, ".%s;\n",
11390 fmtId(tmplinfo->dobj.name));
11392 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11393 fmtId(tmplinfo->dobj.name));
11395 if (binary_upgrade)
11396 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11398 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11399 tmplinfo->dobj.name,
11400 tmplinfo->dobj.namespace->dobj.name,
11403 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11404 q->data, delq->data, NULL,
11405 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11408 /* Dump Template Comments */
11409 dumpComment(fout, labelq->data,
11411 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11413 destroyPQExpBuffer(q);
11414 destroyPQExpBuffer(delq);
11415 destroyPQExpBuffer(labelq);
11420 * write out a single text search configuration
11423 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11427 PQExpBuffer labelq;
11437 /* Skip if not to be dumped */
11438 if (!cfginfo->dobj.dump || dataOnly)
11441 q = createPQExpBuffer();
11442 delq = createPQExpBuffer();
11443 labelq = createPQExpBuffer();
11444 query = createPQExpBuffer();
11446 /* Fetch name and namespace of the config's parser */
11447 selectSourceSchema(fout, "pg_catalog");
11448 appendPQExpBuffer(query, "SELECT nspname, prsname "
11449 "FROM pg_ts_parser p, pg_namespace n "
11450 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11451 cfginfo->cfgparser);
11452 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11453 ntups = PQntuples(res);
11456 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11457 "query returned %d rows instead of one: %s\n",
11459 ntups, query->data);
11462 nspname = PQgetvalue(res, 0, 0);
11463 prsname = PQgetvalue(res, 0, 1);
11465 /* Make sure we are in proper schema */
11466 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11468 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11469 fmtId(cfginfo->dobj.name));
11471 appendPQExpBuffer(q, " PARSER = ");
11472 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11473 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11474 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11478 resetPQExpBuffer(query);
11479 appendPQExpBuffer(query,
11481 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11482 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11483 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11484 "FROM pg_catalog.pg_ts_config_map AS m \n"
11485 "WHERE m.mapcfg = '%u' \n"
11486 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11487 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11489 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11490 ntups = PQntuples(res);
11492 i_tokenname = PQfnumber(res, "tokenname");
11493 i_dictname = PQfnumber(res, "dictname");
11495 for (i = 0; i < ntups; i++)
11497 char *tokenname = PQgetvalue(res, i, i_tokenname);
11498 char *dictname = PQgetvalue(res, i, i_dictname);
11501 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11503 /* starting a new token type, so start a new command */
11505 appendPQExpBuffer(q, ";\n");
11506 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11507 fmtId(cfginfo->dobj.name));
11508 /* tokenname needs quoting, dictname does NOT */
11509 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11510 fmtId(tokenname), dictname);
11513 appendPQExpBuffer(q, ", %s", dictname);
11517 appendPQExpBuffer(q, ";\n");
11522 * DROP must be fully qualified in case same name appears in pg_catalog
11524 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11525 fmtId(cfginfo->dobj.namespace->dobj.name));
11526 appendPQExpBuffer(delq, ".%s;\n",
11527 fmtId(cfginfo->dobj.name));
11529 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11530 fmtId(cfginfo->dobj.name));
11532 if (binary_upgrade)
11533 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11535 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11536 cfginfo->dobj.name,
11537 cfginfo->dobj.namespace->dobj.name,
11540 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11541 q->data, delq->data, NULL,
11542 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11545 /* Dump Configuration Comments */
11546 dumpComment(fout, labelq->data,
11547 NULL, cfginfo->rolname,
11548 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11550 destroyPQExpBuffer(q);
11551 destroyPQExpBuffer(delq);
11552 destroyPQExpBuffer(labelq);
11553 destroyPQExpBuffer(query);
11557 * dumpForeignDataWrapper
11558 * write out a single foreign-data wrapper definition
11561 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11565 PQExpBuffer labelq;
11568 /* Skip if not to be dumped */
11569 if (!fdwinfo->dobj.dump || dataOnly)
11573 * FDWs that belong to an extension are dumped based on their "dump"
11574 * field. Otherwise omit them if we are only dumping some specific object.
11576 if (!fdwinfo->dobj.ext_member)
11577 if (!include_everything)
11580 q = createPQExpBuffer();
11581 delq = createPQExpBuffer();
11582 labelq = createPQExpBuffer();
11584 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11586 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11589 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11590 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11592 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11593 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11595 if (strlen(fdwinfo->fdwoptions) > 0)
11596 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11598 appendPQExpBuffer(q, ";\n");
11600 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11603 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11606 if (binary_upgrade)
11607 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11609 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11610 fdwinfo->dobj.name,
11614 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11615 q->data, delq->data, NULL,
11616 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11619 /* Handle the ACL */
11620 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11621 "FOREIGN DATA WRAPPER",
11622 qfdwname, NULL, fdwinfo->dobj.name,
11623 NULL, fdwinfo->rolname,
11626 /* Dump Foreign Data Wrapper Comments */
11627 dumpComment(fout, labelq->data,
11628 NULL, fdwinfo->rolname,
11629 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11633 destroyPQExpBuffer(q);
11634 destroyPQExpBuffer(delq);
11635 destroyPQExpBuffer(labelq);
11639 * dumpForeignServer
11640 * write out a foreign server definition
11643 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11647 PQExpBuffer labelq;
11654 /* Skip if not to be dumped */
11655 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11658 q = createPQExpBuffer();
11659 delq = createPQExpBuffer();
11660 labelq = createPQExpBuffer();
11661 query = createPQExpBuffer();
11663 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11665 /* look up the foreign-data wrapper */
11666 selectSourceSchema(fout, "pg_catalog");
11667 appendPQExpBuffer(query, "SELECT fdwname "
11668 "FROM pg_foreign_data_wrapper w "
11669 "WHERE w.oid = '%u'",
11671 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11672 ntups = PQntuples(res);
11675 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11676 "query returned %d rows instead of one: %s\n",
11678 ntups, query->data);
11681 fdwname = PQgetvalue(res, 0, 0);
11683 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11684 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11686 appendPQExpBuffer(q, " TYPE ");
11687 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11689 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11691 appendPQExpBuffer(q, " VERSION ");
11692 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11695 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11696 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11698 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11699 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11701 appendPQExpBuffer(q, ";\n");
11703 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11706 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11708 if (binary_upgrade)
11709 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11711 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11712 srvinfo->dobj.name,
11716 false, "SERVER", SECTION_PRE_DATA,
11717 q->data, delq->data, NULL,
11718 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11721 /* Handle the ACL */
11722 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11724 qsrvname, NULL, srvinfo->dobj.name,
11725 NULL, srvinfo->rolname,
11728 /* Dump user mappings */
11729 dumpUserMappings(fout,
11730 srvinfo->dobj.name, NULL,
11732 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11734 /* Dump Foreign Server Comments */
11735 dumpComment(fout, labelq->data,
11736 NULL, srvinfo->rolname,
11737 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11741 destroyPQExpBuffer(q);
11742 destroyPQExpBuffer(delq);
11743 destroyPQExpBuffer(labelq);
11749 * This routine is used to dump any user mappings associated with the
11750 * server handed to this routine. Should be called after ArchiveEntry()
11754 dumpUserMappings(Archive *fout,
11755 const char *servername, const char *namespace,
11757 CatalogId catalogId, DumpId dumpId)
11769 q = createPQExpBuffer();
11770 tag = createPQExpBuffer();
11771 delq = createPQExpBuffer();
11772 query = createPQExpBuffer();
11775 * We read from the publicly accessible view pg_user_mappings, so as not
11776 * to fail if run by a non-superuser. Note that the view will show
11777 * umoptions as null if the user hasn't got privileges for the associated
11778 * server; this means that pg_dump will dump such a mapping, but with no
11779 * OPTIONS clause. A possible alternative is to skip such mappings
11780 * altogether, but it's not clear that that's an improvement.
11782 selectSourceSchema(fout, "pg_catalog");
11784 appendPQExpBuffer(query,
11786 "array_to_string(ARRAY("
11787 "SELECT quote_ident(option_name) || ' ' || "
11788 "quote_literal(option_value) "
11789 "FROM pg_options_to_table(umoptions) "
11790 "ORDER BY option_name"
11791 "), E',\n ') AS umoptions "
11792 "FROM pg_user_mappings "
11793 "WHERE srvid = '%u' "
11794 "ORDER BY usename",
11797 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11799 ntups = PQntuples(res);
11800 i_usename = PQfnumber(res, "usename");
11801 i_umoptions = PQfnumber(res, "umoptions");
11803 for (i = 0; i < ntups; i++)
11808 usename = PQgetvalue(res, i, i_usename);
11809 umoptions = PQgetvalue(res, i, i_umoptions);
11811 resetPQExpBuffer(q);
11812 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11813 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11815 if (umoptions && strlen(umoptions) > 0)
11816 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11818 appendPQExpBuffer(q, ";\n");
11820 resetPQExpBuffer(delq);
11821 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11822 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11824 resetPQExpBuffer(tag);
11825 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11826 usename, servername);
11828 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11833 "USER MAPPING", SECTION_PRE_DATA,
11834 q->data, delq->data, NULL,
11841 destroyPQExpBuffer(query);
11842 destroyPQExpBuffer(delq);
11843 destroyPQExpBuffer(q);
11847 * Write out default privileges information
11850 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11856 /* Skip if not to be dumped */
11857 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11860 q = createPQExpBuffer();
11861 tag = createPQExpBuffer();
11863 switch (daclinfo->defaclobjtype)
11865 case DEFACLOBJ_RELATION:
11868 case DEFACLOBJ_SEQUENCE:
11869 type = "SEQUENCES";
11871 case DEFACLOBJ_FUNCTION:
11872 type = "FUNCTIONS";
11875 /* shouldn't get here */
11876 write_msg(NULL, "unknown object type (%d) in default privileges\n",
11877 (int) daclinfo->defaclobjtype);
11879 type = ""; /* keep compiler quiet */
11882 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11884 /* build the actual command(s) for this tuple */
11885 if (!buildDefaultACLCommands(type,
11886 daclinfo->dobj.namespace != NULL ?
11887 daclinfo->dobj.namespace->dobj.name : NULL,
11888 daclinfo->defaclacl,
11889 daclinfo->defaclrole,
11890 fout->remoteVersion,
11893 write_msg(NULL, "could not parse default ACL list (%s)\n",
11894 daclinfo->defaclacl);
11898 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11900 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11902 daclinfo->defaclrole,
11903 false, "DEFAULT ACL", SECTION_NONE,
11905 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11908 destroyPQExpBuffer(tag);
11909 destroyPQExpBuffer(q);
11913 * Write out grant/revoke information
11915 * 'objCatId' is the catalog ID of the underlying object.
11916 * 'objDumpId' is the dump ID of the underlying object.
11917 * 'type' must be one of
11918 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11919 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11920 * 'name' is the formatted name of the object. Must be quoted etc. already.
11921 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11922 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11923 * 'nspname' is the namespace the object is in (NULL if none).
11924 * 'owner' is the owner, NULL if there is no owner (for languages).
11925 * 'acls' is the string read out of the fooacl system catalog field;
11926 * it will be parsed here.
11930 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11931 const char *type, const char *name, const char *subname,
11932 const char *tag, const char *nspname, const char *owner,
11937 /* Do nothing if ACL dump is not enabled */
11941 /* --data-only skips ACLs *except* BLOB ACLs */
11942 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11945 sql = createPQExpBuffer();
11947 if (!buildACLCommands(name, subname, type, acls, owner,
11948 "", fout->remoteVersion, sql))
11950 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11956 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11959 owner ? owner : "",
11960 false, "ACL", SECTION_NONE,
11961 sql->data, "", NULL,
11965 destroyPQExpBuffer(sql);
11971 * This routine is used to dump any security labels associated with the
11972 * object handed to this routine. The routine takes a constant character
11973 * string for the target part of the security-label command, plus
11974 * the namespace and owner of the object (for labeling the ArchiveEntry),
11975 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11976 * plus the dump ID for the object (for setting a dependency).
11977 * If a matching pg_seclabel entry is found, it is dumped.
11979 * Note: although this routine takes a dumpId for dependency purposes,
11980 * that purpose is just to mark the dependency in the emitted dump file
11981 * for possible future use by pg_restore. We do NOT use it for determining
11982 * ordering of the label in the dump file, because this routine is called
11983 * after dependency sorting occurs. This routine should be called just after
11984 * calling ArchiveEntry() for the specified object.
11987 dumpSecLabel(Archive *fout, const char *target,
11988 const char *namespace, const char *owner,
11989 CatalogId catalogId, int subid, DumpId dumpId)
11991 SecLabelItem *labels;
11996 /* do nothing, if --no-security-labels is supplied */
11997 if (no_security_labels)
12000 /* Comments are schema not data ... except blob comments are data */
12001 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12012 /* Search for security labels associated with catalogId, using table */
12013 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12015 query = createPQExpBuffer();
12017 for (i = 0; i < nlabels; i++)
12020 * Ignore label entries for which the subid doesn't match.
12022 if (labels[i].objsubid != subid)
12025 appendPQExpBuffer(query,
12026 "SECURITY LABEL FOR %s ON %s IS ",
12027 fmtId(labels[i].provider), target);
12028 appendStringLiteralAH(query, labels[i].label, fout);
12029 appendPQExpBuffer(query, ";\n");
12032 if (query->len > 0)
12034 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12035 target, namespace, NULL, owner,
12036 false, "SECURITY LABEL", SECTION_NONE,
12037 query->data, "", NULL,
12041 destroyPQExpBuffer(query);
12045 * dumpTableSecLabel
12047 * As above, but dump security label for both the specified table (or view)
12051 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12053 SecLabelItem *labels;
12057 PQExpBuffer target;
12059 /* do nothing, if --no-security-labels is supplied */
12060 if (no_security_labels)
12063 /* SecLabel are SCHEMA not data */
12067 /* Search for comments associated with relation, using table */
12068 nlabels = findSecLabels(fout,
12069 tbinfo->dobj.catId.tableoid,
12070 tbinfo->dobj.catId.oid,
12073 /* If security labels exist, build SECURITY LABEL statements */
12077 query = createPQExpBuffer();
12078 target = createPQExpBuffer();
12080 for (i = 0; i < nlabels; i++)
12082 const char *colname;
12083 const char *provider = labels[i].provider;
12084 const char *label = labels[i].label;
12085 int objsubid = labels[i].objsubid;
12087 resetPQExpBuffer(target);
12090 appendPQExpBuffer(target, "%s %s", reltypename,
12091 fmtId(tbinfo->dobj.name));
12095 colname = getAttrName(objsubid, tbinfo);
12096 /* first fmtId result must be consumed before calling it again */
12097 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12098 appendPQExpBuffer(target, ".%s", fmtId(colname));
12100 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12101 fmtId(provider), target->data);
12102 appendStringLiteralAH(query, label, fout);
12103 appendPQExpBuffer(query, ";\n");
12105 if (query->len > 0)
12107 resetPQExpBuffer(target);
12108 appendPQExpBuffer(target, "%s %s", reltypename,
12109 fmtId(tbinfo->dobj.name));
12110 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12112 tbinfo->dobj.namespace->dobj.name,
12113 NULL, tbinfo->rolname,
12114 false, "SECURITY LABEL", SECTION_NONE,
12115 query->data, "", NULL,
12116 &(tbinfo->dobj.dumpId), 1,
12119 destroyPQExpBuffer(query);
12120 destroyPQExpBuffer(target);
12126 * Find the security label(s), if any, associated with the given object.
12127 * All the objsubid values associated with the given classoid/objoid are
12128 * found with one search.
12131 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12133 /* static storage for table of security labels */
12134 static SecLabelItem *labels = NULL;
12135 static int nlabels = -1;
12137 SecLabelItem *middle = NULL;
12139 SecLabelItem *high;
12142 /* Get security labels if we didn't already */
12144 nlabels = collectSecLabels(fout, &labels);
12146 if (nlabels <= 0) /* no labels, so no match is possible */
12153 * Do binary search to find some item matching the object.
12156 high = &labels[nlabels - 1];
12157 while (low <= high)
12159 middle = low + (high - low) / 2;
12161 if (classoid < middle->classoid)
12163 else if (classoid > middle->classoid)
12165 else if (objoid < middle->objoid)
12167 else if (objoid > middle->objoid)
12170 break; /* found a match */
12173 if (low > high) /* no matches */
12180 * Now determine how many items match the object. The search loop
12181 * invariant still holds: only items between low and high inclusive could
12185 while (middle > low)
12187 if (classoid != middle[-1].classoid ||
12188 objoid != middle[-1].objoid)
12197 while (middle <= high)
12199 if (classoid != middle->classoid ||
12200 objoid != middle->objoid)
12212 * Construct a table of all security labels available for database objects.
12213 * It's much faster to pull them all at once.
12215 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12218 collectSecLabels(Archive *fout, SecLabelItem **items)
12229 SecLabelItem *labels;
12231 query = createPQExpBuffer();
12233 appendPQExpBuffer(query,
12234 "SELECT label, provider, classoid, objoid, objsubid "
12235 "FROM pg_catalog.pg_seclabel "
12236 "ORDER BY classoid, objoid, objsubid");
12238 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12240 /* Construct lookup table containing OIDs in numeric form */
12241 i_label = PQfnumber(res, "label");
12242 i_provider = PQfnumber(res, "provider");
12243 i_classoid = PQfnumber(res, "classoid");
12244 i_objoid = PQfnumber(res, "objoid");
12245 i_objsubid = PQfnumber(res, "objsubid");
12247 ntups = PQntuples(res);
12249 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12251 for (i = 0; i < ntups; i++)
12253 labels[i].label = PQgetvalue(res, i, i_label);
12254 labels[i].provider = PQgetvalue(res, i, i_provider);
12255 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12256 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12257 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12260 /* Do NOT free the PGresult since we are keeping pointers into it */
12261 destroyPQExpBuffer(query);
12269 * write out to fout the declarations (not data) of a user-defined table
12272 dumpTable(Archive *fout, TableInfo *tbinfo)
12274 if (tbinfo->dobj.dump)
12278 if (tbinfo->relkind == RELKIND_SEQUENCE)
12279 dumpSequence(fout, tbinfo);
12280 else if (!dataOnly)
12281 dumpTableSchema(fout, tbinfo);
12283 /* Handle the ACL here */
12284 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12285 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12286 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12288 namecopy, NULL, tbinfo->dobj.name,
12289 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12293 * Handle column ACLs, if any. Note: we pull these with a separate
12294 * query rather than trying to fetch them during getTableAttrs, so
12295 * that we won't miss ACLs on system columns.
12297 if (fout->remoteVersion >= 80400)
12299 PQExpBuffer query = createPQExpBuffer();
12303 appendPQExpBuffer(query,
12304 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12305 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12307 tbinfo->dobj.catId.oid);
12308 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12310 for (i = 0; i < PQntuples(res); i++)
12312 char *attname = PQgetvalue(res, i, 0);
12313 char *attacl = PQgetvalue(res, i, 1);
12317 attnamecopy = pg_strdup(fmtId(attname));
12318 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12319 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12320 /* Column's GRANT type is always TABLE */
12321 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12322 namecopy, attnamecopy, acltag,
12323 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12329 destroyPQExpBuffer(query);
12338 * write the declaration (not data) of one user-defined table or view
12341 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12343 PQExpBuffer query = createPQExpBuffer();
12344 PQExpBuffer q = createPQExpBuffer();
12345 PQExpBuffer delq = createPQExpBuffer();
12346 PQExpBuffer labelq = createPQExpBuffer();
12349 TableInfo **parents;
12350 int actual_atts; /* number of attrs in this CREATE statment */
12351 const char *reltypename;
12358 /* Make sure we are in proper schema */
12359 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12361 if (binary_upgrade)
12362 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12363 tbinfo->dobj.catId.oid);
12365 /* Is it a table or a view? */
12366 if (tbinfo->relkind == RELKIND_VIEW)
12370 reltypename = "VIEW";
12372 /* Fetch the view definition */
12373 if (fout->remoteVersion >= 70300)
12375 /* Beginning in 7.3, viewname is not unique; rely on OID */
12376 appendPQExpBuffer(query,
12377 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12378 tbinfo->dobj.catId.oid);
12382 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12383 "FROM pg_views WHERE viewname = ");
12384 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12385 appendPQExpBuffer(query, ";");
12388 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12390 if (PQntuples(res) != 1)
12392 if (PQntuples(res) < 1)
12393 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12394 tbinfo->dobj.name);
12396 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12397 tbinfo->dobj.name);
12401 viewdef = PQgetvalue(res, 0, 0);
12403 if (strlen(viewdef) == 0)
12405 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12406 tbinfo->dobj.name);
12411 * DROP must be fully qualified in case same name appears in
12414 appendPQExpBuffer(delq, "DROP VIEW %s.",
12415 fmtId(tbinfo->dobj.namespace->dobj.name));
12416 appendPQExpBuffer(delq, "%s;\n",
12417 fmtId(tbinfo->dobj.name));
12419 if (binary_upgrade)
12420 binary_upgrade_set_pg_class_oids(fout, q,
12421 tbinfo->dobj.catId.oid, false);
12423 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12424 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12425 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12426 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12428 appendPQExpBuffer(labelq, "VIEW %s",
12429 fmtId(tbinfo->dobj.name));
12435 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12440 reltypename = "FOREIGN TABLE";
12442 /* retrieve name of foreign server and generic options */
12443 appendPQExpBuffer(query,
12444 "SELECT fs.srvname, "
12445 "pg_catalog.array_to_string(ARRAY("
12446 "SELECT pg_catalog.quote_ident(option_name) || "
12447 "' ' || pg_catalog.quote_literal(option_value) "
12448 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12449 "ORDER BY option_name"
12450 "), E',\n ') AS ftoptions "
12451 "FROM pg_catalog.pg_foreign_table ft "
12452 "JOIN pg_catalog.pg_foreign_server fs "
12453 "ON (fs.oid = ft.ftserver) "
12454 "WHERE ft.ftrelid = '%u'",
12455 tbinfo->dobj.catId.oid);
12456 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12457 if (PQntuples(res) != 1)
12459 write_msg(NULL, ngettext("query returned %d foreign server entry for foreign table \"%s\"\n",
12460 "query returned %d foreign server entries for foreign table \"%s\"\n",
12462 PQntuples(res), tbinfo->dobj.name);
12465 i_srvname = PQfnumber(res, "srvname");
12466 i_ftoptions = PQfnumber(res, "ftoptions");
12467 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12468 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12473 reltypename = "TABLE";
12477 numParents = tbinfo->numParents;
12478 parents = tbinfo->parents;
12481 * DROP must be fully qualified in case same name appears in
12484 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12485 fmtId(tbinfo->dobj.namespace->dobj.name));
12486 appendPQExpBuffer(delq, "%s;\n",
12487 fmtId(tbinfo->dobj.name));
12489 appendPQExpBuffer(labelq, "%s %s", reltypename,
12490 fmtId(tbinfo->dobj.name));
12492 if (binary_upgrade)
12493 binary_upgrade_set_pg_class_oids(fout, q,
12494 tbinfo->dobj.catId.oid, false);
12496 appendPQExpBuffer(q, "CREATE %s%s %s",
12497 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12500 fmtId(tbinfo->dobj.name));
12503 * In case of a binary upgrade, we dump the table normally and attach
12504 * it to the type afterward.
12506 if (tbinfo->reloftype && !binary_upgrade)
12507 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12509 for (j = 0; j < tbinfo->numatts; j++)
12512 * Normally, dump if it's one of the table's own attrs, and not
12513 * dropped. But for binary upgrade, dump all the columns.
12515 if ((!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j]) ||
12519 * Default value --- suppress if inherited (except in
12520 * binary-upgrade case, where we're not doing normal
12521 * inheritance) or if it's to be printed separately.
12523 bool has_default = (tbinfo->attrdefs[j] != NULL
12524 && (!tbinfo->inhAttrDef[j] || binary_upgrade)
12525 && !tbinfo->attrdefs[j]->separate);
12528 * Not Null constraint --- suppress if inherited, except in
12529 * binary-upgrade case.
12531 bool has_notnull = (tbinfo->notnull[j]
12532 && (!tbinfo->inhNotNull[j] || binary_upgrade));
12534 if (tbinfo->reloftype && !has_default && !has_notnull && !binary_upgrade)
12537 /* Format properly if not first attr */
12538 if (actual_atts == 0)
12539 appendPQExpBuffer(q, " (");
12541 appendPQExpBuffer(q, ",");
12542 appendPQExpBuffer(q, "\n ");
12545 /* Attribute name */
12546 appendPQExpBuffer(q, "%s ",
12547 fmtId(tbinfo->attnames[j]));
12549 if (tbinfo->attisdropped[j])
12552 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12553 * so we will not have gotten a valid type name; insert
12554 * INTEGER as a stopgap. We'll clean things up later.
12556 appendPQExpBuffer(q, "INTEGER /* dummy */");
12557 /* Skip all the rest, too */
12561 /* Attribute type */
12562 if (tbinfo->reloftype && !binary_upgrade)
12564 appendPQExpBuffer(q, "WITH OPTIONS");
12566 else if (fout->remoteVersion >= 70100)
12568 appendPQExpBuffer(q, "%s",
12569 tbinfo->atttypnames[j]);
12573 /* If no format_type, fake it */
12574 appendPQExpBuffer(q, "%s",
12575 myFormatType(tbinfo->atttypnames[j],
12576 tbinfo->atttypmod[j]));
12579 /* Add collation if not default for the type */
12580 if (OidIsValid(tbinfo->attcollation[j]))
12584 coll = findCollationByOid(tbinfo->attcollation[j]);
12587 /* always schema-qualify, don't try to be smart */
12588 appendPQExpBuffer(q, " COLLATE %s.",
12589 fmtId(coll->dobj.namespace->dobj.name));
12590 appendPQExpBuffer(q, "%s",
12591 fmtId(coll->dobj.name));
12596 appendPQExpBuffer(q, " DEFAULT %s",
12597 tbinfo->attrdefs[j]->adef_expr);
12600 appendPQExpBuffer(q, " NOT NULL");
12605 * Add non-inherited CHECK constraints, if any.
12607 for (j = 0; j < tbinfo->ncheck; j++)
12609 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12611 if (constr->separate || !constr->conislocal)
12614 if (actual_atts == 0)
12615 appendPQExpBuffer(q, " (\n ");
12617 appendPQExpBuffer(q, ",\n ");
12619 appendPQExpBuffer(q, "CONSTRAINT %s ",
12620 fmtId(constr->dobj.name));
12621 appendPQExpBuffer(q, "%s", constr->condef);
12627 appendPQExpBuffer(q, "\n)");
12628 else if (!(tbinfo->reloftype && !binary_upgrade))
12631 * We must have a parenthesized attribute list, even though empty,
12632 * when not using the OF TYPE syntax.
12634 appendPQExpBuffer(q, " (\n)");
12637 if (numParents > 0 && !binary_upgrade)
12639 appendPQExpBuffer(q, "\nINHERITS (");
12640 for (k = 0; k < numParents; k++)
12642 TableInfo *parentRel = parents[k];
12645 appendPQExpBuffer(q, ", ");
12646 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12647 appendPQExpBuffer(q, "%s.",
12648 fmtId(parentRel->dobj.namespace->dobj.name));
12649 appendPQExpBuffer(q, "%s",
12650 fmtId(parentRel->dobj.name));
12652 appendPQExpBuffer(q, ")");
12655 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12656 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12658 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12659 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12661 bool addcomma = false;
12663 appendPQExpBuffer(q, "\nWITH (");
12664 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12667 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12669 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12671 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12672 tbinfo->toast_reloptions);
12674 appendPQExpBuffer(q, ")");
12677 /* Dump generic options if any */
12678 if (ftoptions && ftoptions[0])
12679 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12681 appendPQExpBuffer(q, ";\n");
12684 * To create binary-compatible heap files, we have to ensure the same
12685 * physical column order, including dropped columns, as in the
12686 * original. Therefore, we create dropped columns above and drop them
12687 * here, also updating their attlen/attalign values so that the
12688 * dropped column can be skipped properly. (We do not bother with
12689 * restoring the original attbyval setting.) Also, inheritance
12690 * relationships are set up by doing ALTER INHERIT rather than using
12691 * an INHERITS clause --- the latter would possibly mess up the column
12692 * order. That also means we have to take care about setting
12693 * attislocal correctly, plus fix up any inherited CHECK constraints.
12694 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12696 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12698 for (j = 0; j < tbinfo->numatts; j++)
12700 if (tbinfo->attisdropped[j])
12702 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12703 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12704 "SET attlen = %d, "
12705 "attalign = '%c', attbyval = false\n"
12706 "WHERE attname = ",
12708 tbinfo->attalign[j]);
12709 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12710 appendPQExpBuffer(q, "\n AND attrelid = ");
12711 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12712 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12714 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12715 fmtId(tbinfo->dobj.name));
12716 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12717 fmtId(tbinfo->attnames[j]));
12719 else if (!tbinfo->attislocal[j])
12721 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12722 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12723 "SET attislocal = false\n"
12724 "WHERE attname = ");
12725 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12726 appendPQExpBuffer(q, "\n AND attrelid = ");
12727 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12728 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12732 for (k = 0; k < tbinfo->ncheck; k++)
12734 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12736 if (constr->separate || constr->conislocal)
12739 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12740 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12741 fmtId(tbinfo->dobj.name));
12742 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12743 fmtId(constr->dobj.name));
12744 appendPQExpBuffer(q, "%s;\n", constr->condef);
12745 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12746 "SET conislocal = false\n"
12747 "WHERE contype = 'c' AND conname = ");
12748 appendStringLiteralAH(q, constr->dobj.name, fout);
12749 appendPQExpBuffer(q, "\n AND conrelid = ");
12750 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12751 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12754 if (numParents > 0)
12756 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12757 for (k = 0; k < numParents; k++)
12759 TableInfo *parentRel = parents[k];
12761 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12762 fmtId(tbinfo->dobj.name));
12763 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12764 appendPQExpBuffer(q, "%s.",
12765 fmtId(parentRel->dobj.namespace->dobj.name));
12766 appendPQExpBuffer(q, "%s;\n",
12767 fmtId(parentRel->dobj.name));
12771 if (tbinfo->reloftype)
12773 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12774 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12775 fmtId(tbinfo->dobj.name),
12776 tbinfo->reloftype);
12779 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12780 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12781 "SET relfrozenxid = '%u'\n"
12783 tbinfo->frozenxid);
12784 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12785 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12787 if (tbinfo->toast_oid)
12789 /* We preserve the toast oids, so we can use it during restore */
12790 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12791 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12792 "SET relfrozenxid = '%u'\n"
12793 "WHERE oid = '%u';\n",
12794 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12798 /* Loop dumping statistics and storage statements */
12799 for (j = 0; j < tbinfo->numatts; j++)
12802 * Dump per-column statistics information. We only issue an ALTER
12803 * TABLE statement if the attstattarget entry for this column is
12804 * non-negative (i.e. it's not the default value)
12806 if (tbinfo->attstattarget[j] >= 0 &&
12807 !tbinfo->attisdropped[j])
12809 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12810 fmtId(tbinfo->dobj.name));
12811 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12812 fmtId(tbinfo->attnames[j]));
12813 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12814 tbinfo->attstattarget[j]);
12818 * Dump per-column storage information. The statement is only
12819 * dumped if the storage has been changed from the type's default.
12821 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
12823 switch (tbinfo->attstorage[j])
12829 storage = "EXTERNAL";
12835 storage = "EXTENDED";
12842 * Only dump the statement if it's a storage type we recognize
12844 if (storage != NULL)
12846 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12847 fmtId(tbinfo->dobj.name));
12848 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12849 fmtId(tbinfo->attnames[j]));
12850 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12856 * Dump per-column attributes.
12858 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12860 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12861 fmtId(tbinfo->dobj.name));
12862 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12863 fmtId(tbinfo->attnames[j]));
12864 appendPQExpBuffer(q, "SET (%s);\n",
12865 tbinfo->attoptions[j]);
12869 * Dump per-column fdw options.
12871 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12872 tbinfo->attfdwoptions[j] &&
12873 tbinfo->attfdwoptions[j][0] != '\0')
12875 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12876 fmtId(tbinfo->dobj.name));
12877 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12878 fmtId(tbinfo->attnames[j]));
12879 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12880 tbinfo->attfdwoptions[j]);
12885 if (binary_upgrade)
12886 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12888 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12890 tbinfo->dobj.namespace->dobj.name,
12891 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12893 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12894 reltypename, SECTION_PRE_DATA,
12895 q->data, delq->data, NULL,
12896 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12900 /* Dump Table Comments */
12901 dumpTableComment(fout, tbinfo, reltypename);
12903 /* Dump Table Security Labels */
12904 dumpTableSecLabel(fout, tbinfo, reltypename);
12906 /* Dump comments on inlined table constraints */
12907 for (j = 0; j < tbinfo->ncheck; j++)
12909 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12911 if (constr->separate || !constr->conislocal)
12914 dumpTableConstraintComment(fout, constr);
12917 destroyPQExpBuffer(query);
12918 destroyPQExpBuffer(q);
12919 destroyPQExpBuffer(delq);
12920 destroyPQExpBuffer(labelq);
12924 * dumpAttrDef --- dump an attribute's default-value declaration
12927 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12929 TableInfo *tbinfo = adinfo->adtable;
12930 int adnum = adinfo->adnum;
12934 /* Only print it if "separate" mode is selected */
12935 if (!tbinfo->dobj.dump || !adinfo->separate || dataOnly)
12938 /* Don't print inherited defaults, either, except for binary upgrade */
12939 if (tbinfo->inhAttrDef[adnum - 1] && !binary_upgrade)
12942 q = createPQExpBuffer();
12943 delq = createPQExpBuffer();
12945 appendPQExpBuffer(q, "ALTER TABLE %s ",
12946 fmtId(tbinfo->dobj.name));
12947 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12948 fmtId(tbinfo->attnames[adnum - 1]),
12949 adinfo->adef_expr);
12952 * DROP must be fully qualified in case same name appears in pg_catalog
12954 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12955 fmtId(tbinfo->dobj.namespace->dobj.name));
12956 appendPQExpBuffer(delq, "%s ",
12957 fmtId(tbinfo->dobj.name));
12958 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12959 fmtId(tbinfo->attnames[adnum - 1]));
12961 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12962 tbinfo->attnames[adnum - 1],
12963 tbinfo->dobj.namespace->dobj.name,
12966 false, "DEFAULT", SECTION_PRE_DATA,
12967 q->data, delq->data, NULL,
12968 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12971 destroyPQExpBuffer(q);
12972 destroyPQExpBuffer(delq);
12976 * getAttrName: extract the correct name for an attribute
12978 * The array tblInfo->attnames[] only provides names of user attributes;
12979 * if a system attribute number is supplied, we have to fake it.
12980 * We also do a little bit of bounds checking for safety's sake.
12982 static const char *
12983 getAttrName(int attrnum, TableInfo *tblInfo)
12985 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12986 return tblInfo->attnames[attrnum - 1];
12989 case SelfItemPointerAttributeNumber:
12991 case ObjectIdAttributeNumber:
12993 case MinTransactionIdAttributeNumber:
12995 case MinCommandIdAttributeNumber:
12997 case MaxTransactionIdAttributeNumber:
12999 case MaxCommandIdAttributeNumber:
13001 case TableOidAttributeNumber:
13004 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
13005 attrnum, tblInfo->dobj.name);
13007 return NULL; /* keep compiler quiet */
13012 * write out to fout a user-defined index
13015 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13017 TableInfo *tbinfo = indxinfo->indextable;
13020 PQExpBuffer labelq;
13025 q = createPQExpBuffer();
13026 delq = createPQExpBuffer();
13027 labelq = createPQExpBuffer();
13029 appendPQExpBuffer(labelq, "INDEX %s",
13030 fmtId(indxinfo->dobj.name));
13033 * If there's an associated constraint, don't dump the index per se, but
13034 * do dump any comment for it. (This is safe because dependency ordering
13035 * will have ensured the constraint is emitted first.)
13037 if (indxinfo->indexconstraint == 0)
13039 if (binary_upgrade)
13040 binary_upgrade_set_pg_class_oids(fout, q,
13041 indxinfo->dobj.catId.oid, true);
13043 /* Plain secondary index */
13044 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13046 /* If the index is clustered, we need to record that. */
13047 if (indxinfo->indisclustered)
13049 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13050 fmtId(tbinfo->dobj.name));
13051 appendPQExpBuffer(q, " ON %s;\n",
13052 fmtId(indxinfo->dobj.name));
13056 * DROP must be fully qualified in case same name appears in
13059 appendPQExpBuffer(delq, "DROP INDEX %s.",
13060 fmtId(tbinfo->dobj.namespace->dobj.name));
13061 appendPQExpBuffer(delq, "%s;\n",
13062 fmtId(indxinfo->dobj.name));
13064 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13065 indxinfo->dobj.name,
13066 tbinfo->dobj.namespace->dobj.name,
13067 indxinfo->tablespace,
13068 tbinfo->rolname, false,
13069 "INDEX", SECTION_POST_DATA,
13070 q->data, delq->data, NULL,
13071 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
13075 /* Dump Index Comments */
13076 dumpComment(fout, labelq->data,
13077 tbinfo->dobj.namespace->dobj.name,
13079 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13081 destroyPQExpBuffer(q);
13082 destroyPQExpBuffer(delq);
13083 destroyPQExpBuffer(labelq);
13088 * write out to fout a user-defined constraint
13091 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13093 TableInfo *tbinfo = coninfo->contable;
13097 /* Skip if not to be dumped */
13098 if (!coninfo->dobj.dump || dataOnly)
13101 q = createPQExpBuffer();
13102 delq = createPQExpBuffer();
13104 if (coninfo->contype == 'p' ||
13105 coninfo->contype == 'u' ||
13106 coninfo->contype == 'x')
13108 /* Index-related constraint */
13109 IndxInfo *indxinfo;
13112 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13114 if (indxinfo == NULL)
13116 write_msg(NULL, "missing index for constraint \"%s\"\n",
13117 coninfo->dobj.name);
13121 if (binary_upgrade)
13122 binary_upgrade_set_pg_class_oids(fout, q,
13123 indxinfo->dobj.catId.oid, true);
13125 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13126 fmtId(tbinfo->dobj.name));
13127 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13128 fmtId(coninfo->dobj.name));
13130 if (coninfo->condef)
13132 /* pg_get_constraintdef should have provided everything */
13133 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13137 appendPQExpBuffer(q, "%s (",
13138 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13139 for (k = 0; k < indxinfo->indnkeys; k++)
13141 int indkey = (int) indxinfo->indkeys[k];
13142 const char *attname;
13144 if (indkey == InvalidAttrNumber)
13146 attname = getAttrName(indkey, tbinfo);
13148 appendPQExpBuffer(q, "%s%s",
13149 (k == 0) ? "" : ", ",
13153 appendPQExpBuffer(q, ")");
13155 if (indxinfo->options && strlen(indxinfo->options) > 0)
13156 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13158 if (coninfo->condeferrable)
13160 appendPQExpBuffer(q, " DEFERRABLE");
13161 if (coninfo->condeferred)
13162 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13165 appendPQExpBuffer(q, ";\n");
13168 /* If the index is clustered, we need to record that. */
13169 if (indxinfo->indisclustered)
13171 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13172 fmtId(tbinfo->dobj.name));
13173 appendPQExpBuffer(q, " ON %s;\n",
13174 fmtId(indxinfo->dobj.name));
13178 * DROP must be fully qualified in case same name appears in
13181 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13182 fmtId(tbinfo->dobj.namespace->dobj.name));
13183 appendPQExpBuffer(delq, "%s ",
13184 fmtId(tbinfo->dobj.name));
13185 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13186 fmtId(coninfo->dobj.name));
13188 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13189 coninfo->dobj.name,
13190 tbinfo->dobj.namespace->dobj.name,
13191 indxinfo->tablespace,
13192 tbinfo->rolname, false,
13193 "CONSTRAINT", SECTION_POST_DATA,
13194 q->data, delq->data, NULL,
13195 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13198 else if (coninfo->contype == 'f')
13201 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13202 * current table data is not processed
13204 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13205 fmtId(tbinfo->dobj.name));
13206 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13207 fmtId(coninfo->dobj.name),
13211 * DROP must be fully qualified in case same name appears in
13214 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13215 fmtId(tbinfo->dobj.namespace->dobj.name));
13216 appendPQExpBuffer(delq, "%s ",
13217 fmtId(tbinfo->dobj.name));
13218 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13219 fmtId(coninfo->dobj.name));
13221 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13222 coninfo->dobj.name,
13223 tbinfo->dobj.namespace->dobj.name,
13225 tbinfo->rolname, false,
13226 "FK CONSTRAINT", SECTION_POST_DATA,
13227 q->data, delq->data, NULL,
13228 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13231 else if (coninfo->contype == 'c' && tbinfo)
13233 /* CHECK constraint on a table */
13235 /* Ignore if not to be dumped separately */
13236 if (coninfo->separate)
13238 /* add ONLY if we do not want it to propagate to children */
13239 appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13240 coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13241 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13242 fmtId(coninfo->dobj.name),
13246 * DROP must be fully qualified in case same name appears in
13249 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13250 fmtId(tbinfo->dobj.namespace->dobj.name));
13251 appendPQExpBuffer(delq, "%s ",
13252 fmtId(tbinfo->dobj.name));
13253 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13254 fmtId(coninfo->dobj.name));
13256 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13257 coninfo->dobj.name,
13258 tbinfo->dobj.namespace->dobj.name,
13260 tbinfo->rolname, false,
13261 "CHECK CONSTRAINT", SECTION_POST_DATA,
13262 q->data, delq->data, NULL,
13263 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13267 else if (coninfo->contype == 'c' && tbinfo == NULL)
13269 /* CHECK constraint on a domain */
13270 TypeInfo *tyinfo = coninfo->condomain;
13272 /* Ignore if not to be dumped separately */
13273 if (coninfo->separate)
13275 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13276 fmtId(tyinfo->dobj.name));
13277 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13278 fmtId(coninfo->dobj.name),
13282 * DROP must be fully qualified in case same name appears in
13285 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13286 fmtId(tyinfo->dobj.namespace->dobj.name));
13287 appendPQExpBuffer(delq, "%s ",
13288 fmtId(tyinfo->dobj.name));
13289 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13290 fmtId(coninfo->dobj.name));
13292 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13293 coninfo->dobj.name,
13294 tyinfo->dobj.namespace->dobj.name,
13296 tyinfo->rolname, false,
13297 "CHECK CONSTRAINT", SECTION_POST_DATA,
13298 q->data, delq->data, NULL,
13299 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13305 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
13309 /* Dump Constraint Comments --- only works for table constraints */
13310 if (tbinfo && coninfo->separate)
13311 dumpTableConstraintComment(fout, coninfo);
13313 destroyPQExpBuffer(q);
13314 destroyPQExpBuffer(delq);
13318 * dumpTableConstraintComment --- dump a constraint's comment if any
13320 * This is split out because we need the function in two different places
13321 * depending on whether the constraint is dumped as part of CREATE TABLE
13322 * or as a separate ALTER command.
13325 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13327 TableInfo *tbinfo = coninfo->contable;
13328 PQExpBuffer labelq = createPQExpBuffer();
13330 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13331 fmtId(coninfo->dobj.name));
13332 appendPQExpBuffer(labelq, "ON %s",
13333 fmtId(tbinfo->dobj.name));
13334 dumpComment(fout, labelq->data,
13335 tbinfo->dobj.namespace->dobj.name,
13337 coninfo->dobj.catId, 0,
13338 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13340 destroyPQExpBuffer(labelq);
13344 * findLastBuiltInOid -
13345 * find the last built in oid
13347 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13348 * pg_database entry for the current database
13351 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13356 PQExpBuffer query = createPQExpBuffer();
13358 resetPQExpBuffer(query);
13359 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13360 appendStringLiteralAH(query, dbname, fout);
13362 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13364 ntups = PQntuples(res);
13367 write_msg(NULL, "missing pg_database entry for this database\n");
13372 write_msg(NULL, "found more than one pg_database entry for this database\n");
13375 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13377 destroyPQExpBuffer(query);
13382 * findLastBuiltInOid -
13383 * find the last built in oid
13385 * For 7.0, we do this by assuming that the last thing that initdb does is to
13386 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13387 * initdb won't be changing anymore, it'll do.
13390 findLastBuiltinOid_V70(Archive *fout)
13396 res = ExecuteSqlQuery(fout,
13397 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
13399 ntups = PQntuples(res);
13402 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
13407 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
13410 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13416 dumpSequence(Archive *fout, TableInfo *tbinfo)
13429 PQExpBuffer query = createPQExpBuffer();
13430 PQExpBuffer delqry = createPQExpBuffer();
13431 PQExpBuffer labelq = createPQExpBuffer();
13433 /* Make sure we are in proper schema */
13434 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13436 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13437 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13439 if (fout->remoteVersion >= 80400)
13441 appendPQExpBuffer(query,
13442 "SELECT sequence_name, "
13443 "start_value, last_value, increment_by, "
13444 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13445 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13447 "END AS max_value, "
13448 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13449 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13451 "END AS min_value, "
13452 "cache_value, is_cycled, is_called from %s",
13454 fmtId(tbinfo->dobj.name));
13458 appendPQExpBuffer(query,
13459 "SELECT sequence_name, "
13460 "0 AS start_value, last_value, increment_by, "
13461 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13462 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13464 "END AS max_value, "
13465 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13466 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13468 "END AS min_value, "
13469 "cache_value, is_cycled, is_called from %s",
13471 fmtId(tbinfo->dobj.name));
13474 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13476 if (PQntuples(res) != 1)
13478 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13479 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13481 tbinfo->dobj.name, PQntuples(res));
13485 /* Disable this check: it fails if sequence has been renamed */
13487 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13489 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13490 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13495 startv = PQgetvalue(res, 0, 1);
13496 last = PQgetvalue(res, 0, 2);
13497 incby = PQgetvalue(res, 0, 3);
13498 if (!PQgetisnull(res, 0, 4))
13499 maxv = PQgetvalue(res, 0, 4);
13500 if (!PQgetisnull(res, 0, 5))
13501 minv = PQgetvalue(res, 0, 5);
13502 cache = PQgetvalue(res, 0, 6);
13503 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13504 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13507 * The logic we use for restoring sequences is as follows:
13509 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13510 * last_val for start if called is false, else use min_val for start_val).
13511 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13512 * BY command for it.
13514 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13519 * DROP must be fully qualified in case same name appears in
13522 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13523 fmtId(tbinfo->dobj.namespace->dobj.name));
13524 appendPQExpBuffer(delqry, "%s;\n",
13525 fmtId(tbinfo->dobj.name));
13527 resetPQExpBuffer(query);
13529 if (binary_upgrade)
13531 binary_upgrade_set_pg_class_oids(fout, query,
13532 tbinfo->dobj.catId.oid, false);
13533 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13534 tbinfo->dobj.catId.oid);
13537 appendPQExpBuffer(query,
13538 "CREATE SEQUENCE %s\n",
13539 fmtId(tbinfo->dobj.name));
13541 if (fout->remoteVersion >= 80400)
13542 appendPQExpBuffer(query, " START WITH %s\n", startv);
13546 * Versions before 8.4 did not remember the true start value. If
13547 * is_called is false then the sequence has never been incremented
13548 * so we can use last_val. Otherwise punt and let it default.
13551 appendPQExpBuffer(query, " START WITH %s\n", last);
13554 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13557 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13559 appendPQExpBuffer(query, " NO MINVALUE\n");
13562 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13564 appendPQExpBuffer(query, " NO MAXVALUE\n");
13566 appendPQExpBuffer(query,
13568 cache, (cycled ? "\n CYCLE" : ""));
13570 appendPQExpBuffer(query, ";\n");
13572 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13574 /* binary_upgrade: no need to clear TOAST table oid */
13576 if (binary_upgrade)
13577 binary_upgrade_extension_member(query, &tbinfo->dobj,
13580 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13582 tbinfo->dobj.namespace->dobj.name,
13585 false, "SEQUENCE", SECTION_PRE_DATA,
13586 query->data, delqry->data, NULL,
13587 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13591 * If the sequence is owned by a table column, emit the ALTER for it
13592 * as a separate TOC entry immediately following the sequence's own
13593 * entry. It's OK to do this rather than using full sorting logic,
13594 * because the dependency that tells us it's owned will have forced
13595 * the table to be created first. We can't just include the ALTER in
13596 * the TOC entry because it will fail if we haven't reassigned the
13597 * sequence owner to match the table's owner.
13599 * We need not schema-qualify the table reference because both
13600 * sequence and table must be in the same schema.
13602 if (OidIsValid(tbinfo->owning_tab))
13604 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13606 if (owning_tab && owning_tab->dobj.dump)
13608 resetPQExpBuffer(query);
13609 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13610 fmtId(tbinfo->dobj.name));
13611 appendPQExpBuffer(query, " OWNED BY %s",
13612 fmtId(owning_tab->dobj.name));
13613 appendPQExpBuffer(query, ".%s;\n",
13614 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13616 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13618 tbinfo->dobj.namespace->dobj.name,
13621 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13622 query->data, "", NULL,
13623 &(tbinfo->dobj.dumpId), 1,
13628 /* Dump Sequence Comments and Security Labels */
13629 dumpComment(fout, labelq->data,
13630 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13631 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13632 dumpSecLabel(fout, labelq->data,
13633 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13634 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13639 resetPQExpBuffer(query);
13640 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13641 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13642 appendPQExpBuffer(query, ", %s, %s);\n",
13643 last, (called ? "true" : "false"));
13645 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13647 tbinfo->dobj.namespace->dobj.name,
13650 false, "SEQUENCE SET", SECTION_PRE_DATA,
13651 query->data, "", NULL,
13652 &(tbinfo->dobj.dumpId), 1,
13658 destroyPQExpBuffer(query);
13659 destroyPQExpBuffer(delqry);
13660 destroyPQExpBuffer(labelq);
13664 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13666 TableInfo *tbinfo = tginfo->tgtable;
13668 PQExpBuffer delqry;
13669 PQExpBuffer labelq;
13678 query = createPQExpBuffer();
13679 delqry = createPQExpBuffer();
13680 labelq = createPQExpBuffer();
13683 * DROP must be fully qualified in case same name appears in pg_catalog
13685 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13686 fmtId(tginfo->dobj.name));
13687 appendPQExpBuffer(delqry, "ON %s.",
13688 fmtId(tbinfo->dobj.namespace->dobj.name));
13689 appendPQExpBuffer(delqry, "%s;\n",
13690 fmtId(tbinfo->dobj.name));
13694 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13698 if (tginfo->tgisconstraint)
13700 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13701 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13705 appendPQExpBuffer(query, "CREATE TRIGGER ");
13706 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13708 appendPQExpBuffer(query, "\n ");
13711 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13712 appendPQExpBuffer(query, "BEFORE");
13713 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13714 appendPQExpBuffer(query, "AFTER");
13715 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13716 appendPQExpBuffer(query, "INSTEAD OF");
13719 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13724 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13726 appendPQExpBuffer(query, " INSERT");
13729 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13732 appendPQExpBuffer(query, " OR DELETE");
13734 appendPQExpBuffer(query, " DELETE");
13737 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13740 appendPQExpBuffer(query, " OR UPDATE");
13742 appendPQExpBuffer(query, " UPDATE");
13745 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13748 appendPQExpBuffer(query, " OR TRUNCATE");
13750 appendPQExpBuffer(query, " TRUNCATE");
13753 appendPQExpBuffer(query, " ON %s\n",
13754 fmtId(tbinfo->dobj.name));
13756 if (tginfo->tgisconstraint)
13758 if (OidIsValid(tginfo->tgconstrrelid))
13760 /* If we are using regclass, name is already quoted */
13761 if (fout->remoteVersion >= 70300)
13762 appendPQExpBuffer(query, " FROM %s\n ",
13763 tginfo->tgconstrrelname);
13765 appendPQExpBuffer(query, " FROM %s\n ",
13766 fmtId(tginfo->tgconstrrelname));
13768 if (!tginfo->tgdeferrable)
13769 appendPQExpBuffer(query, "NOT ");
13770 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13771 if (tginfo->tginitdeferred)
13772 appendPQExpBuffer(query, "DEFERRED\n");
13774 appendPQExpBuffer(query, "IMMEDIATE\n");
13777 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13778 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13780 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13782 /* In 7.3, result of regproc is already quoted */
13783 if (fout->remoteVersion >= 70300)
13784 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13787 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13788 fmtId(tginfo->tgfname));
13790 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13793 for (findx = 0; findx < tginfo->tgnargs; findx++)
13795 /* find the embedded null that terminates this trigger argument */
13796 size_t tlen = strlen(p);
13798 if (p + tlen >= tgargs + lentgargs)
13800 /* hm, not found before end of bytea value... */
13801 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13804 tbinfo->dobj.name);
13809 appendPQExpBuffer(query, ", ");
13810 appendStringLiteralAH(query, p, fout);
13814 appendPQExpBuffer(query, ");\n");
13817 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13819 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13820 fmtId(tbinfo->dobj.name));
13821 switch (tginfo->tgenabled)
13825 appendPQExpBuffer(query, "DISABLE");
13828 appendPQExpBuffer(query, "ENABLE ALWAYS");
13831 appendPQExpBuffer(query, "ENABLE REPLICA");
13834 appendPQExpBuffer(query, "ENABLE");
13837 appendPQExpBuffer(query, " TRIGGER %s;\n",
13838 fmtId(tginfo->dobj.name));
13841 appendPQExpBuffer(labelq, "TRIGGER %s ",
13842 fmtId(tginfo->dobj.name));
13843 appendPQExpBuffer(labelq, "ON %s",
13844 fmtId(tbinfo->dobj.name));
13846 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13848 tbinfo->dobj.namespace->dobj.name,
13850 tbinfo->rolname, false,
13851 "TRIGGER", SECTION_POST_DATA,
13852 query->data, delqry->data, NULL,
13853 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13856 dumpComment(fout, labelq->data,
13857 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13858 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13860 destroyPQExpBuffer(query);
13861 destroyPQExpBuffer(delqry);
13862 destroyPQExpBuffer(labelq);
13870 dumpRule(Archive *fout, RuleInfo *rinfo)
13872 TableInfo *tbinfo = rinfo->ruletable;
13875 PQExpBuffer delcmd;
13876 PQExpBuffer labelq;
13879 /* Skip if not to be dumped */
13880 if (!rinfo->dobj.dump || dataOnly)
13884 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13885 * we do not want to dump it as a separate object.
13887 if (!rinfo->separate)
13891 * Make sure we are in proper schema.
13893 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13895 query = createPQExpBuffer();
13896 cmd = createPQExpBuffer();
13897 delcmd = createPQExpBuffer();
13898 labelq = createPQExpBuffer();
13900 if (fout->remoteVersion >= 70300)
13902 appendPQExpBuffer(query,
13903 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13904 rinfo->dobj.catId.oid);
13908 /* Rule name was unique before 7.3 ... */
13909 appendPQExpBuffer(query,
13910 "SELECT pg_get_ruledef('%s') AS definition",
13914 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13916 if (PQntuples(res) != 1)
13918 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13919 rinfo->dobj.name, tbinfo->dobj.name);
13923 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13926 * Add the command to alter the rules replication firing semantics if it
13927 * differs from the default.
13929 if (rinfo->ev_enabled != 'O')
13931 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13932 fmtId(tbinfo->dobj.namespace->dobj.name));
13933 appendPQExpBuffer(cmd, "%s ",
13934 fmtId(tbinfo->dobj.name));
13935 switch (rinfo->ev_enabled)
13938 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13939 fmtId(rinfo->dobj.name));
13942 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13943 fmtId(rinfo->dobj.name));
13946 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13947 fmtId(rinfo->dobj.name));
13953 * DROP must be fully qualified in case same name appears in pg_catalog
13955 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13956 fmtId(rinfo->dobj.name));
13957 appendPQExpBuffer(delcmd, "ON %s.",
13958 fmtId(tbinfo->dobj.namespace->dobj.name));
13959 appendPQExpBuffer(delcmd, "%s;\n",
13960 fmtId(tbinfo->dobj.name));
13962 appendPQExpBuffer(labelq, "RULE %s",
13963 fmtId(rinfo->dobj.name));
13964 appendPQExpBuffer(labelq, " ON %s",
13965 fmtId(tbinfo->dobj.name));
13967 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13969 tbinfo->dobj.namespace->dobj.name,
13971 tbinfo->rolname, false,
13972 "RULE", SECTION_POST_DATA,
13973 cmd->data, delcmd->data, NULL,
13974 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13977 /* Dump rule comments */
13978 dumpComment(fout, labelq->data,
13979 tbinfo->dobj.namespace->dobj.name,
13981 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13985 destroyPQExpBuffer(query);
13986 destroyPQExpBuffer(cmd);
13987 destroyPQExpBuffer(delcmd);
13988 destroyPQExpBuffer(labelq);
13992 * getExtensionMembership --- obtain extension membership data
13995 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14006 DumpableObject *dobj,
14009 /* Nothing to do if no extensions */
14010 if (numExtensions == 0)
14013 /* Make sure we are in proper schema */
14014 selectSourceSchema(fout, "pg_catalog");
14016 query = createPQExpBuffer();
14018 /* refclassid constraint is redundant but may speed the search */
14019 appendPQExpBuffer(query, "SELECT "
14020 "classid, objid, refclassid, refobjid "
14022 "WHERE refclassid = 'pg_extension'::regclass "
14023 "AND deptype = 'e' "
14026 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14028 ntups = PQntuples(res);
14030 i_classid = PQfnumber(res, "classid");
14031 i_objid = PQfnumber(res, "objid");
14032 i_refclassid = PQfnumber(res, "refclassid");
14033 i_refobjid = PQfnumber(res, "refobjid");
14036 * Since we ordered the SELECT by referenced ID, we can expect that
14037 * multiple entries for the same extension will appear together; this
14038 * saves on searches.
14042 for (i = 0; i < ntups; i++)
14045 CatalogId refobjId;
14047 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14048 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14049 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14050 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14052 if (refdobj == NULL ||
14053 refdobj->catId.tableoid != refobjId.tableoid ||
14054 refdobj->catId.oid != refobjId.oid)
14055 refdobj = findObjectByCatalogId(refobjId);
14058 * Failure to find objects mentioned in pg_depend is not unexpected,
14059 * since for example we don't collect info about TOAST tables.
14061 if (refdobj == NULL)
14064 fprintf(stderr, "no referenced object %u %u\n",
14065 refobjId.tableoid, refobjId.oid);
14070 dobj = findObjectByCatalogId(objId);
14075 fprintf(stderr, "no referencing object %u %u\n",
14076 objId.tableoid, objId.oid);
14081 /* Record dependency so that getDependencies needn't repeat this */
14082 addObjectDependency(dobj, refdobj->dumpId);
14084 dobj->ext_member = true;
14087 * Normally, mark the member object as not to be dumped. But in
14088 * binary upgrades, we still dump the members individually, since the
14089 * idea is to exactly reproduce the database contents rather than
14090 * replace the extension contents with something different.
14092 if (!binary_upgrade)
14093 dobj->dump = false;
14095 dobj->dump = refdobj->dump;
14101 * Now identify extension configuration tables and create TableDataInfo
14102 * objects for them, ensuring their data will be dumped even though the
14103 * tables themselves won't be.
14105 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14106 * user data in a configuration table is treated like schema data. This
14107 * seems appropriate since system data in a config table would get
14108 * reloaded by CREATE EXTENSION.
14110 for (i = 0; i < numExtensions; i++)
14112 char *extconfig = extinfo[i].extconfig;
14113 char *extcondition = extinfo[i].extcondition;
14114 char **extconfigarray = NULL;
14115 char **extconditionarray = NULL;
14117 int nconditionitems;
14119 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14120 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14121 nconfigitems == nconditionitems)
14125 for (j = 0; j < nconfigitems; j++)
14127 TableInfo *configtbl;
14129 configtbl = findTableByOid(atooid(extconfigarray[j]));
14130 if (configtbl && configtbl->dataObj == NULL)
14133 * Note: config tables are dumped without OIDs regardless
14134 * of the --oids setting. This is because row filtering
14135 * conditions aren't compatible with dumping OIDs.
14137 makeTableDataInfo(configtbl, false);
14138 if (strlen(extconditionarray[j]) > 0)
14139 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14143 if (extconfigarray)
14144 free(extconfigarray);
14145 if (extconditionarray)
14146 free(extconditionarray);
14149 destroyPQExpBuffer(query);
14153 * getDependencies --- obtain available dependency data
14156 getDependencies(Archive *fout)
14167 DumpableObject *dobj,
14170 /* No dependency info available before 7.3 */
14171 if (fout->remoteVersion < 70300)
14175 write_msg(NULL, "reading dependency data\n");
14177 /* Make sure we are in proper schema */
14178 selectSourceSchema(fout, "pg_catalog");
14180 query = createPQExpBuffer();
14183 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14184 * already processed by getExtensionMembership.
14186 appendPQExpBuffer(query, "SELECT "
14187 "classid, objid, refclassid, refobjid, deptype "
14189 "WHERE deptype != 'p' AND deptype != 'e' "
14192 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14194 ntups = PQntuples(res);
14196 i_classid = PQfnumber(res, "classid");
14197 i_objid = PQfnumber(res, "objid");
14198 i_refclassid = PQfnumber(res, "refclassid");
14199 i_refobjid = PQfnumber(res, "refobjid");
14200 i_deptype = PQfnumber(res, "deptype");
14203 * Since we ordered the SELECT by referencing ID, we can expect that
14204 * multiple entries for the same object will appear together; this saves
14209 for (i = 0; i < ntups; i++)
14212 CatalogId refobjId;
14215 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14216 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14217 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14218 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14219 deptype = *(PQgetvalue(res, i, i_deptype));
14221 if (dobj == NULL ||
14222 dobj->catId.tableoid != objId.tableoid ||
14223 dobj->catId.oid != objId.oid)
14224 dobj = findObjectByCatalogId(objId);
14227 * Failure to find objects mentioned in pg_depend is not unexpected,
14228 * since for example we don't collect info about TOAST tables.
14233 fprintf(stderr, "no referencing object %u %u\n",
14234 objId.tableoid, objId.oid);
14239 refdobj = findObjectByCatalogId(refobjId);
14241 if (refdobj == NULL)
14244 fprintf(stderr, "no referenced object %u %u\n",
14245 refobjId.tableoid, refobjId.oid);
14251 * Ordinarily, table rowtypes have implicit dependencies on their
14252 * tables. However, for a composite type the implicit dependency goes
14253 * the other way in pg_depend; which is the right thing for DROP but
14254 * it doesn't produce the dependency ordering we need. So in that one
14255 * case, we reverse the direction of the dependency.
14257 if (deptype == 'i' &&
14258 dobj->objType == DO_TABLE &&
14259 refdobj->objType == DO_TYPE)
14260 addObjectDependency(refdobj, dobj->dumpId);
14263 addObjectDependency(dobj, refdobj->dumpId);
14268 destroyPQExpBuffer(query);
14273 * selectSourceSchema - make the specified schema the active search path
14274 * in the source database.
14276 * NB: pg_catalog is explicitly searched after the specified schema;
14277 * so user names are only qualified if they are cross-schema references,
14278 * and system names are only qualified if they conflict with a user name
14279 * in the current schema.
14281 * Whenever the selected schema is not pg_catalog, be careful to qualify
14282 * references to system catalogs and types in our emitted commands!
14285 selectSourceSchema(Archive *fout, const char *schemaName)
14287 static char *curSchemaName = NULL;
14290 /* Not relevant if fetching from pre-7.3 DB */
14291 if (fout->remoteVersion < 70300)
14293 /* Ignore null schema names */
14294 if (schemaName == NULL || *schemaName == '\0')
14296 /* Optimize away repeated selection of same schema */
14297 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14300 query = createPQExpBuffer();
14301 appendPQExpBuffer(query, "SET search_path = %s",
14302 fmtId(schemaName));
14303 if (strcmp(schemaName, "pg_catalog") != 0)
14304 appendPQExpBuffer(query, ", pg_catalog");
14306 ExecuteSqlStatement(fout, query->data);
14308 destroyPQExpBuffer(query);
14310 free(curSchemaName);
14311 curSchemaName = pg_strdup(schemaName);
14315 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14318 * NB: in 7.3 and up the result may depend on the currently-selected
14319 * schema; this is why we don't try to cache the names.
14322 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14331 if ((opts & zeroAsOpaque) != 0)
14332 return pg_strdup(g_opaque_type);
14333 else if ((opts & zeroAsAny) != 0)
14334 return pg_strdup("'any'");
14335 else if ((opts & zeroAsStar) != 0)
14336 return pg_strdup("*");
14337 else if ((opts & zeroAsNone) != 0)
14338 return pg_strdup("NONE");
14341 query = createPQExpBuffer();
14342 if (fout->remoteVersion >= 70300)
14344 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14347 else if (fout->remoteVersion >= 70100)
14349 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14354 appendPQExpBuffer(query, "SELECT typname "
14356 "WHERE oid = '%u'::oid",
14360 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14362 /* Expecting a single result only */
14363 ntups = PQntuples(res);
14366 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
14367 "query returned %d rows instead of one: %s\n",
14369 ntups, query->data);
14373 if (fout->remoteVersion >= 70100)
14375 /* already quoted */
14376 result = pg_strdup(PQgetvalue(res, 0, 0));
14380 /* may need to quote it */
14381 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14385 destroyPQExpBuffer(query);
14391 * myFormatType --- local implementation of format_type for use with 7.0.
14394 myFormatType(const char *typname, int32 typmod)
14397 bool isarray = false;
14398 PQExpBuffer buf = createPQExpBuffer();
14400 /* Handle array types */
14401 if (typname[0] == '_')
14407 /* Show lengths on bpchar and varchar */
14408 if (strcmp(typname, "bpchar") == 0)
14410 int len = (typmod - VARHDRSZ);
14412 appendPQExpBuffer(buf, "character");
14414 appendPQExpBuffer(buf, "(%d)",
14415 typmod - VARHDRSZ);
14417 else if (strcmp(typname, "varchar") == 0)
14419 appendPQExpBuffer(buf, "character varying");
14421 appendPQExpBuffer(buf, "(%d)",
14422 typmod - VARHDRSZ);
14424 else if (strcmp(typname, "numeric") == 0)
14426 appendPQExpBuffer(buf, "numeric");
14433 tmp_typmod = typmod - VARHDRSZ;
14434 precision = (tmp_typmod >> 16) & 0xffff;
14435 scale = tmp_typmod & 0xffff;
14436 appendPQExpBuffer(buf, "(%d,%d)",
14442 * char is an internal single-byte data type; Let's make sure we force it
14443 * through with quotes. - thomas 1998-12-13
14445 else if (strcmp(typname, "char") == 0)
14446 appendPQExpBuffer(buf, "\"char\"");
14448 appendPQExpBuffer(buf, "%s", fmtId(typname));
14450 /* Append array qualifier for array types */
14452 appendPQExpBuffer(buf, "[]");
14454 result = pg_strdup(buf->data);
14455 destroyPQExpBuffer(buf);
14461 * fmtQualifiedId - convert a qualified name to the proper format for
14462 * the source database.
14464 * Like fmtId, use the result before calling again.
14466 static const char *
14467 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14469 static PQExpBuffer id_return = NULL;
14471 if (id_return) /* first time through? */
14472 resetPQExpBuffer(id_return);
14474 id_return = createPQExpBuffer();
14476 /* Suppress schema name if fetching from pre-7.3 DB */
14477 if (fout->remoteVersion >= 70300 && schema && *schema)
14479 appendPQExpBuffer(id_return, "%s.",
14482 appendPQExpBuffer(id_return, "%s",
14485 return id_return->data;
14489 * Return a column list clause for the given relation.
14491 * Special case: if there are no undropped columns in the relation, return
14492 * "", not an invalid "()" column list.
14494 static const char *
14495 fmtCopyColumnList(const TableInfo *ti)
14497 static PQExpBuffer q = NULL;
14498 int numatts = ti->numatts;
14499 char **attnames = ti->attnames;
14500 bool *attisdropped = ti->attisdropped;
14504 if (q) /* first time through? */
14505 resetPQExpBuffer(q);
14507 q = createPQExpBuffer();
14509 appendPQExpBuffer(q, "(");
14511 for (i = 0; i < numatts; i++)
14513 if (attisdropped[i])
14516 appendPQExpBuffer(q, ", ");
14517 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14522 return ""; /* no undropped columns */
14524 appendPQExpBuffer(q, ")");