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;
1146 * selectDumpableType: policy-setting subroutine
1147 * Mark a type as to be dumped or not
1149 * If it's a table's rowtype or an autogenerated array type, we also apply a
1150 * special type code to facilitate sorting into the desired order. (We don't
1151 * want to consider those to be ordinary types because that would bring tables
1152 * up into the datatype part of the dump order.) We still set the object's
1153 * dump flag; that's not going to cause the dummy type to be dumped, but we
1154 * need it so that casts involving such types will be dumped correctly -- see
1155 * dumpCast. This means the flag should be set the same as for the underlying
1156 * object (the table or base type).
1159 selectDumpableType(TypeInfo *tyinfo)
1161 /* skip complex types, except for standalone composite types */
1162 if (OidIsValid(tyinfo->typrelid) &&
1163 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1165 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1167 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1168 if (tytable != NULL)
1169 tyinfo->dobj.dump = tytable->dobj.dump;
1171 tyinfo->dobj.dump = false;
1175 /* skip auto-generated array types */
1176 if (tyinfo->isArray)
1178 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1180 * Fall through to set the dump flag; we assume that the subsequent
1181 * rules will do the same thing as they would for the array's base
1182 * type. (We cannot reliably look up the base type here, since
1183 * getTypes may not have processed it yet.)
1187 /* dump only types in dumpable namespaces */
1188 if (!tyinfo->dobj.namespace->dobj.dump)
1189 tyinfo->dobj.dump = false;
1191 /* skip undefined placeholder types */
1192 else if (!tyinfo->isDefined)
1193 tyinfo->dobj.dump = false;
1196 tyinfo->dobj.dump = true;
1200 * selectDumpableDefaultACL: policy-setting subroutine
1201 * Mark a default ACL as to be dumped or not
1203 * For per-schema default ACLs, dump if the schema is to be dumped.
1204 * Otherwise dump if we are dumping "everything". Note that dataOnly
1205 * and aclsSkip are checked separately.
1208 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1210 if (dinfo->dobj.namespace)
1211 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1213 dinfo->dobj.dump = include_everything;
1217 * selectDumpableExtension: policy-setting subroutine
1218 * Mark an extension as to be dumped or not
1220 * Normally, we dump all extensions, or none of them if include_everything
1221 * is false (i.e., a --schema or --table switch was given). However, in
1222 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1223 * assume those will already be installed in the target database. We identify
1224 * such extensions by their having OIDs in the range reserved for initdb.
1227 selectDumpableExtension(ExtensionInfo *extinfo)
1229 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1230 extinfo->dobj.dump = false;
1232 extinfo->dobj.dump = include_everything;
1236 * selectDumpableObject: policy-setting subroutine
1237 * Mark a generic dumpable object as to be dumped or not
1239 * Use this only for object types without a special-case routine above.
1242 selectDumpableObject(DumpableObject *dobj)
1245 * Default policy is to dump if parent namespace is dumpable, or always
1246 * for non-namespace-associated items.
1248 if (dobj->namespace)
1249 dobj->dump = dobj->namespace->dobj.dump;
1255 * Dump a table's contents for loading using the COPY command
1256 * - this routine is called by the Archiver when it wants the table
1261 dumpTableData_copy(Archive *fout, void *dcontext)
1263 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1264 TableInfo *tbinfo = tdinfo->tdtable;
1265 const char *classname = tbinfo->dobj.name;
1266 const bool hasoids = tbinfo->hasoids;
1267 const bool oids = tdinfo->oids;
1268 PQExpBuffer q = createPQExpBuffer();
1272 const char *column_list;
1275 write_msg(NULL, "dumping contents of table %s\n", classname);
1278 * Make sure we are in proper schema. We will qualify the table name
1279 * below anyway (in case its name conflicts with a pg_catalog table); but
1280 * this ensures reproducible results in case the table contains regproc,
1281 * regclass, etc columns.
1283 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1286 * If possible, specify the column list explicitly so that we have no
1287 * possibility of retrieving data in the wrong column order. (The default
1288 * column ordering of COPY will not be what we want in certain corner
1289 * cases involving ADD COLUMN and inheritance.)
1291 if (fout->remoteVersion >= 70300)
1292 column_list = fmtCopyColumnList(tbinfo);
1294 column_list = ""; /* can't select columns in COPY */
1296 if (oids && hasoids)
1298 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1299 fmtQualifiedId(fout,
1300 tbinfo->dobj.namespace->dobj.name,
1304 else if (tdinfo->filtercond)
1306 /* Note: this syntax is only supported in 8.2 and up */
1307 appendPQExpBufferStr(q, "COPY (SELECT ");
1308 /* klugery to get rid of parens in column list */
1309 if (strlen(column_list) > 2)
1311 appendPQExpBufferStr(q, column_list + 1);
1312 q->data[q->len - 1] = ' ';
1315 appendPQExpBufferStr(q, "* ");
1316 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1317 fmtQualifiedId(fout,
1318 tbinfo->dobj.namespace->dobj.name,
1320 tdinfo->filtercond);
1324 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1325 fmtQualifiedId(fout,
1326 tbinfo->dobj.namespace->dobj.name,
1330 res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
1335 ret = PQgetCopyData(g_conn, ©buf, 0);
1338 break; /* done or error */
1342 WriteData(fout, copybuf, ret);
1349 * There was considerable discussion in late July, 2000 regarding
1350 * slowing down pg_dump when backing up large tables. Users with both
1351 * slow & fast (multi-processor) machines experienced performance
1352 * degradation when doing a backup.
1354 * Initial attempts based on sleeping for a number of ms for each ms
1355 * of work were deemed too complex, then a simple 'sleep in each loop'
1356 * implementation was suggested. The latter failed because the loop
1357 * was too tight. Finally, the following was implemented:
1359 * If throttle is non-zero, then
1360 * See how long since the last sleep.
1361 * Work out how long to sleep (based on ratio).
1362 * If sleep is more than 100ms, then
1368 * where the throttle value was the number of ms to sleep per ms of
1369 * work. The calculation was done in each loop.
1371 * Most of the hard work is done in the backend, and this solution
1372 * still did not work particularly well: on slow machines, the ratio
1373 * was 50:1, and on medium paced machines, 1:1, and on fast
1374 * multi-processor machines, it had little or no effect, for reasons
1375 * that were unclear.
1377 * Further discussion ensued, and the proposal was dropped.
1379 * For those people who want this feature, it can be implemented using
1380 * gettimeofday in each loop, calculating the time since last sleep,
1381 * multiplying that by the sleep ratio, then if the result is more
1382 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1383 * function to sleep for a subsecond period ie.
1385 * select(0, NULL, NULL, NULL, &tvi);
1387 * This will return after the interval specified in the structure tvi.
1388 * Finally, call gettimeofday again to save the 'last sleep time'.
1392 archprintf(fout, "\\.\n\n\n");
1396 /* copy data transfer failed */
1397 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1398 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1399 write_msg(NULL, "The command was: %s\n", q->data);
1403 /* Check command status and return to normal libpq state */
1404 res = PQgetResult(g_conn);
1405 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1407 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetResult() failed.\n", classname);
1408 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1409 write_msg(NULL, "The command was: %s\n", q->data);
1414 destroyPQExpBuffer(q);
1419 * Dump table data using INSERT commands.
1421 * Caution: when we restore from an archive file direct to database, the
1422 * INSERT commands emitted by this function have to be parsed by
1423 * pg_backup_db.c's ExecuteInsertCommands(), which will not handle comments,
1424 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1427 dumpTableData_insert(Archive *fout, void *dcontext)
1429 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1430 TableInfo *tbinfo = tdinfo->tdtable;
1431 const char *classname = tbinfo->dobj.name;
1432 PQExpBuffer q = createPQExpBuffer();
1439 * Make sure we are in proper schema. We will qualify the table name
1440 * below anyway (in case its name conflicts with a pg_catalog table); but
1441 * this ensures reproducible results in case the table contains regproc,
1442 * regclass, etc columns.
1444 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
1446 if (fout->remoteVersion >= 70100)
1448 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1449 "SELECT * FROM ONLY %s",
1450 fmtQualifiedId(fout,
1451 tbinfo->dobj.namespace->dobj.name,
1456 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1458 fmtQualifiedId(fout,
1459 tbinfo->dobj.namespace->dobj.name,
1462 if (tdinfo->filtercond)
1463 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1465 ExecuteSqlStatement(fout, q->data);
1469 res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
1471 nfields = PQnfields(res);
1472 for (tuple = 0; tuple < PQntuples(res); tuple++)
1474 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1477 /* corner case for zero-column table */
1478 archprintf(fout, "DEFAULT VALUES;\n");
1483 resetPQExpBuffer(q);
1484 appendPQExpBuffer(q, "(");
1485 for (field = 0; field < nfields; field++)
1488 appendPQExpBuffer(q, ", ");
1489 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1491 appendPQExpBuffer(q, ") ");
1492 archputs(q->data, fout);
1494 archprintf(fout, "VALUES (");
1495 for (field = 0; field < nfields; field++)
1498 archprintf(fout, ", ");
1499 if (PQgetisnull(res, tuple, field))
1501 archprintf(fout, "NULL");
1505 /* XXX This code is partially duplicated in ruleutils.c */
1506 switch (PQftype(res, field))
1517 * These types are printed without quotes unless
1518 * they contain values that aren't accepted by the
1519 * scanner unquoted (e.g., 'NaN'). Note that
1520 * strtod() and friends might accept NaN, so we
1521 * can't use that to test.
1523 * In reality we only need to defend against
1524 * infinity and NaN, so we need not get too crazy
1525 * about pattern matching here.
1527 const char *s = PQgetvalue(res, tuple, field);
1529 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1530 archprintf(fout, "%s", s);
1532 archprintf(fout, "'%s'", s);
1538 archprintf(fout, "B'%s'",
1539 PQgetvalue(res, tuple, field));
1543 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1544 archprintf(fout, "true");
1546 archprintf(fout, "false");
1550 /* All other types are printed as string literals. */
1551 resetPQExpBuffer(q);
1552 appendStringLiteralAH(q,
1553 PQgetvalue(res, tuple, field),
1555 archputs(q->data, fout);
1559 archprintf(fout, ");\n");
1562 if (PQntuples(res) <= 0)
1570 archprintf(fout, "\n\n");
1572 ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
1574 destroyPQExpBuffer(q);
1581 * dump the contents of a single table
1583 * Actually, this just makes an ArchiveEntry for the table contents.
1586 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1588 TableInfo *tbinfo = tdinfo->tdtable;
1589 PQExpBuffer copyBuf = createPQExpBuffer();
1590 DataDumperPtr dumpFn;
1595 /* Dump/restore using COPY */
1596 dumpFn = dumpTableData_copy;
1597 /* must use 2 steps here 'cause fmtId is nonreentrant */
1598 appendPQExpBuffer(copyBuf, "COPY %s ",
1599 fmtId(tbinfo->dobj.name));
1600 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1601 fmtCopyColumnList(tbinfo),
1602 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1603 copyStmt = copyBuf->data;
1607 /* Restore using INSERT */
1608 dumpFn = dumpTableData_insert;
1612 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1613 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1614 NULL, tbinfo->rolname,
1615 false, "TABLE DATA", SECTION_DATA,
1617 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1620 destroyPQExpBuffer(copyBuf);
1625 * set up dumpable objects representing the contents of tables
1628 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1632 for (i = 0; i < numTables; i++)
1634 if (tblinfo[i].dobj.dump)
1635 makeTableDataInfo(&(tblinfo[i]), oids);
1640 * Make a dumpable object for the data of this specific table
1642 * Note: we make a TableDataInfo if and only if we are going to dump the
1643 * table data; the "dump" flag in such objects isn't used.
1646 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1648 TableDataInfo *tdinfo;
1651 * Nothing to do if we already decided to dump the table. This will
1652 * happen for "config" tables.
1654 if (tbinfo->dataObj != NULL)
1657 /* Skip VIEWs (no data to dump) */
1658 if (tbinfo->relkind == RELKIND_VIEW)
1660 /* Skip SEQUENCEs (handled elsewhere) */
1661 if (tbinfo->relkind == RELKIND_SEQUENCE)
1663 /* Skip FOREIGN TABLEs (no data to dump) */
1664 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
1667 /* Don't dump data in unlogged tables, if so requested */
1668 if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
1669 no_unlogged_table_data)
1672 /* Check that the data is not explicitly excluded */
1673 if (simple_oid_list_member(&tabledata_exclude_oids,
1674 tbinfo->dobj.catId.oid))
1677 /* OK, let's dump it */
1678 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1680 tdinfo->dobj.objType = DO_TABLE_DATA;
1683 * Note: use tableoid 0 so that this object won't be mistaken for
1684 * something that pg_depend entries apply to.
1686 tdinfo->dobj.catId.tableoid = 0;
1687 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1688 AssignDumpId(&tdinfo->dobj);
1689 tdinfo->dobj.name = tbinfo->dobj.name;
1690 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1691 tdinfo->tdtable = tbinfo;
1692 tdinfo->oids = oids;
1693 tdinfo->filtercond = NULL; /* might get set later */
1694 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1696 tbinfo->dataObj = tdinfo;
1700 * getTableDataFKConstraints -
1701 * add dump-order dependencies reflecting foreign key constraints
1703 * This code is executed only in a data-only dump --- in schema+data dumps
1704 * we handle foreign key issues by not creating the FK constraints until
1705 * after the data is loaded. In a data-only dump, however, we want to
1706 * order the table data objects in such a way that a table's referenced
1707 * tables are restored first. (In the presence of circular references or
1708 * self-references this may be impossible; we'll detect and complain about
1709 * that during the dependency sorting step.)
1712 getTableDataFKConstraints(void)
1714 DumpableObject **dobjs;
1718 /* Search through all the dumpable objects for FK constraints */
1719 getDumpableObjects(&dobjs, &numObjs);
1720 for (i = 0; i < numObjs; i++)
1722 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1724 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1727 /* Not interesting unless both tables are to be dumped */
1728 if (cinfo->contable == NULL ||
1729 cinfo->contable->dataObj == NULL)
1731 ftable = findTableByOid(cinfo->confrelid);
1732 if (ftable == NULL ||
1733 ftable->dataObj == NULL)
1737 * Okay, make referencing table's TABLE_DATA object depend on the
1738 * referenced table's TABLE_DATA object.
1740 addObjectDependency(&cinfo->contable->dataObj->dobj,
1741 ftable->dataObj->dobj.dumpId);
1749 * guessConstraintInheritance:
1750 * In pre-8.4 databases, we can't tell for certain which constraints
1751 * are inherited. We assume a CHECK constraint is inherited if its name
1752 * matches the name of any constraint in the parent. Originally this code
1753 * tried to compare the expression texts, but that can fail for various
1754 * reasons --- for example, if the parent and child tables are in different
1755 * schemas, reverse-listing of function calls may produce different text
1756 * (schema-qualified or not) depending on search path.
1758 * In 8.4 and up we can rely on the conislocal field to decide which
1759 * constraints must be dumped; much safer.
1761 * This function assumes all conislocal flags were initialized to TRUE.
1762 * It clears the flag on anything that seems to be inherited.
1765 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1771 for (i = 0; i < numTables; i++)
1773 TableInfo *tbinfo = &(tblinfo[i]);
1775 TableInfo **parents;
1778 /* Sequences and views never have parents */
1779 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1780 tbinfo->relkind == RELKIND_VIEW)
1783 /* Don't bother computing anything for non-target tables, either */
1784 if (!tbinfo->dobj.dump)
1787 numParents = tbinfo->numParents;
1788 parents = tbinfo->parents;
1790 if (numParents == 0)
1791 continue; /* nothing to see here, move along */
1793 /* scan for inherited CHECK constraints */
1794 for (j = 0; j < tbinfo->ncheck; j++)
1796 ConstraintInfo *constr;
1798 constr = &(tbinfo->checkexprs[j]);
1800 for (k = 0; k < numParents; k++)
1804 parent = parents[k];
1805 for (l = 0; l < parent->ncheck; l++)
1807 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1809 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1811 constr->conislocal = false;
1815 if (!constr->conislocal)
1825 * dump the database definition
1828 dumpDatabase(Archive *fout)
1830 PQExpBuffer dbQry = createPQExpBuffer();
1831 PQExpBuffer delQry = createPQExpBuffer();
1832 PQExpBuffer creaQry = createPQExpBuffer();
1845 const char *datname,
1853 datname = PQdb(g_conn);
1856 write_msg(NULL, "saving database definition\n");
1858 /* Make sure we are in proper schema */
1859 selectSourceSchema(fout, "pg_catalog");
1861 /* Get the database owner and parameters from pg_database */
1862 if (fout->remoteVersion >= 80400)
1864 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1865 "(%s datdba) AS dba, "
1866 "pg_encoding_to_char(encoding) AS encoding, "
1867 "datcollate, datctype, datfrozenxid, "
1868 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1869 "shobj_description(oid, 'pg_database') AS description "
1874 appendStringLiteralAH(dbQry, datname, fout);
1876 else if (fout->remoteVersion >= 80200)
1878 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1879 "(%s datdba) AS dba, "
1880 "pg_encoding_to_char(encoding) AS encoding, "
1881 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1882 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1883 "shobj_description(oid, 'pg_database') AS description "
1888 appendStringLiteralAH(dbQry, datname, fout);
1890 else if (fout->remoteVersion >= 80000)
1892 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1893 "(%s datdba) AS dba, "
1894 "pg_encoding_to_char(encoding) AS encoding, "
1895 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1896 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1900 appendStringLiteralAH(dbQry, datname, fout);
1902 else if (fout->remoteVersion >= 70100)
1904 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1905 "(%s datdba) AS dba, "
1906 "pg_encoding_to_char(encoding) AS encoding, "
1907 "NULL AS datcollate, NULL AS datctype, "
1908 "0 AS datfrozenxid, "
1909 "NULL AS tablespace "
1913 appendStringLiteralAH(dbQry, datname, fout);
1917 appendPQExpBuffer(dbQry, "SELECT "
1918 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1920 "(%s datdba) AS dba, "
1921 "pg_encoding_to_char(encoding) AS encoding, "
1922 "NULL AS datcollate, NULL AS datctype, "
1923 "0 AS datfrozenxid, "
1924 "NULL AS tablespace "
1928 appendStringLiteralAH(dbQry, datname, fout);
1931 res = ExecuteSqlQuery(fout, dbQry->data, PGRES_TUPLES_OK);
1933 ntups = PQntuples(res);
1937 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1944 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1949 i_tableoid = PQfnumber(res, "tableoid");
1950 i_oid = PQfnumber(res, "oid");
1951 i_dba = PQfnumber(res, "dba");
1952 i_encoding = PQfnumber(res, "encoding");
1953 i_collate = PQfnumber(res, "datcollate");
1954 i_ctype = PQfnumber(res, "datctype");
1955 i_frozenxid = PQfnumber(res, "datfrozenxid");
1956 i_tablespace = PQfnumber(res, "tablespace");
1958 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1959 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1960 dba = PQgetvalue(res, 0, i_dba);
1961 encoding = PQgetvalue(res, 0, i_encoding);
1962 collate = PQgetvalue(res, 0, i_collate);
1963 ctype = PQgetvalue(res, 0, i_ctype);
1964 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1965 tablespace = PQgetvalue(res, 0, i_tablespace);
1967 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1969 if (strlen(encoding) > 0)
1971 appendPQExpBuffer(creaQry, " ENCODING = ");
1972 appendStringLiteralAH(creaQry, encoding, fout);
1974 if (strlen(collate) > 0)
1976 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1977 appendStringLiteralAH(creaQry, collate, fout);
1979 if (strlen(ctype) > 0)
1981 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1982 appendStringLiteralAH(creaQry, ctype, fout);
1984 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1985 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1987 appendPQExpBuffer(creaQry, ";\n");
1991 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1992 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1993 "SET datfrozenxid = '%u'\n"
1996 appendStringLiteralAH(creaQry, datname, fout);
1997 appendPQExpBuffer(creaQry, ";\n");
2001 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
2004 dbDumpId = createDumpId();
2007 dbCatId, /* catalog ID */
2008 dbDumpId, /* dump ID */
2010 NULL, /* Namespace */
2011 NULL, /* Tablespace */
2013 false, /* with oids */
2014 "DATABASE", /* Desc */
2015 SECTION_PRE_DATA, /* Section */
2016 creaQry->data, /* Create */
2017 delQry->data, /* Del */
2022 NULL); /* Dumper Arg */
2025 * pg_largeobject and pg_largeobject_metadata come from the old system
2026 * intact, so set their relfrozenxids.
2031 PQExpBuffer loFrozenQry = createPQExpBuffer();
2032 PQExpBuffer loOutQry = createPQExpBuffer();
2038 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2039 "FROM pg_catalog.pg_class\n"
2040 "WHERE oid = %u;\n",
2041 LargeObjectRelationId);
2043 lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
2045 if (PQntuples(lo_res) != 1)
2047 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
2051 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2053 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
2054 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2055 "SET relfrozenxid = '%u'\n"
2056 "WHERE oid = %u;\n",
2057 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2058 LargeObjectRelationId);
2059 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2060 "pg_largeobject", NULL, NULL, "",
2061 false, "pg_largeobject", SECTION_PRE_DATA,
2062 loOutQry->data, "", NULL,
2069 * pg_largeobject_metadata
2071 if (fout->remoteVersion >= 90000)
2073 resetPQExpBuffer(loFrozenQry);
2074 resetPQExpBuffer(loOutQry);
2076 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
2077 "FROM pg_catalog.pg_class\n"
2078 "WHERE oid = %u;\n",
2079 LargeObjectMetadataRelationId);
2081 lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
2083 if (PQntuples(lo_res) != 1)
2085 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject_metadata.relfrozenxid\n");
2089 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2091 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2092 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2093 "SET relfrozenxid = '%u'\n"
2094 "WHERE oid = %u;\n",
2095 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2096 LargeObjectMetadataRelationId);
2097 ArchiveEntry(fout, nilCatalogId, createDumpId(),
2098 "pg_largeobject_metadata", NULL, NULL, "",
2099 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2100 loOutQry->data, "", NULL,
2107 destroyPQExpBuffer(loFrozenQry);
2108 destroyPQExpBuffer(loOutQry);
2111 /* Dump DB comment if any */
2112 if (fout->remoteVersion >= 80200)
2115 * 8.2 keeps comments on shared objects in a shared table, so we
2116 * cannot use the dumpComment used for other database objects.
2118 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2120 if (comment && strlen(comment))
2122 resetPQExpBuffer(dbQry);
2125 * Generates warning when loaded into a differently-named
2128 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2129 appendStringLiteralAH(dbQry, comment, fout);
2130 appendPQExpBuffer(dbQry, ";\n");
2132 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2133 dba, false, "COMMENT", SECTION_NONE,
2134 dbQry->data, "", NULL,
2135 &dbDumpId, 1, NULL, NULL);
2140 resetPQExpBuffer(dbQry);
2141 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2142 dumpComment(fout, dbQry->data, NULL, "",
2143 dbCatId, 0, dbDumpId);
2148 /* Dump shared security label. */
2149 if (!no_security_labels && fout->remoteVersion >= 90200)
2151 PQExpBuffer seclabelQry = createPQExpBuffer();
2153 buildShSecLabelQuery(g_conn, "pg_database", dbCatId.oid, seclabelQry);
2154 res = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
2155 resetPQExpBuffer(seclabelQry);
2156 emitShSecLabels(g_conn, res, seclabelQry, "DATABASE", datname);
2157 if (strlen(seclabelQry->data))
2158 ArchiveEntry(fout, dbCatId, createDumpId(), datname, NULL, NULL,
2159 dba, false, "SECURITY LABEL", SECTION_NONE,
2160 seclabelQry->data, "", NULL,
2161 &dbDumpId, 1, NULL, NULL);
2162 destroyPQExpBuffer(seclabelQry);
2165 destroyPQExpBuffer(dbQry);
2166 destroyPQExpBuffer(delQry);
2167 destroyPQExpBuffer(creaQry);
2172 * dumpEncoding: put the correct encoding into the archive
2175 dumpEncoding(Archive *AH)
2177 const char *encname = pg_encoding_to_char(AH->encoding);
2178 PQExpBuffer qry = createPQExpBuffer();
2181 write_msg(NULL, "saving encoding = %s\n", encname);
2183 appendPQExpBuffer(qry, "SET client_encoding = ");
2184 appendStringLiteralAH(qry, encname, AH);
2185 appendPQExpBuffer(qry, ";\n");
2187 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2188 "ENCODING", NULL, NULL, "",
2189 false, "ENCODING", SECTION_PRE_DATA,
2190 qry->data, "", NULL,
2194 destroyPQExpBuffer(qry);
2199 * dumpStdStrings: put the correct escape string behavior into the archive
2202 dumpStdStrings(Archive *AH)
2204 const char *stdstrings = AH->std_strings ? "on" : "off";
2205 PQExpBuffer qry = createPQExpBuffer();
2208 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2211 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2214 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2215 "STDSTRINGS", NULL, NULL, "",
2216 false, "STDSTRINGS", SECTION_PRE_DATA,
2217 qry->data, "", NULL,
2221 destroyPQExpBuffer(qry);
2227 * Collect schema-level data about large objects
2230 getBlobs(Archive *fout)
2232 PQExpBuffer blobQry = createPQExpBuffer();
2234 DumpableObject *bdata;
2239 /* Verbose message */
2241 write_msg(NULL, "reading large objects\n");
2243 /* Make sure we are in proper schema */
2244 selectSourceSchema(fout, "pg_catalog");
2246 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2247 if (fout->remoteVersion >= 90000)
2248 appendPQExpBuffer(blobQry,
2249 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2250 " FROM pg_largeobject_metadata",
2252 else if (fout->remoteVersion >= 70100)
2253 appendPQExpBuffer(blobQry,
2254 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2255 " FROM pg_largeobject");
2257 appendPQExpBuffer(blobQry,
2258 "SELECT oid, NULL::oid, NULL::oid"
2259 " FROM pg_class WHERE relkind = 'l'");
2261 res = ExecuteSqlQuery(fout, blobQry->data, PGRES_TUPLES_OK);
2263 ntups = PQntuples(res);
2267 * Each large object has its own BLOB archive entry.
2269 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2271 for (i = 0; i < ntups; i++)
2273 binfo[i].dobj.objType = DO_BLOB;
2274 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2275 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2276 AssignDumpId(&binfo[i].dobj);
2278 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2279 if (!PQgetisnull(res, i, 1))
2280 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2282 binfo[i].rolname = "";
2283 if (!PQgetisnull(res, i, 2))
2284 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2286 binfo[i].blobacl = NULL;
2290 * If we have any large objects, a "BLOBS" archive entry is needed.
2291 * This is just a placeholder for sorting; it carries no data now.
2293 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2294 bdata->objType = DO_BLOB_DATA;
2295 bdata->catId = nilCatalogId;
2296 AssignDumpId(bdata);
2297 bdata->name = pg_strdup("BLOBS");
2301 destroyPQExpBuffer(blobQry);
2307 * dump the definition (metadata) of the given large object
2310 dumpBlob(Archive *fout, BlobInfo *binfo)
2312 PQExpBuffer cquery = createPQExpBuffer();
2313 PQExpBuffer dquery = createPQExpBuffer();
2315 appendPQExpBuffer(cquery,
2316 "SELECT pg_catalog.lo_create('%s');\n",
2319 appendPQExpBuffer(dquery,
2320 "SELECT pg_catalog.lo_unlink('%s');\n",
2323 ArchiveEntry(fout, binfo->dobj.catId, binfo->dobj.dumpId,
2326 binfo->rolname, false,
2327 "BLOB", SECTION_PRE_DATA,
2328 cquery->data, dquery->data, NULL,
2329 binfo->dobj.dependencies, binfo->dobj.nDeps,
2332 /* set up tag for comment and/or ACL */
2333 resetPQExpBuffer(cquery);
2334 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2336 /* Dump comment if any */
2337 dumpComment(fout, cquery->data,
2338 NULL, binfo->rolname,
2339 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2341 /* Dump security label if any */
2342 dumpSecLabel(fout, cquery->data,
2343 NULL, binfo->rolname,
2344 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2346 /* Dump ACL if any */
2348 dumpACL(fout, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2349 binfo->dobj.name, NULL, cquery->data,
2350 NULL, binfo->rolname, binfo->blobacl);
2352 destroyPQExpBuffer(cquery);
2353 destroyPQExpBuffer(dquery);
2358 * dump the data contents of all large objects
2361 dumpBlobs(Archive *fout, void *arg)
2363 const char *blobQry;
2364 const char *blobFetchQry;
2366 char buf[LOBBUFSIZE];
2372 write_msg(NULL, "saving large objects\n");
2374 /* Make sure we are in proper schema */
2375 selectSourceSchema(fout, "pg_catalog");
2378 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2379 * the already-in-memory dumpable objects instead...
2381 if (fout->remoteVersion >= 90000)
2382 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2383 else if (fout->remoteVersion >= 70100)
2384 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2386 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2388 ExecuteSqlStatement(fout, blobQry);
2390 /* Command to fetch from cursor */
2391 blobFetchQry = "FETCH 1000 IN bloboid";
2396 res = ExecuteSqlQuery(fout, blobFetchQry, PGRES_TUPLES_OK);
2398 /* Process the tuples, if any */
2399 ntups = PQntuples(res);
2400 for (i = 0; i < ntups; i++)
2405 blobOid = atooid(PQgetvalue(res, i, 0));
2407 loFd = lo_open(g_conn, blobOid, INV_READ);
2410 write_msg(NULL, "could not open large object %u: %s",
2411 blobOid, PQerrorMessage(g_conn));
2415 StartBlob(fout, blobOid);
2417 /* Now read it in chunks, sending data to archive */
2420 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2423 write_msg(NULL, "error reading large object %u: %s",
2424 blobOid, PQerrorMessage(g_conn));
2428 WriteData(fout, buf, cnt);
2431 lo_close(g_conn, loFd);
2433 EndBlob(fout, blobOid);
2437 } while (ntups > 0);
2445 binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
2446 PQExpBuffer upgrade_buffer,
2449 PQExpBuffer upgrade_query = createPQExpBuffer();
2451 PGresult *upgrade_res;
2452 Oid pg_type_array_oid;
2454 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2455 appendPQExpBuffer(upgrade_buffer,
2456 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2459 /* we only support old >= 8.3 for binary upgrades */
2460 appendPQExpBuffer(upgrade_query,
2462 "FROM pg_catalog.pg_type "
2463 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2466 upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2468 /* Expecting a single result only */
2469 ntups = PQntuples(upgrade_res);
2472 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2473 "query returned %d rows instead of one: %s\n",
2475 ntups, upgrade_query->data);
2479 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2481 if (OidIsValid(pg_type_array_oid))
2483 appendPQExpBuffer(upgrade_buffer,
2484 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2485 appendPQExpBuffer(upgrade_buffer,
2486 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2490 PQclear(upgrade_res);
2491 destroyPQExpBuffer(upgrade_query);
2495 binary_upgrade_set_type_oids_by_rel_oid(Archive *fout,
2496 PQExpBuffer upgrade_buffer,
2499 PQExpBuffer upgrade_query = createPQExpBuffer();
2501 PGresult *upgrade_res;
2503 bool toast_set = false;
2505 /* we only support old >= 8.3 for binary upgrades */
2506 appendPQExpBuffer(upgrade_query,
2507 "SELECT c.reltype AS crel, t.reltype AS trel "
2508 "FROM pg_catalog.pg_class c "
2509 "LEFT JOIN pg_catalog.pg_class t ON "
2510 " (c.reltoastrelid = t.oid) "
2511 "WHERE c.oid = '%u'::pg_catalog.oid;",
2514 upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2516 /* Expecting a single result only */
2517 ntups = PQntuples(upgrade_res);
2520 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2521 "query returned %d rows instead of one: %s\n",
2523 ntups, upgrade_query->data);
2527 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2529 binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
2532 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2534 /* Toast tables do not have pg_type array rows */
2535 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2536 PQfnumber(upgrade_res, "trel")));
2538 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2539 appendPQExpBuffer(upgrade_buffer,
2540 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2546 PQclear(upgrade_res);
2547 destroyPQExpBuffer(upgrade_query);
2553 binary_upgrade_set_pg_class_oids(Archive *fout,
2554 PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2557 PQExpBuffer upgrade_query = createPQExpBuffer();
2559 PGresult *upgrade_res;
2560 Oid pg_class_reltoastrelid;
2561 Oid pg_class_reltoastidxid;
2563 appendPQExpBuffer(upgrade_query,
2564 "SELECT c.reltoastrelid, t.reltoastidxid "
2565 "FROM pg_catalog.pg_class c LEFT JOIN "
2566 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2567 "WHERE c.oid = '%u'::pg_catalog.oid;",
2570 upgrade_res = ExecuteSqlQuery(fout, upgrade_query->data, PGRES_TUPLES_OK);
2572 /* Expecting a single result only */
2573 ntups = PQntuples(upgrade_res);
2576 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2577 "query returned %d rows instead of one: %s\n",
2579 ntups, upgrade_query->data);
2583 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2584 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2586 appendPQExpBuffer(upgrade_buffer,
2587 "\n-- For binary upgrade, must preserve pg_class oids\n");
2591 appendPQExpBuffer(upgrade_buffer,
2592 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2594 /* only tables have toast tables, not indexes */
2595 if (OidIsValid(pg_class_reltoastrelid))
2598 * One complexity is that the table definition might not require
2599 * the creation of a TOAST table, and the TOAST table might have
2600 * been created long after table creation, when the table was
2601 * loaded with wide data. By setting the TOAST oid we force
2602 * creation of the TOAST heap and TOAST index by the backend so we
2603 * can cleanly copy the files during binary upgrade.
2606 appendPQExpBuffer(upgrade_buffer,
2607 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2608 pg_class_reltoastrelid);
2610 /* every toast table has an index */
2611 appendPQExpBuffer(upgrade_buffer,
2612 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2613 pg_class_reltoastidxid);
2617 appendPQExpBuffer(upgrade_buffer,
2618 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2621 appendPQExpBuffer(upgrade_buffer, "\n");
2623 PQclear(upgrade_res);
2624 destroyPQExpBuffer(upgrade_query);
2628 * If the DumpableObject is a member of an extension, add a suitable
2629 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2632 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2633 DumpableObject *dobj,
2634 const char *objlabel)
2636 DumpableObject *extobj = NULL;
2639 if (!dobj->ext_member)
2643 * Find the parent extension. We could avoid this search if we wanted to
2644 * add a link field to DumpableObject, but the space costs of that would
2645 * be considerable. We assume that member objects could only have a
2646 * direct dependency on their own extension, not any others.
2648 for (i = 0; i < dobj->nDeps; i++)
2650 extobj = findObjectByDumpId(dobj->dependencies[i]);
2651 if (extobj && extobj->objType == DO_EXTENSION)
2657 write_msg(NULL, "could not find parent extension for %s", objlabel);
2661 appendPQExpBuffer(upgrade_buffer,
2662 "\n-- For binary upgrade, handle extension membership the hard way\n");
2663 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2664 fmtId(extobj->name),
2670 * read all namespaces in the system catalogs and return them in the
2671 * NamespaceInfo* structure
2673 * numNamespaces is set to the number of namespaces read in
2676 getNamespaces(Archive *fout, int *numNamespaces)
2682 NamespaceInfo *nsinfo;
2690 * Before 7.3, there are no real namespaces; create two dummy entries, one
2691 * for user stuff and one for system stuff.
2693 if (fout->remoteVersion < 70300)
2695 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2697 nsinfo[0].dobj.objType = DO_NAMESPACE;
2698 nsinfo[0].dobj.catId.tableoid = 0;
2699 nsinfo[0].dobj.catId.oid = 0;
2700 AssignDumpId(&nsinfo[0].dobj);
2701 nsinfo[0].dobj.name = pg_strdup("public");
2702 nsinfo[0].rolname = pg_strdup("");
2703 nsinfo[0].nspacl = pg_strdup("");
2705 selectDumpableNamespace(&nsinfo[0]);
2707 nsinfo[1].dobj.objType = DO_NAMESPACE;
2708 nsinfo[1].dobj.catId.tableoid = 0;
2709 nsinfo[1].dobj.catId.oid = 1;
2710 AssignDumpId(&nsinfo[1].dobj);
2711 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2712 nsinfo[1].rolname = pg_strdup("");
2713 nsinfo[1].nspacl = pg_strdup("");
2715 selectDumpableNamespace(&nsinfo[1]);
2717 g_namespaces = nsinfo;
2718 g_numNamespaces = *numNamespaces = 2;
2723 query = createPQExpBuffer();
2725 /* Make sure we are in proper schema */
2726 selectSourceSchema(fout, "pg_catalog");
2729 * we fetch all namespaces including system ones, so that every object we
2730 * read in can be linked to a containing namespace.
2732 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2733 "(%s nspowner) AS rolname, "
2734 "nspacl FROM pg_namespace",
2737 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2739 ntups = PQntuples(res);
2741 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2743 i_tableoid = PQfnumber(res, "tableoid");
2744 i_oid = PQfnumber(res, "oid");
2745 i_nspname = PQfnumber(res, "nspname");
2746 i_rolname = PQfnumber(res, "rolname");
2747 i_nspacl = PQfnumber(res, "nspacl");
2749 for (i = 0; i < ntups; i++)
2751 nsinfo[i].dobj.objType = DO_NAMESPACE;
2752 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2753 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2754 AssignDumpId(&nsinfo[i].dobj);
2755 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2756 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2757 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2759 /* Decide whether to dump this namespace */
2760 selectDumpableNamespace(&nsinfo[i]);
2762 if (strlen(nsinfo[i].rolname) == 0)
2763 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2764 nsinfo[i].dobj.name);
2768 destroyPQExpBuffer(query);
2770 g_namespaces = nsinfo;
2771 g_numNamespaces = *numNamespaces = ntups;
2778 * given a namespace OID and an object OID, look up the info read by
2781 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2782 * a system object or not. In 7.3 and later there is no guessing.
2784 static NamespaceInfo *
2785 findNamespace(Archive *fout, Oid nsoid, Oid objoid)
2789 if (fout->remoteVersion >= 70300)
2791 for (i = 0; i < g_numNamespaces; i++)
2793 NamespaceInfo *nsinfo = &g_namespaces[i];
2795 if (nsoid == nsinfo->dobj.catId.oid)
2798 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2803 /* This code depends on the layout set up by getNamespaces. */
2804 if (objoid > g_last_builtin_oid)
2805 i = 0; /* user object */
2807 i = 1; /* system object */
2808 return &g_namespaces[i];
2811 return NULL; /* keep compiler quiet */
2816 * read all extensions in the system catalogs and return them in the
2817 * ExtensionInfo* structure
2819 * numExtensions is set to the number of extensions read in
2822 getExtensions(Archive *fout, int *numExtensions)
2828 ExtensionInfo *extinfo;
2833 int i_extrelocatable;
2839 * Before 9.1, there are no extensions.
2841 if (fout->remoteVersion < 90100)
2847 query = createPQExpBuffer();
2849 /* Make sure we are in proper schema */
2850 selectSourceSchema(fout, "pg_catalog");
2852 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2853 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2854 "FROM pg_extension x "
2855 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2857 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2859 ntups = PQntuples(res);
2861 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2863 i_tableoid = PQfnumber(res, "tableoid");
2864 i_oid = PQfnumber(res, "oid");
2865 i_extname = PQfnumber(res, "extname");
2866 i_nspname = PQfnumber(res, "nspname");
2867 i_extrelocatable = PQfnumber(res, "extrelocatable");
2868 i_extversion = PQfnumber(res, "extversion");
2869 i_extconfig = PQfnumber(res, "extconfig");
2870 i_extcondition = PQfnumber(res, "extcondition");
2872 for (i = 0; i < ntups; i++)
2874 extinfo[i].dobj.objType = DO_EXTENSION;
2875 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2876 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2877 AssignDumpId(&extinfo[i].dobj);
2878 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2879 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2880 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2881 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2882 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2883 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2885 /* Decide whether we want to dump it */
2886 selectDumpableExtension(&(extinfo[i]));
2890 destroyPQExpBuffer(query);
2892 *numExtensions = ntups;
2899 * read all types in the system catalogs and return them in the
2900 * TypeInfo* structure
2902 * numTypes is set to the number of types read in
2904 * NB: this must run after getFuncs() because we assume we can do
2908 getTypes(Archive *fout, int *numTypes)
2913 PQExpBuffer query = createPQExpBuffer();
2915 ShellTypeInfo *stinfo;
2931 * we include even the built-in types because those may be used as array
2932 * elements by user-defined types
2934 * we filter out the built-in types when we dump out the types
2936 * same approach for undefined (shell) types and array types
2938 * Note: as of 8.3 we can reliably detect whether a type is an
2939 * auto-generated array type by checking the element type's typarray.
2940 * (Before that the test is capable of generating false positives.) We
2941 * still check for name beginning with '_', though, so as to avoid the
2942 * cost of the subselect probe for all standard types. This would have to
2943 * be revisited if the backend ever allows renaming of array types.
2946 /* Make sure we are in proper schema */
2947 selectSourceSchema(fout, "pg_catalog");
2949 if (fout->remoteVersion >= 80300)
2951 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2953 "(%s typowner) AS rolname, "
2954 "typinput::oid AS typinput, "
2955 "typoutput::oid AS typoutput, typelem, typrelid, "
2956 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2957 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2958 "typtype, typisdefined, "
2959 "typname[0] = '_' AND typelem != 0 AND "
2960 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2964 else if (fout->remoteVersion >= 70300)
2966 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2968 "(%s typowner) AS rolname, "
2969 "typinput::oid AS typinput, "
2970 "typoutput::oid AS typoutput, typelem, typrelid, "
2971 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2972 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2973 "typtype, typisdefined, "
2974 "typname[0] = '_' AND typelem != 0 AS isarray "
2978 else if (fout->remoteVersion >= 70100)
2980 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2981 "0::oid AS typnamespace, "
2982 "(%s typowner) AS rolname, "
2983 "typinput::oid AS typinput, "
2984 "typoutput::oid AS typoutput, typelem, typrelid, "
2985 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2986 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2987 "typtype, typisdefined, "
2988 "typname[0] = '_' AND typelem != 0 AS isarray "
2994 appendPQExpBuffer(query, "SELECT "
2995 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2997 "0::oid AS typnamespace, "
2998 "(%s typowner) AS rolname, "
2999 "typinput::oid AS typinput, "
3000 "typoutput::oid AS typoutput, typelem, typrelid, "
3001 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
3002 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
3003 "typtype, typisdefined, "
3004 "typname[0] = '_' AND typelem != 0 AS isarray "
3009 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3011 ntups = PQntuples(res);
3013 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
3015 i_tableoid = PQfnumber(res, "tableoid");
3016 i_oid = PQfnumber(res, "oid");
3017 i_typname = PQfnumber(res, "typname");
3018 i_typnamespace = PQfnumber(res, "typnamespace");
3019 i_rolname = PQfnumber(res, "rolname");
3020 i_typinput = PQfnumber(res, "typinput");
3021 i_typoutput = PQfnumber(res, "typoutput");
3022 i_typelem = PQfnumber(res, "typelem");
3023 i_typrelid = PQfnumber(res, "typrelid");
3024 i_typrelkind = PQfnumber(res, "typrelkind");
3025 i_typtype = PQfnumber(res, "typtype");
3026 i_typisdefined = PQfnumber(res, "typisdefined");
3027 i_isarray = PQfnumber(res, "isarray");
3029 for (i = 0; i < ntups; i++)
3031 tyinfo[i].dobj.objType = DO_TYPE;
3032 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3033 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3034 AssignDumpId(&tyinfo[i].dobj);
3035 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
3036 tyinfo[i].dobj.namespace =
3038 atooid(PQgetvalue(res, i, i_typnamespace)),
3039 tyinfo[i].dobj.catId.oid);
3040 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3041 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
3042 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
3043 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
3044 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
3045 tyinfo[i].shellType = NULL;
3047 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
3048 tyinfo[i].isDefined = true;
3050 tyinfo[i].isDefined = false;
3052 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
3053 tyinfo[i].isArray = true;
3055 tyinfo[i].isArray = false;
3057 /* Decide whether we want to dump it */
3058 selectDumpableType(&tyinfo[i]);
3061 * If it's a domain, fetch info about its constraints, if any
3063 tyinfo[i].nDomChecks = 0;
3064 tyinfo[i].domChecks = NULL;
3065 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
3066 getDomainConstraints(fout, &(tyinfo[i]));
3069 * If it's a base type, make a DumpableObject representing a shell
3070 * definition of the type. We will need to dump that ahead of the I/O
3071 * functions for the type. Similarly, range types need a shell
3072 * definition in case they have a canonicalize function.
3074 * Note: the shell type doesn't have a catId. You might think it
3075 * should copy the base type's catId, but then it might capture the
3076 * pg_depend entries for the type, which we don't want.
3078 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
3079 tyinfo[i].typtype == TYPTYPE_RANGE))
3081 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3082 stinfo->dobj.objType = DO_SHELL_TYPE;
3083 stinfo->dobj.catId = nilCatalogId;
3084 AssignDumpId(&stinfo->dobj);
3085 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3086 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3087 stinfo->baseType = &(tyinfo[i]);
3088 tyinfo[i].shellType = stinfo;
3091 * Initially mark the shell type as not to be dumped. We'll only
3092 * dump it if the I/O or canonicalize functions need to be dumped;
3093 * this is taken care of while sorting dependencies.
3095 stinfo->dobj.dump = false;
3098 * However, if dumping from pre-7.3, there will be no dependency
3099 * info so we have to fake it here. We only need to worry about
3100 * typinput and typoutput since the other functions only exist
3103 if (fout->remoteVersion < 70300)
3109 typinput = atooid(PQgetvalue(res, i, i_typinput));
3110 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3112 funcInfo = findFuncByOid(typinput);
3113 if (funcInfo && funcInfo->dobj.dump)
3115 /* base type depends on function */
3116 addObjectDependency(&tyinfo[i].dobj,
3117 funcInfo->dobj.dumpId);
3118 /* function depends on shell type */
3119 addObjectDependency(&funcInfo->dobj,
3120 stinfo->dobj.dumpId);
3121 /* mark shell type as to be dumped */
3122 stinfo->dobj.dump = true;
3125 funcInfo = findFuncByOid(typoutput);
3126 if (funcInfo && funcInfo->dobj.dump)
3128 /* base type depends on function */
3129 addObjectDependency(&tyinfo[i].dobj,
3130 funcInfo->dobj.dumpId);
3131 /* function depends on shell type */
3132 addObjectDependency(&funcInfo->dobj,
3133 stinfo->dobj.dumpId);
3134 /* mark shell type as to be dumped */
3135 stinfo->dobj.dump = true;
3140 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3141 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3142 tyinfo[i].dobj.name);
3149 destroyPQExpBuffer(query);
3156 * read all operators in the system catalogs and return them in the
3157 * OprInfo* structure
3159 * numOprs is set to the number of operators read in
3162 getOperators(Archive *fout, int *numOprs)
3167 PQExpBuffer query = createPQExpBuffer();
3178 * find all operators, including builtin operators; we filter out
3179 * system-defined operators at dump-out time.
3182 /* Make sure we are in proper schema */
3183 selectSourceSchema(fout, "pg_catalog");
3185 if (fout->remoteVersion >= 70300)
3187 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3189 "(%s oprowner) AS rolname, "
3191 "oprcode::oid AS oprcode "
3195 else if (fout->remoteVersion >= 70100)
3197 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3198 "0::oid AS oprnamespace, "
3199 "(%s oprowner) AS rolname, "
3201 "oprcode::oid AS oprcode "
3207 appendPQExpBuffer(query, "SELECT "
3208 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3210 "0::oid AS oprnamespace, "
3211 "(%s oprowner) AS rolname, "
3213 "oprcode::oid AS oprcode "
3218 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3220 ntups = PQntuples(res);
3223 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3225 i_tableoid = PQfnumber(res, "tableoid");
3226 i_oid = PQfnumber(res, "oid");
3227 i_oprname = PQfnumber(res, "oprname");
3228 i_oprnamespace = PQfnumber(res, "oprnamespace");
3229 i_rolname = PQfnumber(res, "rolname");
3230 i_oprkind = PQfnumber(res, "oprkind");
3231 i_oprcode = PQfnumber(res, "oprcode");
3233 for (i = 0; i < ntups; i++)
3235 oprinfo[i].dobj.objType = DO_OPERATOR;
3236 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3237 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3238 AssignDumpId(&oprinfo[i].dobj);
3239 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3240 oprinfo[i].dobj.namespace =
3242 atooid(PQgetvalue(res, i, i_oprnamespace)),
3243 oprinfo[i].dobj.catId.oid);
3244 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3245 oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
3246 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3248 /* Decide whether we want to dump it */
3249 selectDumpableObject(&(oprinfo[i].dobj));
3251 if (strlen(oprinfo[i].rolname) == 0)
3252 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3253 oprinfo[i].dobj.name);
3258 destroyPQExpBuffer(query);
3265 * read all collations in the system catalogs and return them in the
3266 * CollInfo* structure
3268 * numCollations is set to the number of collations read in
3271 getCollations(Archive *fout, int *numCollations)
3276 PQExpBuffer query = createPQExpBuffer();
3281 int i_collnamespace;
3284 /* Collations didn't exist pre-9.1 */
3285 if (fout->remoteVersion < 90100)
3292 * find all collations, including builtin collations; we filter out
3293 * system-defined collations at dump-out time.
3296 /* Make sure we are in proper schema */
3297 selectSourceSchema(fout, "pg_catalog");
3299 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3301 "(%s collowner) AS rolname "
3302 "FROM pg_collation",
3305 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3307 ntups = PQntuples(res);
3308 *numCollations = ntups;
3310 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3312 i_tableoid = PQfnumber(res, "tableoid");
3313 i_oid = PQfnumber(res, "oid");
3314 i_collname = PQfnumber(res, "collname");
3315 i_collnamespace = PQfnumber(res, "collnamespace");
3316 i_rolname = PQfnumber(res, "rolname");
3318 for (i = 0; i < ntups; i++)
3320 collinfo[i].dobj.objType = DO_COLLATION;
3321 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3322 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3323 AssignDumpId(&collinfo[i].dobj);
3324 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3325 collinfo[i].dobj.namespace =
3327 atooid(PQgetvalue(res, i, i_collnamespace)),
3328 collinfo[i].dobj.catId.oid);
3329 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3331 /* Decide whether we want to dump it */
3332 selectDumpableObject(&(collinfo[i].dobj));
3337 destroyPQExpBuffer(query);
3344 * read all conversions in the system catalogs and return them in the
3345 * ConvInfo* structure
3347 * numConversions is set to the number of conversions read in
3350 getConversions(Archive *fout, int *numConversions)
3355 PQExpBuffer query = createPQExpBuffer();
3363 /* Conversions didn't exist pre-7.3 */
3364 if (fout->remoteVersion < 70300)
3366 *numConversions = 0;
3371 * find all conversions, including builtin conversions; we filter out
3372 * system-defined conversions at dump-out time.
3375 /* Make sure we are in proper schema */
3376 selectSourceSchema(fout, "pg_catalog");
3378 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3380 "(%s conowner) AS rolname "
3381 "FROM pg_conversion",
3384 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3386 ntups = PQntuples(res);
3387 *numConversions = ntups;
3389 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3391 i_tableoid = PQfnumber(res, "tableoid");
3392 i_oid = PQfnumber(res, "oid");
3393 i_conname = PQfnumber(res, "conname");
3394 i_connamespace = PQfnumber(res, "connamespace");
3395 i_rolname = PQfnumber(res, "rolname");
3397 for (i = 0; i < ntups; i++)
3399 convinfo[i].dobj.objType = DO_CONVERSION;
3400 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3401 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3402 AssignDumpId(&convinfo[i].dobj);
3403 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3404 convinfo[i].dobj.namespace =
3406 atooid(PQgetvalue(res, i, i_connamespace)),
3407 convinfo[i].dobj.catId.oid);
3408 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3410 /* Decide whether we want to dump it */
3411 selectDumpableObject(&(convinfo[i].dobj));
3416 destroyPQExpBuffer(query);
3423 * read all opclasses in the system catalogs and return them in the
3424 * OpclassInfo* structure
3426 * numOpclasses is set to the number of opclasses read in
3429 getOpclasses(Archive *fout, int *numOpclasses)
3434 PQExpBuffer query = createPQExpBuffer();
3435 OpclassInfo *opcinfo;
3443 * find all opclasses, including builtin opclasses; we filter out
3444 * system-defined opclasses at dump-out time.
3447 /* Make sure we are in proper schema */
3448 selectSourceSchema(fout, "pg_catalog");
3450 if (fout->remoteVersion >= 70300)
3452 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3454 "(%s opcowner) AS rolname "
3458 else if (fout->remoteVersion >= 70100)
3460 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3461 "0::oid AS opcnamespace, "
3462 "''::name AS rolname "
3467 appendPQExpBuffer(query, "SELECT "
3468 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3470 "0::oid AS opcnamespace, "
3471 "''::name AS rolname "
3475 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3477 ntups = PQntuples(res);
3478 *numOpclasses = ntups;
3480 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3482 i_tableoid = PQfnumber(res, "tableoid");
3483 i_oid = PQfnumber(res, "oid");
3484 i_opcname = PQfnumber(res, "opcname");
3485 i_opcnamespace = PQfnumber(res, "opcnamespace");
3486 i_rolname = PQfnumber(res, "rolname");
3488 for (i = 0; i < ntups; i++)
3490 opcinfo[i].dobj.objType = DO_OPCLASS;
3491 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3492 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3493 AssignDumpId(&opcinfo[i].dobj);
3494 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3495 opcinfo[i].dobj.namespace =
3497 atooid(PQgetvalue(res, i, i_opcnamespace)),
3498 opcinfo[i].dobj.catId.oid);
3499 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3501 /* Decide whether we want to dump it */
3502 selectDumpableObject(&(opcinfo[i].dobj));
3504 if (fout->remoteVersion >= 70300)
3506 if (strlen(opcinfo[i].rolname) == 0)
3507 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3508 opcinfo[i].dobj.name);
3514 destroyPQExpBuffer(query);
3521 * read all opfamilies in the system catalogs and return them in the
3522 * OpfamilyInfo* structure
3524 * numOpfamilies is set to the number of opfamilies read in
3527 getOpfamilies(Archive *fout, int *numOpfamilies)
3533 OpfamilyInfo *opfinfo;
3540 /* Before 8.3, there is no separate concept of opfamilies */
3541 if (fout->remoteVersion < 80300)
3547 query = createPQExpBuffer();
3550 * find all opfamilies, including builtin opfamilies; we filter out
3551 * system-defined opfamilies at dump-out time.
3554 /* Make sure we are in proper schema */
3555 selectSourceSchema(fout, "pg_catalog");
3557 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3559 "(%s opfowner) AS rolname "
3563 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3565 ntups = PQntuples(res);
3566 *numOpfamilies = ntups;
3568 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3570 i_tableoid = PQfnumber(res, "tableoid");
3571 i_oid = PQfnumber(res, "oid");
3572 i_opfname = PQfnumber(res, "opfname");
3573 i_opfnamespace = PQfnumber(res, "opfnamespace");
3574 i_rolname = PQfnumber(res, "rolname");
3576 for (i = 0; i < ntups; i++)
3578 opfinfo[i].dobj.objType = DO_OPFAMILY;
3579 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3580 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3581 AssignDumpId(&opfinfo[i].dobj);
3582 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3583 opfinfo[i].dobj.namespace =
3585 atooid(PQgetvalue(res, i, i_opfnamespace)),
3586 opfinfo[i].dobj.catId.oid);
3587 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3589 /* Decide whether we want to dump it */
3590 selectDumpableObject(&(opfinfo[i].dobj));
3592 if (fout->remoteVersion >= 70300)
3594 if (strlen(opfinfo[i].rolname) == 0)
3595 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3596 opfinfo[i].dobj.name);
3602 destroyPQExpBuffer(query);
3609 * read all the user-defined aggregates in the system catalogs and
3610 * return them in the AggInfo* structure
3612 * numAggs is set to the number of aggregates read in
3615 getAggregates(Archive *fout, int *numAggs)
3620 PQExpBuffer query = createPQExpBuffer();
3631 /* Make sure we are in proper schema */
3632 selectSourceSchema(fout, "pg_catalog");
3635 * Find all user-defined aggregates. See comment in getFuncs() for the
3636 * rationale behind the filtering logic.
3639 if (fout->remoteVersion >= 80200)
3641 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3642 "pronamespace AS aggnamespace, "
3643 "pronargs, proargtypes, "
3644 "(%s proowner) AS rolname, "
3647 "WHERE proisagg AND ("
3649 "(SELECT oid FROM pg_namespace "
3650 "WHERE nspname = 'pg_catalog')",
3652 if (binary_upgrade && fout->remoteVersion >= 90100)
3653 appendPQExpBuffer(query,
3654 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3655 "classid = 'pg_proc'::regclass AND "
3656 "objid = p.oid AND "
3657 "refclassid = 'pg_extension'::regclass AND "
3659 appendPQExpBuffer(query, ")");
3661 else if (fout->remoteVersion >= 70300)
3663 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3664 "pronamespace AS aggnamespace, "
3665 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3667 "(%s proowner) AS rolname, "
3671 "AND pronamespace != "
3672 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3675 else if (fout->remoteVersion >= 70100)
3677 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3678 "0::oid AS aggnamespace, "
3679 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3680 "aggbasetype AS proargtypes, "
3681 "(%s aggowner) AS rolname, "
3683 "FROM pg_aggregate "
3684 "where oid > '%u'::oid",
3686 g_last_builtin_oid);
3690 appendPQExpBuffer(query, "SELECT "
3691 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3693 "0::oid AS aggnamespace, "
3694 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3695 "aggbasetype AS proargtypes, "
3696 "(%s aggowner) AS rolname, "
3698 "FROM pg_aggregate "
3699 "where oid > '%u'::oid",
3701 g_last_builtin_oid);
3704 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3706 ntups = PQntuples(res);
3709 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3711 i_tableoid = PQfnumber(res, "tableoid");
3712 i_oid = PQfnumber(res, "oid");
3713 i_aggname = PQfnumber(res, "aggname");
3714 i_aggnamespace = PQfnumber(res, "aggnamespace");
3715 i_pronargs = PQfnumber(res, "pronargs");
3716 i_proargtypes = PQfnumber(res, "proargtypes");
3717 i_rolname = PQfnumber(res, "rolname");
3718 i_aggacl = PQfnumber(res, "aggacl");
3720 for (i = 0; i < ntups; i++)
3722 agginfo[i].aggfn.dobj.objType = DO_AGG;
3723 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3724 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3725 AssignDumpId(&agginfo[i].aggfn.dobj);
3726 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3727 agginfo[i].aggfn.dobj.namespace =
3729 atooid(PQgetvalue(res, i, i_aggnamespace)),
3730 agginfo[i].aggfn.dobj.catId.oid);
3731 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3732 if (strlen(agginfo[i].aggfn.rolname) == 0)
3733 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3734 agginfo[i].aggfn.dobj.name);
3735 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3736 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3737 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3738 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3739 if (agginfo[i].aggfn.nargs == 0)
3740 agginfo[i].aggfn.argtypes = NULL;
3743 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3744 if (fout->remoteVersion >= 70300)
3745 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3746 agginfo[i].aggfn.argtypes,
3747 agginfo[i].aggfn.nargs);
3749 /* it's just aggbasetype */
3750 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3753 /* Decide whether we want to dump it */
3754 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3759 destroyPQExpBuffer(query);
3766 * read all the user-defined functions in the system catalogs and
3767 * return them in the FuncInfo* structure
3769 * numFuncs is set to the number of functions read in
3772 getFuncs(Archive *fout, int *numFuncs)
3777 PQExpBuffer query = createPQExpBuffer();
3790 /* Make sure we are in proper schema */
3791 selectSourceSchema(fout, "pg_catalog");
3794 * Find all user-defined functions. Normally we can exclude functions in
3795 * pg_catalog, which is worth doing since there are several thousand of
3796 * 'em. However, there are some extensions that create functions in
3797 * pg_catalog. In normal dumps we can still ignore those --- but in
3798 * binary-upgrade mode, we must dump the member objects of the extension,
3799 * so be sure to fetch any such functions.
3801 * Also, in 9.2 and up, exclude functions that are internally dependent on
3802 * something else, since presumably those will be created as a result of
3803 * creating the something else. This currently only acts to suppress
3804 * constructor functions for range types. Note that this is OK only
3805 * because the constructors don't have any dependencies the range type
3806 * doesn't have; otherwise we might not get creation ordering correct.
3809 if (fout->remoteVersion >= 70300)
3811 appendPQExpBuffer(query,
3812 "SELECT tableoid, oid, proname, prolang, "
3813 "pronargs, proargtypes, prorettype, proacl, "
3815 "(%s proowner) AS rolname "
3817 "WHERE NOT proisagg AND ("
3819 "(SELECT oid FROM pg_namespace "
3820 "WHERE nspname = 'pg_catalog')",
3822 if (fout->remoteVersion >= 90200)
3823 appendPQExpBuffer(query,
3824 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3825 "WHERE classid = 'pg_proc'::regclass AND "
3826 "objid = p.oid AND deptype = 'i')");
3827 if (binary_upgrade && fout->remoteVersion >= 90100)
3828 appendPQExpBuffer(query,
3829 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3830 "classid = 'pg_proc'::regclass AND "
3831 "objid = p.oid AND "
3832 "refclassid = 'pg_extension'::regclass AND "
3834 appendPQExpBuffer(query, ")");
3836 else if (fout->remoteVersion >= 70100)
3838 appendPQExpBuffer(query,
3839 "SELECT tableoid, oid, proname, prolang, "
3840 "pronargs, proargtypes, prorettype, "
3841 "'{=X}' AS proacl, "
3842 "0::oid AS pronamespace, "
3843 "(%s proowner) AS rolname "
3845 "WHERE pg_proc.oid > '%u'::oid",
3847 g_last_builtin_oid);
3851 appendPQExpBuffer(query,
3853 "(SELECT oid FROM pg_class "
3854 " WHERE relname = 'pg_proc') AS tableoid, "
3855 "oid, proname, prolang, "
3856 "pronargs, proargtypes, prorettype, "
3857 "'{=X}' AS proacl, "
3858 "0::oid AS pronamespace, "
3859 "(%s proowner) AS rolname "
3861 "where pg_proc.oid > '%u'::oid",
3863 g_last_builtin_oid);
3866 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
3868 ntups = PQntuples(res);
3872 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3874 i_tableoid = PQfnumber(res, "tableoid");
3875 i_oid = PQfnumber(res, "oid");
3876 i_proname = PQfnumber(res, "proname");
3877 i_pronamespace = PQfnumber(res, "pronamespace");
3878 i_rolname = PQfnumber(res, "rolname");
3879 i_prolang = PQfnumber(res, "prolang");
3880 i_pronargs = PQfnumber(res, "pronargs");
3881 i_proargtypes = PQfnumber(res, "proargtypes");
3882 i_prorettype = PQfnumber(res, "prorettype");
3883 i_proacl = PQfnumber(res, "proacl");
3885 for (i = 0; i < ntups; i++)
3887 finfo[i].dobj.objType = DO_FUNC;
3888 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3889 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3890 AssignDumpId(&finfo[i].dobj);
3891 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3892 finfo[i].dobj.namespace =
3894 atooid(PQgetvalue(res, i, i_pronamespace)),
3895 finfo[i].dobj.catId.oid);
3896 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3897 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3898 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3899 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3900 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3901 if (finfo[i].nargs == 0)
3902 finfo[i].argtypes = NULL;
3905 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3906 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3907 finfo[i].argtypes, finfo[i].nargs);
3910 /* Decide whether we want to dump it */
3911 selectDumpableObject(&(finfo[i].dobj));
3913 if (strlen(finfo[i].rolname) == 0)
3915 "WARNING: owner of function \"%s\" appears to be invalid\n",
3916 finfo[i].dobj.name);
3921 destroyPQExpBuffer(query);
3928 * read all the user-defined tables (no indexes, no catalogs)
3929 * in the system catalogs return them in the TableInfo* structure
3931 * numTables is set to the number of tables read in
3934 getTables(Archive *fout, int *numTables)
3939 PQExpBuffer query = createPQExpBuffer();
3949 int i_relhastriggers;
3955 int i_toastfrozenxid;
3956 int i_relpersistence;
3959 int i_reltablespace;
3961 int i_toastreloptions;
3964 /* Make sure we are in proper schema */
3965 selectSourceSchema(fout, "pg_catalog");
3968 * Find all the tables (including views and sequences).
3970 * We include system catalogs, so that we can work if a user table is
3971 * defined to inherit from a system catalog (pretty weird, but...)
3973 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3974 * (sequence), 'v' (view), or 'c' (composite type).
3976 * Composite-type table entries won't be dumped as such, but we have to
3977 * make a DumpableObject for them so that we can track dependencies of the
3978 * composite type (pg_depend entries for columns of the composite type
3979 * link to the pg_class entry not the pg_type entry).
3981 * Note: in this phase we should collect only a minimal amount of
3982 * information about each table, basically just enough to decide if it is
3983 * interesting. We must fetch all tables in this phase because otherwise
3984 * we cannot correctly identify inherited columns, owned sequences, etc.
3987 if (fout->remoteVersion >= 90100)
3990 * Left join to pick up dependency info linking sequences to their
3991 * owning column, if any (note this dependency is AUTO as of 8.2)
3993 appendPQExpBuffer(query,
3994 "SELECT c.tableoid, c.oid, c.relname, "
3995 "c.relacl, c.relkind, c.relnamespace, "
3996 "(%s c.relowner) AS rolname, "
3997 "c.relchecks, c.relhastriggers, "
3998 "c.relhasindex, c.relhasrules, c.relhasoids, "
3999 "c.relfrozenxid, tc.oid AS toid, "
4000 "tc.relfrozenxid AS tfrozenxid, "
4001 "c.relpersistence, "
4002 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4003 "d.refobjid AS owning_tab, "
4004 "d.refobjsubid AS owning_col, "
4005 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4006 "array_to_string(c.reloptions, ', ') AS reloptions, "
4007 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4009 "LEFT JOIN pg_depend d ON "
4010 "(c.relkind = '%c' AND "
4011 "d.classid = c.tableoid AND d.objid = c.oid AND "
4012 "d.objsubid = 0 AND "
4013 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4014 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4015 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
4019 RELKIND_RELATION, RELKIND_SEQUENCE,
4020 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
4021 RELKIND_FOREIGN_TABLE);
4023 else if (fout->remoteVersion >= 90000)
4026 * Left join to pick up dependency info linking sequences to their
4027 * owning column, if any (note this dependency is AUTO as of 8.2)
4029 appendPQExpBuffer(query,
4030 "SELECT c.tableoid, c.oid, c.relname, "
4031 "c.relacl, c.relkind, c.relnamespace, "
4032 "(%s c.relowner) AS rolname, "
4033 "c.relchecks, c.relhastriggers, "
4034 "c.relhasindex, c.relhasrules, c.relhasoids, "
4035 "c.relfrozenxid, tc.oid AS toid, "
4036 "tc.relfrozenxid AS tfrozenxid, "
4037 "'p' AS relpersistence, "
4038 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
4039 "d.refobjid AS owning_tab, "
4040 "d.refobjsubid AS owning_col, "
4041 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4042 "array_to_string(c.reloptions, ', ') AS reloptions, "
4043 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4045 "LEFT JOIN pg_depend d ON "
4046 "(c.relkind = '%c' AND "
4047 "d.classid = c.tableoid AND d.objid = c.oid AND "
4048 "d.objsubid = 0 AND "
4049 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4050 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4051 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4055 RELKIND_RELATION, RELKIND_SEQUENCE,
4056 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4058 else if (fout->remoteVersion >= 80400)
4061 * Left join to pick up dependency info linking sequences to their
4062 * owning column, if any (note this dependency is AUTO as of 8.2)
4064 appendPQExpBuffer(query,
4065 "SELECT c.tableoid, c.oid, c.relname, "
4066 "c.relacl, c.relkind, c.relnamespace, "
4067 "(%s c.relowner) AS rolname, "
4068 "c.relchecks, c.relhastriggers, "
4069 "c.relhasindex, c.relhasrules, c.relhasoids, "
4070 "c.relfrozenxid, tc.oid AS toid, "
4071 "tc.relfrozenxid AS tfrozenxid, "
4072 "'p' AS relpersistence, "
4073 "NULL AS reloftype, "
4074 "d.refobjid AS owning_tab, "
4075 "d.refobjsubid AS owning_col, "
4076 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4077 "array_to_string(c.reloptions, ', ') AS reloptions, "
4078 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
4080 "LEFT JOIN pg_depend d ON "
4081 "(c.relkind = '%c' AND "
4082 "d.classid = c.tableoid AND d.objid = c.oid AND "
4083 "d.objsubid = 0 AND "
4084 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4085 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4086 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4090 RELKIND_RELATION, RELKIND_SEQUENCE,
4091 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4093 else if (fout->remoteVersion >= 80200)
4096 * Left join to pick up dependency info linking sequences to their
4097 * owning column, if any (note this dependency is AUTO as of 8.2)
4099 appendPQExpBuffer(query,
4100 "SELECT c.tableoid, c.oid, c.relname, "
4101 "c.relacl, c.relkind, c.relnamespace, "
4102 "(%s c.relowner) AS rolname, "
4103 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4104 "c.relhasindex, c.relhasrules, c.relhasoids, "
4105 "c.relfrozenxid, tc.oid AS toid, "
4106 "tc.relfrozenxid AS tfrozenxid, "
4107 "'p' AS relpersistence, "
4108 "NULL AS reloftype, "
4109 "d.refobjid AS owning_tab, "
4110 "d.refobjsubid AS owning_col, "
4111 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4112 "array_to_string(c.reloptions, ', ') AS reloptions, "
4113 "NULL AS toast_reloptions "
4115 "LEFT JOIN pg_depend d ON "
4116 "(c.relkind = '%c' AND "
4117 "d.classid = c.tableoid AND d.objid = c.oid AND "
4118 "d.objsubid = 0 AND "
4119 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4120 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4121 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4125 RELKIND_RELATION, RELKIND_SEQUENCE,
4126 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4128 else if (fout->remoteVersion >= 80000)
4131 * Left join to pick up dependency info linking sequences to their
4132 * owning column, if any
4134 appendPQExpBuffer(query,
4135 "SELECT c.tableoid, c.oid, relname, "
4136 "relacl, relkind, relnamespace, "
4137 "(%s relowner) AS rolname, "
4138 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4139 "relhasindex, relhasrules, relhasoids, "
4140 "0 AS relfrozenxid, "
4143 "'p' AS relpersistence, "
4144 "NULL AS reloftype, "
4145 "d.refobjid AS owning_tab, "
4146 "d.refobjsubid AS owning_col, "
4147 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4148 "NULL AS reloptions, "
4149 "NULL AS toast_reloptions "
4151 "LEFT JOIN pg_depend d ON "
4152 "(c.relkind = '%c' AND "
4153 "d.classid = c.tableoid AND d.objid = c.oid AND "
4154 "d.objsubid = 0 AND "
4155 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4156 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4160 RELKIND_RELATION, RELKIND_SEQUENCE,
4161 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4163 else if (fout->remoteVersion >= 70300)
4166 * Left join to pick up dependency info linking sequences to their
4167 * owning column, if any
4169 appendPQExpBuffer(query,
4170 "SELECT c.tableoid, c.oid, relname, "
4171 "relacl, relkind, relnamespace, "
4172 "(%s relowner) AS rolname, "
4173 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4174 "relhasindex, relhasrules, relhasoids, "
4175 "0 AS relfrozenxid, "
4178 "'p' AS relpersistence, "
4179 "NULL AS reloftype, "
4180 "d.refobjid AS owning_tab, "
4181 "d.refobjsubid AS owning_col, "
4182 "NULL AS reltablespace, "
4183 "NULL AS reloptions, "
4184 "NULL AS toast_reloptions "
4186 "LEFT JOIN pg_depend d ON "
4187 "(c.relkind = '%c' AND "
4188 "d.classid = c.tableoid AND d.objid = c.oid AND "
4189 "d.objsubid = 0 AND "
4190 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4191 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4195 RELKIND_RELATION, RELKIND_SEQUENCE,
4196 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4198 else if (fout->remoteVersion >= 70200)
4200 appendPQExpBuffer(query,
4201 "SELECT tableoid, oid, relname, relacl, relkind, "
4202 "0::oid AS relnamespace, "
4203 "(%s relowner) AS rolname, "
4204 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4205 "relhasindex, relhasrules, relhasoids, "
4206 "0 AS relfrozenxid, "
4209 "'p' AS relpersistence, "
4210 "NULL AS reloftype, "
4211 "NULL::oid AS owning_tab, "
4212 "NULL::int4 AS owning_col, "
4213 "NULL AS reltablespace, "
4214 "NULL AS reloptions, "
4215 "NULL AS toast_reloptions "
4217 "WHERE relkind IN ('%c', '%c', '%c') "
4220 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4222 else if (fout->remoteVersion >= 70100)
4224 /* all tables have oids in 7.1 */
4225 appendPQExpBuffer(query,
4226 "SELECT tableoid, oid, relname, relacl, relkind, "
4227 "0::oid AS relnamespace, "
4228 "(%s relowner) AS rolname, "
4229 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4230 "relhasindex, relhasrules, "
4231 "'t'::bool AS relhasoids, "
4232 "0 AS relfrozenxid, "
4235 "'p' AS relpersistence, "
4236 "NULL AS reloftype, "
4237 "NULL::oid AS owning_tab, "
4238 "NULL::int4 AS owning_col, "
4239 "NULL AS reltablespace, "
4240 "NULL AS reloptions, "
4241 "NULL AS toast_reloptions "
4243 "WHERE relkind IN ('%c', '%c', '%c') "
4246 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4251 * Before 7.1, view relkind was not set to 'v', so we must check if we
4252 * have a view by looking for a rule in pg_rewrite.
4254 appendPQExpBuffer(query,
4256 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4257 "oid, relname, relacl, "
4258 "CASE WHEN relhasrules and relkind = 'r' "
4259 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4260 " r.ev_class = c.oid AND r.ev_type = '1') "
4261 "THEN '%c'::\"char\" "
4262 "ELSE relkind END AS relkind,"
4263 "0::oid AS relnamespace, "
4264 "(%s relowner) AS rolname, "
4265 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4266 "relhasindex, relhasrules, "
4267 "'t'::bool AS relhasoids, "
4268 "0 as relfrozenxid, "
4271 "'p' AS relpersistence, "
4272 "NULL AS reloftype, "
4273 "NULL::oid AS owning_tab, "
4274 "NULL::int4 AS owning_col, "
4275 "NULL AS reltablespace, "
4276 "NULL AS reloptions, "
4277 "NULL AS toast_reloptions "
4279 "WHERE relkind IN ('%c', '%c') "
4283 RELKIND_RELATION, RELKIND_SEQUENCE);
4286 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4288 ntups = PQntuples(res);
4293 * Extract data from result and lock dumpable tables. We do the locking
4294 * before anything else, to minimize the window wherein a table could
4295 * disappear under us.
4297 * Note that we have to save info about all tables here, even when dumping
4298 * only one, because we don't yet know which tables might be inheritance
4299 * ancestors of the target table.
4301 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4303 i_reltableoid = PQfnumber(res, "tableoid");
4304 i_reloid = PQfnumber(res, "oid");
4305 i_relname = PQfnumber(res, "relname");
4306 i_relnamespace = PQfnumber(res, "relnamespace");
4307 i_relacl = PQfnumber(res, "relacl");
4308 i_relkind = PQfnumber(res, "relkind");
4309 i_rolname = PQfnumber(res, "rolname");
4310 i_relchecks = PQfnumber(res, "relchecks");
4311 i_relhastriggers = PQfnumber(res, "relhastriggers");
4312 i_relhasindex = PQfnumber(res, "relhasindex");
4313 i_relhasrules = PQfnumber(res, "relhasrules");
4314 i_relhasoids = PQfnumber(res, "relhasoids");
4315 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4316 i_toastoid = PQfnumber(res, "toid");
4317 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4318 i_relpersistence = PQfnumber(res, "relpersistence");
4319 i_owning_tab = PQfnumber(res, "owning_tab");
4320 i_owning_col = PQfnumber(res, "owning_col");
4321 i_reltablespace = PQfnumber(res, "reltablespace");
4322 i_reloptions = PQfnumber(res, "reloptions");
4323 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4324 i_reloftype = PQfnumber(res, "reloftype");
4326 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4329 * Arrange to fail instead of waiting forever for a table lock.
4331 * NB: this coding assumes that the only queries issued within the
4332 * following loop are LOCK TABLEs; else the timeout may be undesirably
4333 * applied to other things too.
4335 resetPQExpBuffer(query);
4336 appendPQExpBuffer(query, "SET statement_timeout = ");
4337 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
4338 ExecuteSqlStatement(fout, query->data);
4341 for (i = 0; i < ntups; i++)
4343 tblinfo[i].dobj.objType = DO_TABLE;
4344 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4345 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4346 AssignDumpId(&tblinfo[i].dobj);
4347 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4348 tblinfo[i].dobj.namespace =
4350 atooid(PQgetvalue(res, i, i_relnamespace)),
4351 tblinfo[i].dobj.catId.oid);
4352 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4353 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4354 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4355 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4356 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4357 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4358 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4359 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4360 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4361 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4362 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4363 if (PQgetisnull(res, i, i_reloftype))
4364 tblinfo[i].reloftype = NULL;
4366 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4367 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4368 if (PQgetisnull(res, i, i_owning_tab))
4370 tblinfo[i].owning_tab = InvalidOid;
4371 tblinfo[i].owning_col = 0;
4375 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4376 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4378 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4379 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4380 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4382 /* other fields were zeroed above */
4385 * Decide whether we want to dump this table.
4387 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4388 tblinfo[i].dobj.dump = false;
4390 selectDumpableTable(&tblinfo[i]);
4391 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4394 * Read-lock target tables to make sure they aren't DROPPED or altered
4395 * in schema before we get around to dumping them.
4397 * Note that we don't explicitly lock parents of the target tables; we
4398 * assume our lock on the child is enough to prevent schema
4399 * alterations to parent tables.
4401 * NOTE: it'd be kinda nice to lock other relations too, not only
4402 * plain tables, but the backend doesn't presently allow that.
4404 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4406 resetPQExpBuffer(query);
4407 appendPQExpBuffer(query,
4408 "LOCK TABLE %s IN ACCESS SHARE MODE",
4409 fmtQualifiedId(fout,
4410 tblinfo[i].dobj.namespace->dobj.name,
4411 tblinfo[i].dobj.name));
4412 ExecuteSqlStatement(fout, query->data);
4415 /* Emit notice if join for owner failed */
4416 if (strlen(tblinfo[i].rolname) == 0)
4417 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4418 tblinfo[i].dobj.name);
4421 if (lockWaitTimeout && fout->remoteVersion >= 70300)
4423 ExecuteSqlStatement(fout, "SET statement_timeout = 0");
4429 * Force sequences that are "owned" by table columns to be dumped whenever
4430 * their owning table is being dumped.
4432 for (i = 0; i < ntups; i++)
4434 TableInfo *seqinfo = &tblinfo[i];
4437 if (!OidIsValid(seqinfo->owning_tab))
4438 continue; /* not an owned sequence */
4439 if (seqinfo->dobj.dump)
4440 continue; /* no need to search */
4442 /* can't use findTableByOid yet, unfortunately */
4443 for (j = 0; j < ntups; j++)
4445 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4447 if (tblinfo[j].dobj.dump)
4449 seqinfo->interesting = true;
4450 seqinfo->dobj.dump = true;
4457 destroyPQExpBuffer(query);
4464 * read all the inheritance information
4465 * from the system catalogs return them in the InhInfo* structure
4467 * numInherits is set to the number of pairs read in
4470 getInherits(Archive *fout, int *numInherits)
4475 PQExpBuffer query = createPQExpBuffer();
4481 /* Make sure we are in proper schema */
4482 selectSourceSchema(fout, "pg_catalog");
4484 /* find all the inheritance information */
4486 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4488 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4490 ntups = PQntuples(res);
4492 *numInherits = ntups;
4494 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4496 i_inhrelid = PQfnumber(res, "inhrelid");
4497 i_inhparent = PQfnumber(res, "inhparent");
4499 for (i = 0; i < ntups; i++)
4501 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4502 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4507 destroyPQExpBuffer(query);
4514 * get information about every index on a dumpable table
4516 * Note: index data is not returned directly to the caller, but it
4517 * does get entered into the DumpableObject tables.
4520 getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
4524 PQExpBuffer query = createPQExpBuffer();
4527 ConstraintInfo *constrinfo;
4546 for (i = 0; i < numTables; i++)
4548 TableInfo *tbinfo = &tblinfo[i];
4550 /* Only plain tables have indexes */
4551 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4554 /* Ignore indexes of tables not to be dumped */
4555 if (!tbinfo->dobj.dump)
4559 write_msg(NULL, "reading indexes for table \"%s\"\n",
4562 /* Make sure we are in proper schema so indexdef is right */
4563 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4566 * The point of the messy-looking outer join is to find a constraint
4567 * that is related by an internal dependency link to the index. If we
4568 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4569 * assume an index won't have more than one internal dependency.
4571 * As of 9.0 we don't need to look at pg_depend but can check for a
4572 * match to pg_constraint.conindid. The check on conrelid is
4573 * redundant but useful because that column is indexed while conindid
4576 resetPQExpBuffer(query);
4577 if (fout->remoteVersion >= 90000)
4579 appendPQExpBuffer(query,
4580 "SELECT t.tableoid, t.oid, "
4581 "t.relname AS indexname, "
4582 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4583 "t.relnatts AS indnkeys, "
4584 "i.indkey, i.indisclustered, "
4585 "c.contype, c.conname, "
4586 "c.condeferrable, c.condeferred, "
4587 "c.tableoid AS contableoid, "
4589 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4590 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4591 "array_to_string(t.reloptions, ', ') AS options "
4592 "FROM pg_catalog.pg_index i "
4593 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4594 "LEFT JOIN pg_catalog.pg_constraint c "
4595 "ON (i.indrelid = c.conrelid AND "
4596 "i.indexrelid = c.conindid AND "
4597 "c.contype IN ('p','u','x')) "
4598 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4599 "ORDER BY indexname",
4600 tbinfo->dobj.catId.oid);
4602 else if (fout->remoteVersion >= 80200)
4604 appendPQExpBuffer(query,
4605 "SELECT t.tableoid, t.oid, "
4606 "t.relname AS indexname, "
4607 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4608 "t.relnatts AS indnkeys, "
4609 "i.indkey, i.indisclustered, "
4610 "c.contype, c.conname, "
4611 "c.condeferrable, c.condeferred, "
4612 "c.tableoid AS contableoid, "
4615 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4616 "array_to_string(t.reloptions, ', ') AS options "
4617 "FROM pg_catalog.pg_index i "
4618 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4619 "LEFT JOIN pg_catalog.pg_depend d "
4620 "ON (d.classid = t.tableoid "
4621 "AND d.objid = t.oid "
4622 "AND d.deptype = 'i') "
4623 "LEFT JOIN pg_catalog.pg_constraint c "
4624 "ON (d.refclassid = c.tableoid "
4625 "AND d.refobjid = c.oid) "
4626 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4627 "ORDER BY indexname",
4628 tbinfo->dobj.catId.oid);
4630 else if (fout->remoteVersion >= 80000)
4632 appendPQExpBuffer(query,
4633 "SELECT t.tableoid, t.oid, "
4634 "t.relname AS indexname, "
4635 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4636 "t.relnatts AS indnkeys, "
4637 "i.indkey, i.indisclustered, "
4638 "c.contype, c.conname, "
4639 "c.condeferrable, c.condeferred, "
4640 "c.tableoid AS contableoid, "
4643 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4645 "FROM pg_catalog.pg_index i "
4646 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4647 "LEFT JOIN pg_catalog.pg_depend d "
4648 "ON (d.classid = t.tableoid "
4649 "AND d.objid = t.oid "
4650 "AND d.deptype = 'i') "
4651 "LEFT JOIN pg_catalog.pg_constraint c "
4652 "ON (d.refclassid = c.tableoid "
4653 "AND d.refobjid = c.oid) "
4654 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4655 "ORDER BY indexname",
4656 tbinfo->dobj.catId.oid);
4658 else if (fout->remoteVersion >= 70300)
4660 appendPQExpBuffer(query,
4661 "SELECT t.tableoid, t.oid, "
4662 "t.relname AS indexname, "
4663 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4664 "t.relnatts AS indnkeys, "
4665 "i.indkey, i.indisclustered, "
4666 "c.contype, c.conname, "
4667 "c.condeferrable, c.condeferred, "
4668 "c.tableoid AS contableoid, "
4671 "NULL AS tablespace, "
4673 "FROM pg_catalog.pg_index i "
4674 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4675 "LEFT JOIN pg_catalog.pg_depend d "
4676 "ON (d.classid = t.tableoid "
4677 "AND d.objid = t.oid "
4678 "AND d.deptype = 'i') "
4679 "LEFT JOIN pg_catalog.pg_constraint c "
4680 "ON (d.refclassid = c.tableoid "
4681 "AND d.refobjid = c.oid) "
4682 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4683 "ORDER BY indexname",
4684 tbinfo->dobj.catId.oid);
4686 else if (fout->remoteVersion >= 70100)
4688 appendPQExpBuffer(query,
4689 "SELECT t.tableoid, t.oid, "
4690 "t.relname AS indexname, "
4691 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4692 "t.relnatts AS indnkeys, "
4693 "i.indkey, false AS indisclustered, "
4694 "CASE WHEN i.indisprimary THEN 'p'::char "
4695 "ELSE '0'::char END AS contype, "
4696 "t.relname AS conname, "
4697 "false AS condeferrable, "
4698 "false AS condeferred, "
4699 "0::oid AS contableoid, "
4702 "NULL AS tablespace, "
4704 "FROM pg_index i, pg_class t "
4705 "WHERE t.oid = i.indexrelid "
4706 "AND i.indrelid = '%u'::oid "
4707 "ORDER BY indexname",
4708 tbinfo->dobj.catId.oid);
4712 appendPQExpBuffer(query,
4714 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4716 "t.relname AS indexname, "
4717 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4718 "t.relnatts AS indnkeys, "
4719 "i.indkey, false AS indisclustered, "
4720 "CASE WHEN i.indisprimary THEN 'p'::char "
4721 "ELSE '0'::char END AS contype, "
4722 "t.relname AS conname, "
4723 "false AS condeferrable, "
4724 "false AS condeferred, "
4725 "0::oid AS contableoid, "
4728 "NULL AS tablespace, "
4730 "FROM pg_index i, pg_class t "
4731 "WHERE t.oid = i.indexrelid "
4732 "AND i.indrelid = '%u'::oid "
4733 "ORDER BY indexname",
4734 tbinfo->dobj.catId.oid);
4737 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4739 ntups = PQntuples(res);
4741 i_tableoid = PQfnumber(res, "tableoid");
4742 i_oid = PQfnumber(res, "oid");
4743 i_indexname = PQfnumber(res, "indexname");
4744 i_indexdef = PQfnumber(res, "indexdef");
4745 i_indnkeys = PQfnumber(res, "indnkeys");
4746 i_indkey = PQfnumber(res, "indkey");
4747 i_indisclustered = PQfnumber(res, "indisclustered");
4748 i_contype = PQfnumber(res, "contype");
4749 i_conname = PQfnumber(res, "conname");
4750 i_condeferrable = PQfnumber(res, "condeferrable");
4751 i_condeferred = PQfnumber(res, "condeferred");
4752 i_contableoid = PQfnumber(res, "contableoid");
4753 i_conoid = PQfnumber(res, "conoid");
4754 i_condef = PQfnumber(res, "condef");
4755 i_tablespace = PQfnumber(res, "tablespace");
4756 i_options = PQfnumber(res, "options");
4758 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4759 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4761 for (j = 0; j < ntups; j++)
4765 indxinfo[j].dobj.objType = DO_INDEX;
4766 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4767 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4768 AssignDumpId(&indxinfo[j].dobj);
4769 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4770 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4771 indxinfo[j].indextable = tbinfo;
4772 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4773 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4774 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4775 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4778 * In pre-7.4 releases, indkeys may contain more entries than
4779 * indnkeys says (since indnkeys will be 1 for a functional
4780 * index). We don't actually care about this case since we don't
4781 * examine indkeys except for indexes associated with PRIMARY and
4782 * UNIQUE constraints, which are never functional indexes. But we
4783 * have to allocate enough space to keep parseOidArray from
4786 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4787 parseOidArray(PQgetvalue(res, j, i_indkey),
4788 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4789 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4790 contype = *(PQgetvalue(res, j, i_contype));
4792 if (contype == 'p' || contype == 'u' || contype == 'x')
4795 * If we found a constraint matching the index, create an
4798 * In a pre-7.3 database, we take this path iff the index was
4799 * marked indisprimary.
4801 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4802 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4803 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4804 AssignDumpId(&constrinfo[j].dobj);
4805 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4806 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4807 constrinfo[j].contable = tbinfo;
4808 constrinfo[j].condomain = NULL;
4809 constrinfo[j].contype = contype;
4811 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4813 constrinfo[j].condef = NULL;
4814 constrinfo[j].confrelid = InvalidOid;
4815 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4816 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4817 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4818 constrinfo[j].conislocal = true;
4819 constrinfo[j].separate = true;
4821 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4823 /* If pre-7.3 DB, better make sure table comes first */
4824 addObjectDependency(&constrinfo[j].dobj,
4825 tbinfo->dobj.dumpId);
4829 /* Plain secondary index */
4830 indxinfo[j].indexconstraint = 0;
4837 destroyPQExpBuffer(query);
4843 * Get info about constraints on dumpable tables.
4845 * Currently handles foreign keys only.
4846 * Unique and primary key constraints are handled with indexes,
4847 * while check constraints are processed in getTableAttrs().
4850 getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
4854 ConstraintInfo *constrinfo;
4864 /* pg_constraint was created in 7.3, so nothing to do if older */
4865 if (fout->remoteVersion < 70300)
4868 query = createPQExpBuffer();
4870 for (i = 0; i < numTables; i++)
4872 TableInfo *tbinfo = &tblinfo[i];
4874 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4878 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4882 * select table schema to ensure constraint expr is qualified if
4885 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
4887 resetPQExpBuffer(query);
4888 appendPQExpBuffer(query,
4889 "SELECT tableoid, oid, conname, confrelid, "
4890 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4891 "FROM pg_catalog.pg_constraint "
4892 "WHERE conrelid = '%u'::pg_catalog.oid "
4893 "AND contype = 'f'",
4894 tbinfo->dobj.catId.oid);
4895 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4897 ntups = PQntuples(res);
4899 i_contableoid = PQfnumber(res, "tableoid");
4900 i_conoid = PQfnumber(res, "oid");
4901 i_conname = PQfnumber(res, "conname");
4902 i_confrelid = PQfnumber(res, "confrelid");
4903 i_condef = PQfnumber(res, "condef");
4905 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4907 for (j = 0; j < ntups; j++)
4909 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4910 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4911 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4912 AssignDumpId(&constrinfo[j].dobj);
4913 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4914 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4915 constrinfo[j].contable = tbinfo;
4916 constrinfo[j].condomain = NULL;
4917 constrinfo[j].contype = 'f';
4918 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4919 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4920 constrinfo[j].conindex = 0;
4921 constrinfo[j].condeferrable = false;
4922 constrinfo[j].condeferred = false;
4923 constrinfo[j].conislocal = true;
4924 constrinfo[j].separate = true;
4930 destroyPQExpBuffer(query);
4934 * getDomainConstraints
4936 * Get info about constraints on a domain.
4939 getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
4942 ConstraintInfo *constrinfo;
4951 /* pg_constraint was created in 7.3, so nothing to do if older */
4952 if (fout->remoteVersion < 70300)
4956 * select appropriate schema to ensure names in constraint are properly
4959 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
4961 query = createPQExpBuffer();
4963 if (fout->remoteVersion >= 90100)
4964 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4965 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4967 "FROM pg_catalog.pg_constraint "
4968 "WHERE contypid = '%u'::pg_catalog.oid "
4970 tyinfo->dobj.catId.oid);
4972 else if (fout->remoteVersion >= 70400)
4973 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4974 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4975 "true as convalidated "
4976 "FROM pg_catalog.pg_constraint "
4977 "WHERE contypid = '%u'::pg_catalog.oid "
4979 tyinfo->dobj.catId.oid);
4981 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4982 "'CHECK (' || consrc || ')' AS consrc, "
4983 "true as convalidated "
4984 "FROM pg_catalog.pg_constraint "
4985 "WHERE contypid = '%u'::pg_catalog.oid "
4987 tyinfo->dobj.catId.oid);
4989 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4991 ntups = PQntuples(res);
4993 i_tableoid = PQfnumber(res, "tableoid");
4994 i_oid = PQfnumber(res, "oid");
4995 i_conname = PQfnumber(res, "conname");
4996 i_consrc = PQfnumber(res, "consrc");
4998 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
5000 tyinfo->nDomChecks = ntups;
5001 tyinfo->domChecks = constrinfo;
5003 for (i = 0; i < ntups; i++)
5005 bool validated = PQgetvalue(res, i, 4)[0] == 't';
5007 constrinfo[i].dobj.objType = DO_CONSTRAINT;
5008 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5009 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5010 AssignDumpId(&constrinfo[i].dobj);
5011 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
5012 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
5013 constrinfo[i].contable = NULL;
5014 constrinfo[i].condomain = tyinfo;
5015 constrinfo[i].contype = 'c';
5016 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
5017 constrinfo[i].confrelid = InvalidOid;
5018 constrinfo[i].conindex = 0;
5019 constrinfo[i].condeferrable = false;
5020 constrinfo[i].condeferred = false;
5021 constrinfo[i].conislocal = true;
5023 constrinfo[i].separate = !validated;
5026 * Make the domain depend on the constraint, ensuring it won't be
5027 * output till any constraint dependencies are OK. If the constraint
5028 * has not been validated, it's going to be dumped after the domain
5029 * anyway, so this doesn't matter.
5032 addObjectDependency(&tyinfo->dobj,
5033 constrinfo[i].dobj.dumpId);
5038 destroyPQExpBuffer(query);
5043 * get basic information about every rule in the system
5045 * numRules is set to the number of rules read in
5048 getRules(Archive *fout, int *numRules)
5053 PQExpBuffer query = createPQExpBuffer();
5063 /* Make sure we are in proper schema */
5064 selectSourceSchema(fout, "pg_catalog");
5066 if (fout->remoteVersion >= 80300)
5068 appendPQExpBuffer(query, "SELECT "
5069 "tableoid, oid, rulename, "
5070 "ev_class AS ruletable, ev_type, is_instead, "
5075 else if (fout->remoteVersion >= 70100)
5077 appendPQExpBuffer(query, "SELECT "
5078 "tableoid, oid, rulename, "
5079 "ev_class AS ruletable, ev_type, is_instead, "
5080 "'O'::char AS ev_enabled "
5086 appendPQExpBuffer(query, "SELECT "
5087 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
5089 "ev_class AS ruletable, ev_type, is_instead, "
5090 "'O'::char AS ev_enabled "
5095 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5097 ntups = PQntuples(res);
5101 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5103 i_tableoid = PQfnumber(res, "tableoid");
5104 i_oid = PQfnumber(res, "oid");
5105 i_rulename = PQfnumber(res, "rulename");
5106 i_ruletable = PQfnumber(res, "ruletable");
5107 i_ev_type = PQfnumber(res, "ev_type");
5108 i_is_instead = PQfnumber(res, "is_instead");
5109 i_ev_enabled = PQfnumber(res, "ev_enabled");
5111 for (i = 0; i < ntups; i++)
5115 ruleinfo[i].dobj.objType = DO_RULE;
5116 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5117 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5118 AssignDumpId(&ruleinfo[i].dobj);
5119 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5120 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5121 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5122 if (ruleinfo[i].ruletable == NULL)
5124 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5126 ruleinfo[i].dobj.catId.oid);
5129 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5130 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5131 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5132 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5133 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5134 if (ruleinfo[i].ruletable)
5137 * If the table is a view, force its ON SELECT rule to be sorted
5138 * before the view itself --- this ensures that any dependencies
5139 * for the rule affect the table's positioning. Other rules are
5140 * forced to appear after their table.
5142 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5143 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5145 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5146 ruleinfo[i].dobj.dumpId);
5147 /* We'll merge the rule into CREATE VIEW, if possible */
5148 ruleinfo[i].separate = false;
5152 addObjectDependency(&ruleinfo[i].dobj,
5153 ruleinfo[i].ruletable->dobj.dumpId);
5154 ruleinfo[i].separate = true;
5158 ruleinfo[i].separate = true;
5163 destroyPQExpBuffer(query);
5170 * get information about every trigger on a dumpable table
5172 * Note: trigger data is not returned directly to the caller, but it
5173 * does get entered into the DumpableObject tables.
5176 getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
5180 PQExpBuffer query = createPQExpBuffer();
5182 TriggerInfo *tginfo;
5200 for (i = 0; i < numTables; i++)
5202 TableInfo *tbinfo = &tblinfo[i];
5204 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5208 write_msg(NULL, "reading triggers for table \"%s\"\n",
5212 * select table schema to ensure regproc name is qualified if needed
5214 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5216 resetPQExpBuffer(query);
5217 if (fout->remoteVersion >= 90000)
5220 * NB: think not to use pretty=true in pg_get_triggerdef. It
5221 * could result in non-forward-compatible dumps of WHEN clauses
5222 * due to under-parenthesization.
5224 appendPQExpBuffer(query,
5226 "tgfoid::pg_catalog.regproc AS tgfname, "
5227 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5228 "tgenabled, tableoid, oid "
5229 "FROM pg_catalog.pg_trigger t "
5230 "WHERE tgrelid = '%u'::pg_catalog.oid "
5231 "AND NOT tgisinternal",
5232 tbinfo->dobj.catId.oid);
5234 else if (fout->remoteVersion >= 80300)
5237 * We ignore triggers that are tied to a foreign-key constraint
5239 appendPQExpBuffer(query,
5241 "tgfoid::pg_catalog.regproc AS tgfname, "
5242 "tgtype, tgnargs, tgargs, tgenabled, "
5243 "tgisconstraint, tgconstrname, tgdeferrable, "
5244 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5245 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5246 "FROM pg_catalog.pg_trigger t "
5247 "WHERE tgrelid = '%u'::pg_catalog.oid "
5248 "AND tgconstraint = 0",
5249 tbinfo->dobj.catId.oid);
5251 else if (fout->remoteVersion >= 70300)
5254 * We ignore triggers that are tied to a foreign-key constraint,
5255 * but in these versions we have to grovel through pg_constraint
5258 appendPQExpBuffer(query,
5260 "tgfoid::pg_catalog.regproc AS tgfname, "
5261 "tgtype, tgnargs, tgargs, tgenabled, "
5262 "tgisconstraint, tgconstrname, tgdeferrable, "
5263 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5264 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5265 "FROM pg_catalog.pg_trigger t "
5266 "WHERE tgrelid = '%u'::pg_catalog.oid "
5267 "AND (NOT tgisconstraint "
5269 " (SELECT 1 FROM pg_catalog.pg_depend d "
5270 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5271 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5272 tbinfo->dobj.catId.oid);
5274 else if (fout->remoteVersion >= 70100)
5276 appendPQExpBuffer(query,
5277 "SELECT tgname, tgfoid::regproc AS tgfname, "
5278 "tgtype, tgnargs, tgargs, tgenabled, "
5279 "tgisconstraint, tgconstrname, tgdeferrable, "
5280 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5281 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5282 " AS tgconstrrelname "
5284 "WHERE tgrelid = '%u'::oid",
5285 tbinfo->dobj.catId.oid);
5289 appendPQExpBuffer(query,
5290 "SELECT tgname, tgfoid::regproc AS tgfname, "
5291 "tgtype, tgnargs, tgargs, tgenabled, "
5292 "tgisconstraint, tgconstrname, tgdeferrable, "
5293 "tgconstrrelid, tginitdeferred, "
5294 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5296 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5297 " AS tgconstrrelname "
5299 "WHERE tgrelid = '%u'::oid",
5300 tbinfo->dobj.catId.oid);
5302 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5304 ntups = PQntuples(res);
5306 i_tableoid = PQfnumber(res, "tableoid");
5307 i_oid = PQfnumber(res, "oid");
5308 i_tgname = PQfnumber(res, "tgname");
5309 i_tgfname = PQfnumber(res, "tgfname");
5310 i_tgtype = PQfnumber(res, "tgtype");
5311 i_tgnargs = PQfnumber(res, "tgnargs");
5312 i_tgargs = PQfnumber(res, "tgargs");
5313 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5314 i_tgconstrname = PQfnumber(res, "tgconstrname");
5315 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5316 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5317 i_tgenabled = PQfnumber(res, "tgenabled");
5318 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5319 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5320 i_tgdef = PQfnumber(res, "tgdef");
5322 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5324 for (j = 0; j < ntups; j++)
5326 tginfo[j].dobj.objType = DO_TRIGGER;
5327 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5328 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5329 AssignDumpId(&tginfo[j].dobj);
5330 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5331 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5332 tginfo[j].tgtable = tbinfo;
5333 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5336 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5338 /* remaining fields are not valid if we have tgdef */
5339 tginfo[j].tgfname = NULL;
5340 tginfo[j].tgtype = 0;
5341 tginfo[j].tgnargs = 0;
5342 tginfo[j].tgargs = NULL;
5343 tginfo[j].tgisconstraint = false;
5344 tginfo[j].tgdeferrable = false;
5345 tginfo[j].tginitdeferred = false;
5346 tginfo[j].tgconstrname = NULL;
5347 tginfo[j].tgconstrrelid = InvalidOid;
5348 tginfo[j].tgconstrrelname = NULL;
5352 tginfo[j].tgdef = NULL;
5354 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5355 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5356 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5357 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5358 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5359 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5360 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5362 if (tginfo[j].tgisconstraint)
5364 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5365 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5366 if (OidIsValid(tginfo[j].tgconstrrelid))
5368 if (PQgetisnull(res, j, i_tgconstrrelname))
5370 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5371 tginfo[j].dobj.name, tbinfo->dobj.name,
5372 tginfo[j].tgconstrrelid);
5375 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5378 tginfo[j].tgconstrrelname = NULL;
5382 tginfo[j].tgconstrname = NULL;
5383 tginfo[j].tgconstrrelid = InvalidOid;
5384 tginfo[j].tgconstrrelname = NULL;
5392 destroyPQExpBuffer(query);
5397 * get basic information about every procedural language in the system
5399 * numProcLangs is set to the number of langs read in
5401 * NB: this must run after getFuncs() because we assume we can do
5405 getProcLangs(Archive *fout, int *numProcLangs)
5410 PQExpBuffer query = createPQExpBuffer();
5411 ProcLangInfo *planginfo;
5416 int i_lanplcallfoid;
5422 /* Make sure we are in proper schema */
5423 selectSourceSchema(fout, "pg_catalog");
5425 if (fout->remoteVersion >= 90000)
5427 /* pg_language has a laninline column */
5428 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5429 "lanname, lanpltrusted, lanplcallfoid, "
5430 "laninline, lanvalidator, lanacl, "
5431 "(%s lanowner) AS lanowner "
5437 else if (fout->remoteVersion >= 80300)
5439 /* pg_language has a lanowner column */
5440 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5441 "lanname, lanpltrusted, lanplcallfoid, "
5442 "lanvalidator, lanacl, "
5443 "(%s lanowner) AS lanowner "
5449 else if (fout->remoteVersion >= 80100)
5451 /* Languages are owned by the bootstrap superuser, OID 10 */
5452 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5453 "(%s '10') AS lanowner "
5459 else if (fout->remoteVersion >= 70400)
5461 /* Languages are owned by the bootstrap superuser, sysid 1 */
5462 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5463 "(%s '1') AS lanowner "
5469 else if (fout->remoteVersion >= 70100)
5471 /* No clear notion of an owner at all before 7.4 ... */
5472 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5478 appendPQExpBuffer(query, "SELECT "
5479 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5480 "oid, * FROM pg_language "
5485 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5487 ntups = PQntuples(res);
5489 *numProcLangs = ntups;
5491 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5493 i_tableoid = PQfnumber(res, "tableoid");
5494 i_oid = PQfnumber(res, "oid");
5495 i_lanname = PQfnumber(res, "lanname");
5496 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5497 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5498 /* these may fail and return -1: */
5499 i_laninline = PQfnumber(res, "laninline");
5500 i_lanvalidator = PQfnumber(res, "lanvalidator");
5501 i_lanacl = PQfnumber(res, "lanacl");
5502 i_lanowner = PQfnumber(res, "lanowner");
5504 for (i = 0; i < ntups; i++)
5506 planginfo[i].dobj.objType = DO_PROCLANG;
5507 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5508 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5509 AssignDumpId(&planginfo[i].dobj);
5511 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5512 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5513 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5514 if (i_laninline >= 0)
5515 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5517 planginfo[i].laninline = InvalidOid;
5518 if (i_lanvalidator >= 0)
5519 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5521 planginfo[i].lanvalidator = InvalidOid;
5523 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5525 planginfo[i].lanacl = pg_strdup("{=U}");
5526 if (i_lanowner >= 0)
5527 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5529 planginfo[i].lanowner = pg_strdup("");
5531 if (fout->remoteVersion < 70300)
5534 * We need to make a dependency to ensure the function will be
5535 * dumped first. (In 7.3 and later the regular dependency
5536 * mechanism will handle this for us.)
5538 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5541 addObjectDependency(&planginfo[i].dobj,
5542 funcInfo->dobj.dumpId);
5548 destroyPQExpBuffer(query);
5555 * get basic information about every cast in the system
5557 * numCasts is set to the number of casts read in
5560 getCasts(Archive *fout, int *numCasts)
5565 PQExpBuffer query = createPQExpBuffer();
5575 /* Make sure we are in proper schema */
5576 selectSourceSchema(fout, "pg_catalog");
5578 if (fout->remoteVersion >= 80400)
5580 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5581 "castsource, casttarget, castfunc, castcontext, "
5583 "FROM pg_cast ORDER BY 3,4");
5585 else if (fout->remoteVersion >= 70300)
5587 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5588 "castsource, casttarget, castfunc, castcontext, "
5589 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5590 "FROM pg_cast ORDER BY 3,4");
5594 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5595 "t1.oid AS castsource, t2.oid AS casttarget, "
5596 "p.oid AS castfunc, 'e' AS castcontext, "
5597 "'f' AS castmethod "
5598 "FROM pg_type t1, pg_type t2, pg_proc p "
5599 "WHERE p.pronargs = 1 AND "
5600 "p.proargtypes[0] = t1.oid AND "
5601 "p.prorettype = t2.oid AND p.proname = t2.typname "
5605 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5607 ntups = PQntuples(res);
5611 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5613 i_tableoid = PQfnumber(res, "tableoid");
5614 i_oid = PQfnumber(res, "oid");
5615 i_castsource = PQfnumber(res, "castsource");
5616 i_casttarget = PQfnumber(res, "casttarget");
5617 i_castfunc = PQfnumber(res, "castfunc");
5618 i_castcontext = PQfnumber(res, "castcontext");
5619 i_castmethod = PQfnumber(res, "castmethod");
5621 for (i = 0; i < ntups; i++)
5623 PQExpBufferData namebuf;
5624 TypeInfo *sTypeInfo;
5625 TypeInfo *tTypeInfo;
5627 castinfo[i].dobj.objType = DO_CAST;
5628 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5629 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5630 AssignDumpId(&castinfo[i].dobj);
5631 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5632 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5633 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5634 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5635 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5638 * Try to name cast as concatenation of typnames. This is only used
5639 * for purposes of sorting. If we fail to find either type, the name
5640 * will be an empty string.
5642 initPQExpBuffer(&namebuf);
5643 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5644 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5645 if (sTypeInfo && tTypeInfo)
5646 appendPQExpBuffer(&namebuf, "%s %s",
5647 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5648 castinfo[i].dobj.name = namebuf.data;
5650 if (OidIsValid(castinfo[i].castfunc))
5653 * We need to make a dependency to ensure the function will be
5654 * dumped first. (In 7.3 and later the regular dependency
5655 * mechanism will handle this for us.)
5659 funcInfo = findFuncByOid(castinfo[i].castfunc);
5661 addObjectDependency(&castinfo[i].dobj,
5662 funcInfo->dobj.dumpId);
5668 destroyPQExpBuffer(query);
5675 * for each interesting table, read info about its attributes
5676 * (names, types, default values, CHECK constraints, etc)
5678 * This is implemented in a very inefficient way right now, looping
5679 * through the tblinfo and doing a join per table to find the attrs and their
5680 * types. However, because we want type names and so forth to be named
5681 * relative to the schema of each table, we couldn't do it in just one
5682 * query. (Maybe one query per schema?)
5687 getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
5691 PQExpBuffer q = createPQExpBuffer();
5696 int i_attstattarget;
5707 int i_attfdwoptions;
5712 for (i = 0; i < numTables; i++)
5714 TableInfo *tbinfo = &tblinfo[i];
5716 /* Don't bother to collect info for sequences */
5717 if (tbinfo->relkind == RELKIND_SEQUENCE)
5720 /* Don't bother with uninteresting tables, either */
5721 if (!tbinfo->interesting)
5725 * Make sure we are in proper schema for this table; this allows
5726 * correct retrieval of formatted type names and default exprs
5728 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
5730 /* find all the user attributes and their types */
5733 * we must read the attribute names in attribute number order! because
5734 * we will use the attnum to index into the attnames array later. We
5735 * actually ask to order by "attrelid, attnum" because (at least up to
5736 * 7.3) the planner is not smart enough to realize it needn't re-sort
5737 * the output of an indexscan on pg_attribute_relid_attnum_index.
5740 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5743 resetPQExpBuffer(q);
5745 if (fout->remoteVersion >= 90200)
5748 * attfdwoptions is new in 9.2.
5750 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5751 "a.attstattarget, a.attstorage, t.typstorage, "
5752 "a.attnotnull, a.atthasdef, a.attisdropped, "
5753 "a.attlen, a.attalign, a.attislocal, "
5754 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5755 "array_to_string(a.attoptions, ', ') AS attoptions, "
5756 "CASE WHEN a.attcollation <> t.typcollation "
5757 "THEN a.attcollation ELSE 0 END AS attcollation, "
5758 "pg_catalog.array_to_string(ARRAY("
5759 "SELECT pg_catalog.quote_ident(option_name) || "
5760 "' ' || pg_catalog.quote_literal(option_value) "
5761 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
5762 "ORDER BY option_name"
5763 "), E',\n ') AS attfdwoptions "
5764 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5765 "ON a.atttypid = t.oid "
5766 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5767 "AND a.attnum > 0::pg_catalog.int2 "
5768 "ORDER BY a.attrelid, a.attnum",
5769 tbinfo->dobj.catId.oid);
5771 else if (fout->remoteVersion >= 90100)
5774 * attcollation is new in 9.1. Since we only want to dump COLLATE
5775 * clauses for attributes whose collation is different from their
5776 * type's default, we use a CASE here to suppress uninteresting
5777 * attcollations cheaply.
5779 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5780 "a.attstattarget, a.attstorage, t.typstorage, "
5781 "a.attnotnull, a.atthasdef, a.attisdropped, "
5782 "a.attlen, a.attalign, a.attislocal, "
5783 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5784 "array_to_string(a.attoptions, ', ') AS attoptions, "
5785 "CASE WHEN a.attcollation <> t.typcollation "
5786 "THEN a.attcollation ELSE 0 END AS attcollation, "
5787 "NULL AS attfdwoptions "
5788 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5789 "ON a.atttypid = t.oid "
5790 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5791 "AND a.attnum > 0::pg_catalog.int2 "
5792 "ORDER BY a.attrelid, a.attnum",
5793 tbinfo->dobj.catId.oid);
5795 else if (fout->remoteVersion >= 90000)
5797 /* attoptions is new in 9.0 */
5798 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5799 "a.attstattarget, a.attstorage, t.typstorage, "
5800 "a.attnotnull, a.atthasdef, a.attisdropped, "
5801 "a.attlen, a.attalign, a.attislocal, "
5802 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5803 "array_to_string(a.attoptions, ', ') AS attoptions, "
5804 "0 AS attcollation, "
5805 "NULL AS attfdwoptions "
5806 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5807 "ON a.atttypid = t.oid "
5808 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5809 "AND a.attnum > 0::pg_catalog.int2 "
5810 "ORDER BY a.attrelid, a.attnum",
5811 tbinfo->dobj.catId.oid);
5813 else if (fout->remoteVersion >= 70300)
5815 /* need left join here to not fail on dropped columns ... */
5816 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5817 "a.attstattarget, a.attstorage, t.typstorage, "
5818 "a.attnotnull, a.atthasdef, a.attisdropped, "
5819 "a.attlen, a.attalign, a.attislocal, "
5820 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5821 "'' AS attoptions, 0 AS attcollation, "
5822 "NULL AS attfdwoptions "
5823 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5824 "ON a.atttypid = t.oid "
5825 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5826 "AND a.attnum > 0::pg_catalog.int2 "
5827 "ORDER BY a.attrelid, a.attnum",
5828 tbinfo->dobj.catId.oid);
5830 else if (fout->remoteVersion >= 70100)
5833 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5834 * we don't dump it because we can't tell whether it's been
5835 * explicitly set or was just a default.
5837 * attislocal doesn't exist before 7.3, either; in older databases
5838 * we assume it's TRUE, else we'd fail to dump non-inherited atts.
5840 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5841 "-1 AS attstattarget, a.attstorage, "
5842 "t.typstorage, a.attnotnull, a.atthasdef, "
5843 "false AS attisdropped, a.attlen, "
5844 "a.attalign, true AS attislocal, "
5845 "format_type(t.oid,a.atttypmod) AS atttypname, "
5846 "'' AS attoptions, 0 AS attcollation, "
5847 "NULL AS attfdwoptions "
5848 "FROM pg_attribute a LEFT JOIN pg_type t "
5849 "ON a.atttypid = t.oid "
5850 "WHERE a.attrelid = '%u'::oid "
5851 "AND a.attnum > 0::int2 "
5852 "ORDER BY a.attrelid, a.attnum",
5853 tbinfo->dobj.catId.oid);
5857 /* format_type not available before 7.1 */
5858 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5859 "-1 AS attstattarget, "
5860 "attstorage, attstorage AS typstorage, "
5861 "attnotnull, atthasdef, false AS attisdropped, "
5862 "attlen, attalign, "
5863 "true AS attislocal, "
5864 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5865 "'' AS attoptions, 0 AS attcollation, "
5866 "NULL AS attfdwoptions "
5867 "FROM pg_attribute a "
5868 "WHERE attrelid = '%u'::oid "
5869 "AND attnum > 0::int2 "
5870 "ORDER BY attrelid, attnum",
5871 tbinfo->dobj.catId.oid);
5874 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5876 ntups = PQntuples(res);
5878 i_attnum = PQfnumber(res, "attnum");
5879 i_attname = PQfnumber(res, "attname");
5880 i_atttypname = PQfnumber(res, "atttypname");
5881 i_atttypmod = PQfnumber(res, "atttypmod");
5882 i_attstattarget = PQfnumber(res, "attstattarget");
5883 i_attstorage = PQfnumber(res, "attstorage");
5884 i_typstorage = PQfnumber(res, "typstorage");
5885 i_attnotnull = PQfnumber(res, "attnotnull");
5886 i_atthasdef = PQfnumber(res, "atthasdef");
5887 i_attisdropped = PQfnumber(res, "attisdropped");
5888 i_attlen = PQfnumber(res, "attlen");
5889 i_attalign = PQfnumber(res, "attalign");
5890 i_attislocal = PQfnumber(res, "attislocal");
5891 i_attoptions = PQfnumber(res, "attoptions");
5892 i_attcollation = PQfnumber(res, "attcollation");
5893 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5895 tbinfo->numatts = ntups;
5896 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5897 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5898 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5899 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5900 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5901 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5902 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5903 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5904 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5905 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5906 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5907 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5908 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5909 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5910 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5911 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5912 hasdefaults = false;
5914 for (j = 0; j < ntups; j++)
5916 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5918 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5922 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5923 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5924 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5925 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5926 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5927 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5928 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5929 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5930 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5931 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5932 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5933 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5934 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5935 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5936 tbinfo->attrdefs[j] = NULL; /* fix below */
5937 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5939 /* these flags will be set in flagInhAttrs() */
5940 tbinfo->inhNotNull[j] = false;
5946 * Get info about column defaults
5950 AttrDefInfo *attrdefs;
5954 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5957 resetPQExpBuffer(q);
5958 if (fout->remoteVersion >= 70300)
5960 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5961 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5962 "FROM pg_catalog.pg_attrdef "
5963 "WHERE adrelid = '%u'::pg_catalog.oid",
5964 tbinfo->dobj.catId.oid);
5966 else if (fout->remoteVersion >= 70200)
5968 /* 7.2 did not have OIDs in pg_attrdef */
5969 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5970 "pg_get_expr(adbin, adrelid) AS adsrc "
5972 "WHERE adrelid = '%u'::oid",
5973 tbinfo->dobj.catId.oid);
5975 else if (fout->remoteVersion >= 70100)
5977 /* no pg_get_expr, so must rely on adsrc */
5978 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5980 "WHERE adrelid = '%u'::oid",
5981 tbinfo->dobj.catId.oid);
5985 /* no pg_get_expr, no tableoid either */
5986 appendPQExpBuffer(q, "SELECT "
5987 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5988 "oid, adnum, adsrc "
5990 "WHERE adrelid = '%u'::oid",
5991 tbinfo->dobj.catId.oid);
5993 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
5995 numDefaults = PQntuples(res);
5996 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5998 for (j = 0; j < numDefaults; j++)
6002 adnum = atoi(PQgetvalue(res, j, 2));
6004 if (adnum <= 0 || adnum > ntups)
6006 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
6007 adnum, tbinfo->dobj.name);
6012 * dropped columns shouldn't have defaults, but just in case,
6015 if (tbinfo->attisdropped[adnum - 1])
6018 attrdefs[j].dobj.objType = DO_ATTRDEF;
6019 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6020 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6021 AssignDumpId(&attrdefs[j].dobj);
6022 attrdefs[j].adtable = tbinfo;
6023 attrdefs[j].adnum = adnum;
6024 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
6026 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
6027 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
6029 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
6032 * Defaults on a VIEW must always be dumped as separate ALTER
6033 * TABLE commands. Defaults on regular tables are dumped as
6034 * part of the CREATE TABLE if possible, which it won't be
6035 * if the column is not going to be emitted explicitly.
6037 if (tbinfo->relkind == RELKIND_VIEW)
6039 attrdefs[j].separate = true;
6040 /* needed in case pre-7.3 DB: */
6041 addObjectDependency(&attrdefs[j].dobj,
6042 tbinfo->dobj.dumpId);
6044 else if (!shouldPrintColumn(tbinfo, adnum - 1))
6046 /* column will be suppressed, print default separately */
6047 attrdefs[j].separate = true;
6048 /* needed in case pre-7.3 DB: */
6049 addObjectDependency(&attrdefs[j].dobj,
6050 tbinfo->dobj.dumpId);
6054 attrdefs[j].separate = false;
6056 * Mark the default as needing to appear before the table,
6057 * so that any dependencies it has must be emitted before
6058 * the CREATE TABLE. If this is not possible, we'll
6059 * change to "separate" mode while sorting dependencies.
6061 addObjectDependency(&tbinfo->dobj,
6062 attrdefs[j].dobj.dumpId);
6065 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
6071 * Get info about table CHECK constraints
6073 if (tbinfo->ncheck > 0)
6075 ConstraintInfo *constrs;
6079 write_msg(NULL, "finding check constraints for table \"%s\"\n",
6082 resetPQExpBuffer(q);
6083 if (fout->remoteVersion >= 90200)
6086 * conisonly and convalidated are new in 9.2 (actually, the latter
6087 * is there in 9.1, but it wasn't ever false for check constraints
6090 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6091 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6092 "conislocal, convalidated, conisonly "
6093 "FROM pg_catalog.pg_constraint "
6094 "WHERE conrelid = '%u'::pg_catalog.oid "
6095 " AND contype = 'c' "
6097 tbinfo->dobj.catId.oid);
6099 else if (fout->remoteVersion >= 80400)
6101 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6102 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6103 "conislocal, true AS convalidated, "
6104 "false as conisonly "
6105 "FROM pg_catalog.pg_constraint "
6106 "WHERE conrelid = '%u'::pg_catalog.oid "
6107 " AND contype = 'c' "
6109 tbinfo->dobj.catId.oid);
6111 else if (fout->remoteVersion >= 70400)
6113 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6114 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6115 "true AS conislocal, true AS convalidated, "
6116 "false as conisonly "
6117 "FROM pg_catalog.pg_constraint "
6118 "WHERE conrelid = '%u'::pg_catalog.oid "
6119 " AND contype = 'c' "
6121 tbinfo->dobj.catId.oid);
6123 else if (fout->remoteVersion >= 70300)
6125 /* no pg_get_constraintdef, must use consrc */
6126 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6127 "'CHECK (' || consrc || ')' AS consrc, "
6128 "true AS conislocal, true AS convalidated, "
6129 "false as conisonly "
6130 "FROM pg_catalog.pg_constraint "
6131 "WHERE conrelid = '%u'::pg_catalog.oid "
6132 " AND contype = 'c' "
6134 tbinfo->dobj.catId.oid);
6136 else if (fout->remoteVersion >= 70200)
6138 /* 7.2 did not have OIDs in pg_relcheck */
6139 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6140 "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 else if (fout->remoteVersion >= 70100)
6151 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6152 "rcname AS conname, "
6153 "'CHECK (' || rcsrc || ')' AS consrc, "
6154 "true AS conislocal, true AS convalidated, "
6155 "false as conisonly "
6157 "WHERE rcrelid = '%u'::oid "
6159 tbinfo->dobj.catId.oid);
6163 /* no tableoid in 7.0 */
6164 appendPQExpBuffer(q, "SELECT "
6165 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6166 "oid, rcname AS conname, "
6167 "'CHECK (' || rcsrc || ')' AS consrc, "
6168 "true AS conislocal, true AS convalidated, "
6169 "false as conisonly "
6171 "WHERE rcrelid = '%u'::oid "
6173 tbinfo->dobj.catId.oid);
6175 res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
6177 numConstrs = PQntuples(res);
6178 if (numConstrs != tbinfo->ncheck)
6180 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6181 "expected %d check constraints on table \"%s\" but found %d\n",
6183 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6184 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6188 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6189 tbinfo->checkexprs = constrs;
6191 for (j = 0; j < numConstrs; j++)
6193 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6194 bool isonly = PQgetvalue(res, j, 6)[0] == 't';
6196 constrs[j].dobj.objType = DO_CONSTRAINT;
6197 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6198 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6199 AssignDumpId(&constrs[j].dobj);
6200 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6201 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6202 constrs[j].contable = tbinfo;
6203 constrs[j].condomain = NULL;
6204 constrs[j].contype = 'c';
6205 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6206 constrs[j].confrelid = InvalidOid;
6207 constrs[j].conindex = 0;
6208 constrs[j].condeferrable = false;
6209 constrs[j].condeferred = false;
6210 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6211 constrs[j].conisonly = isonly;
6213 * An unvalidated constraint needs to be dumped separately, so
6214 * that potentially-violating existing data is loaded before
6215 * the constraint. An ONLY constraint needs to be dumped
6218 constrs[j].separate = !validated || isonly;
6220 constrs[j].dobj.dump = tbinfo->dobj.dump;
6223 * Mark the constraint as needing to appear before the table
6224 * --- this is so that any other dependencies of the
6225 * constraint will be emitted before we try to create the
6226 * table. If the constraint is to be dumped separately, it will be
6227 * dumped after data is loaded anyway, so don't do it. (There's
6228 * an automatic dependency in the opposite direction anyway, so
6229 * don't need to add one manually here.)
6231 if (!constrs[j].separate)
6232 addObjectDependency(&tbinfo->dobj,
6233 constrs[j].dobj.dumpId);
6236 * If the constraint is inherited, this will be detected later
6237 * (in pre-8.4 databases). We also detect later if the
6238 * constraint must be split out from the table definition.
6245 destroyPQExpBuffer(q);
6249 * Test whether a column should be printed as part of table's CREATE TABLE.
6250 * Column number is zero-based.
6252 * Normally this is always true, but it's false for dropped columns, as well
6253 * as those that were inherited without any local definition. (If we print
6254 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
6255 * However, in binary_upgrade mode, we must print all such columns anyway and
6256 * fix the attislocal/attisdropped state later, so as to keep control of the
6257 * physical column order.
6259 * This function exists because there are scattered nonobvious places that
6260 * must be kept in sync with this decision.
6263 shouldPrintColumn(TableInfo *tbinfo, int colno)
6267 return (tbinfo->attislocal[colno] && !tbinfo->attisdropped[colno]);
6273 * read all text search parsers in the system catalogs and return them
6274 * in the TSParserInfo* structure
6276 * numTSParsers is set to the number of parsers read in
6279 getTSParsers(Archive *fout, int *numTSParsers)
6284 PQExpBuffer query = createPQExpBuffer();
6285 TSParserInfo *prsinfo;
6296 /* Before 8.3, there is no built-in text search support */
6297 if (fout->remoteVersion < 80300)
6304 * find all text search objects, including builtin ones; we filter out
6305 * system-defined objects at dump-out time.
6308 /* Make sure we are in proper schema */
6309 selectSourceSchema(fout, "pg_catalog");
6311 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6312 "prsstart::oid, prstoken::oid, "
6313 "prsend::oid, prsheadline::oid, prslextype::oid "
6314 "FROM pg_ts_parser");
6316 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6318 ntups = PQntuples(res);
6319 *numTSParsers = ntups;
6321 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6323 i_tableoid = PQfnumber(res, "tableoid");
6324 i_oid = PQfnumber(res, "oid");
6325 i_prsname = PQfnumber(res, "prsname");
6326 i_prsnamespace = PQfnumber(res, "prsnamespace");
6327 i_prsstart = PQfnumber(res, "prsstart");
6328 i_prstoken = PQfnumber(res, "prstoken");
6329 i_prsend = PQfnumber(res, "prsend");
6330 i_prsheadline = PQfnumber(res, "prsheadline");
6331 i_prslextype = PQfnumber(res, "prslextype");
6333 for (i = 0; i < ntups; i++)
6335 prsinfo[i].dobj.objType = DO_TSPARSER;
6336 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6337 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6338 AssignDumpId(&prsinfo[i].dobj);
6339 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6340 prsinfo[i].dobj.namespace =
6342 atooid(PQgetvalue(res, i, i_prsnamespace)),
6343 prsinfo[i].dobj.catId.oid);
6344 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6345 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6346 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6347 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6348 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6350 /* Decide whether we want to dump it */
6351 selectDumpableObject(&(prsinfo[i].dobj));
6356 destroyPQExpBuffer(query);
6362 * getTSDictionaries:
6363 * read all text search dictionaries in the system catalogs and return them
6364 * in the TSDictInfo* structure
6366 * numTSDicts is set to the number of dictionaries read in
6369 getTSDictionaries(Archive *fout, int *numTSDicts)
6374 PQExpBuffer query = createPQExpBuffer();
6375 TSDictInfo *dictinfo;
6379 int i_dictnamespace;
6382 int i_dictinitoption;
6384 /* Before 8.3, there is no built-in text search support */
6385 if (fout->remoteVersion < 80300)
6391 /* Make sure we are in proper schema */
6392 selectSourceSchema(fout, "pg_catalog");
6394 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6395 "dictnamespace, (%s dictowner) AS rolname, "
6396 "dicttemplate, dictinitoption "
6400 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6402 ntups = PQntuples(res);
6403 *numTSDicts = ntups;
6405 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6407 i_tableoid = PQfnumber(res, "tableoid");
6408 i_oid = PQfnumber(res, "oid");
6409 i_dictname = PQfnumber(res, "dictname");
6410 i_dictnamespace = PQfnumber(res, "dictnamespace");
6411 i_rolname = PQfnumber(res, "rolname");
6412 i_dictinitoption = PQfnumber(res, "dictinitoption");
6413 i_dicttemplate = PQfnumber(res, "dicttemplate");
6415 for (i = 0; i < ntups; i++)
6417 dictinfo[i].dobj.objType = DO_TSDICT;
6418 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6419 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6420 AssignDumpId(&dictinfo[i].dobj);
6421 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6422 dictinfo[i].dobj.namespace =
6424 atooid(PQgetvalue(res, i, i_dictnamespace)),
6425 dictinfo[i].dobj.catId.oid);
6426 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6427 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6428 if (PQgetisnull(res, i, i_dictinitoption))
6429 dictinfo[i].dictinitoption = NULL;
6431 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6433 /* Decide whether we want to dump it */
6434 selectDumpableObject(&(dictinfo[i].dobj));
6439 destroyPQExpBuffer(query);
6446 * read all text search templates in the system catalogs and return them
6447 * in the TSTemplateInfo* structure
6449 * numTSTemplates is set to the number of templates read in
6452 getTSTemplates(Archive *fout, int *numTSTemplates)
6457 PQExpBuffer query = createPQExpBuffer();
6458 TSTemplateInfo *tmplinfo;
6462 int i_tmplnamespace;
6466 /* Before 8.3, there is no built-in text search support */
6467 if (fout->remoteVersion < 80300)
6469 *numTSTemplates = 0;
6473 /* Make sure we are in proper schema */
6474 selectSourceSchema(fout, "pg_catalog");
6476 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6477 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6478 "FROM pg_ts_template");
6480 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6482 ntups = PQntuples(res);
6483 *numTSTemplates = ntups;
6485 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6487 i_tableoid = PQfnumber(res, "tableoid");
6488 i_oid = PQfnumber(res, "oid");
6489 i_tmplname = PQfnumber(res, "tmplname");
6490 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6491 i_tmplinit = PQfnumber(res, "tmplinit");
6492 i_tmpllexize = PQfnumber(res, "tmpllexize");
6494 for (i = 0; i < ntups; i++)
6496 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6497 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6498 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6499 AssignDumpId(&tmplinfo[i].dobj);
6500 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6501 tmplinfo[i].dobj.namespace =
6503 atooid(PQgetvalue(res, i, i_tmplnamespace)),
6504 tmplinfo[i].dobj.catId.oid);
6505 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6506 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6508 /* Decide whether we want to dump it */
6509 selectDumpableObject(&(tmplinfo[i].dobj));
6514 destroyPQExpBuffer(query);
6520 * getTSConfigurations:
6521 * read all text search configurations in the system catalogs and return
6522 * them in the TSConfigInfo* structure
6524 * numTSConfigs is set to the number of configurations read in
6527 getTSConfigurations(Archive *fout, int *numTSConfigs)
6532 PQExpBuffer query = createPQExpBuffer();
6533 TSConfigInfo *cfginfo;
6541 /* Before 8.3, there is no built-in text search support */
6542 if (fout->remoteVersion < 80300)
6548 /* Make sure we are in proper schema */
6549 selectSourceSchema(fout, "pg_catalog");
6551 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6552 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6553 "FROM pg_ts_config",
6556 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6558 ntups = PQntuples(res);
6559 *numTSConfigs = ntups;
6561 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6563 i_tableoid = PQfnumber(res, "tableoid");
6564 i_oid = PQfnumber(res, "oid");
6565 i_cfgname = PQfnumber(res, "cfgname");
6566 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6567 i_rolname = PQfnumber(res, "rolname");
6568 i_cfgparser = PQfnumber(res, "cfgparser");
6570 for (i = 0; i < ntups; i++)
6572 cfginfo[i].dobj.objType = DO_TSCONFIG;
6573 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6574 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6575 AssignDumpId(&cfginfo[i].dobj);
6576 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6577 cfginfo[i].dobj.namespace =
6579 atooid(PQgetvalue(res, i, i_cfgnamespace)),
6580 cfginfo[i].dobj.catId.oid);
6581 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6582 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6584 /* Decide whether we want to dump it */
6585 selectDumpableObject(&(cfginfo[i].dobj));
6590 destroyPQExpBuffer(query);
6596 * getForeignDataWrappers:
6597 * read all foreign-data wrappers in the system catalogs and return
6598 * them in the FdwInfo* structure
6600 * numForeignDataWrappers is set to the number of fdws read in
6603 getForeignDataWrappers(Archive *fout, int *numForeignDataWrappers)
6608 PQExpBuffer query = createPQExpBuffer();
6619 /* Before 8.4, there are no foreign-data wrappers */
6620 if (fout->remoteVersion < 80400)
6622 *numForeignDataWrappers = 0;
6626 /* Make sure we are in proper schema */
6627 selectSourceSchema(fout, "pg_catalog");
6629 if (fout->remoteVersion >= 90100)
6631 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6632 "(%s fdwowner) AS rolname, "
6633 "fdwhandler::pg_catalog.regproc, "
6634 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6635 "array_to_string(ARRAY("
6636 "SELECT quote_ident(option_name) || ' ' || "
6637 "quote_literal(option_value) "
6638 "FROM pg_options_to_table(fdwoptions) "
6639 "ORDER BY option_name"
6640 "), E',\n ') AS fdwoptions "
6641 "FROM pg_foreign_data_wrapper",
6646 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6647 "(%s fdwowner) AS rolname, "
6648 "'-' AS fdwhandler, "
6649 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6650 "array_to_string(ARRAY("
6651 "SELECT quote_ident(option_name) || ' ' || "
6652 "quote_literal(option_value) "
6653 "FROM pg_options_to_table(fdwoptions) "
6654 "ORDER BY option_name"
6655 "), E',\n ') AS fdwoptions "
6656 "FROM pg_foreign_data_wrapper",
6660 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6662 ntups = PQntuples(res);
6663 *numForeignDataWrappers = ntups;
6665 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6667 i_tableoid = PQfnumber(res, "tableoid");
6668 i_oid = PQfnumber(res, "oid");
6669 i_fdwname = PQfnumber(res, "fdwname");
6670 i_rolname = PQfnumber(res, "rolname");
6671 i_fdwhandler = PQfnumber(res, "fdwhandler");
6672 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6673 i_fdwacl = PQfnumber(res, "fdwacl");
6674 i_fdwoptions = PQfnumber(res, "fdwoptions");
6676 for (i = 0; i < ntups; i++)
6678 fdwinfo[i].dobj.objType = DO_FDW;
6679 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6680 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6681 AssignDumpId(&fdwinfo[i].dobj);
6682 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6683 fdwinfo[i].dobj.namespace = NULL;
6684 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6685 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6686 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6687 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6688 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6690 /* Decide whether we want to dump it */
6691 selectDumpableObject(&(fdwinfo[i].dobj));
6696 destroyPQExpBuffer(query);
6702 * getForeignServers:
6703 * read all foreign servers in the system catalogs and return
6704 * them in the ForeignServerInfo * structure
6706 * numForeignServers is set to the number of servers read in
6709 getForeignServers(Archive *fout, int *numForeignServers)
6714 PQExpBuffer query = createPQExpBuffer();
6715 ForeignServerInfo *srvinfo;
6726 /* Before 8.4, there are no foreign servers */
6727 if (fout->remoteVersion < 80400)
6729 *numForeignServers = 0;
6733 /* Make sure we are in proper schema */
6734 selectSourceSchema(fout,"pg_catalog");
6736 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6737 "(%s srvowner) AS rolname, "
6738 "srvfdw, srvtype, srvversion, srvacl,"
6739 "array_to_string(ARRAY("
6740 "SELECT quote_ident(option_name) || ' ' || "
6741 "quote_literal(option_value) "
6742 "FROM pg_options_to_table(srvoptions) "
6743 "ORDER BY option_name"
6744 "), E',\n ') AS srvoptions "
6745 "FROM pg_foreign_server",
6748 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6750 ntups = PQntuples(res);
6751 *numForeignServers = ntups;
6753 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6755 i_tableoid = PQfnumber(res, "tableoid");
6756 i_oid = PQfnumber(res, "oid");
6757 i_srvname = PQfnumber(res, "srvname");
6758 i_rolname = PQfnumber(res, "rolname");
6759 i_srvfdw = PQfnumber(res, "srvfdw");
6760 i_srvtype = PQfnumber(res, "srvtype");
6761 i_srvversion = PQfnumber(res, "srvversion");
6762 i_srvacl = PQfnumber(res, "srvacl");
6763 i_srvoptions = PQfnumber(res, "srvoptions");
6765 for (i = 0; i < ntups; i++)
6767 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6768 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6769 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6770 AssignDumpId(&srvinfo[i].dobj);
6771 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6772 srvinfo[i].dobj.namespace = NULL;
6773 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6774 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6775 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6776 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6777 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6778 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6780 /* Decide whether we want to dump it */
6781 selectDumpableObject(&(srvinfo[i].dobj));
6786 destroyPQExpBuffer(query);
6793 * read all default ACL information in the system catalogs and return
6794 * them in the DefaultACLInfo structure
6796 * numDefaultACLs is set to the number of ACLs read in
6799 getDefaultACLs(Archive *fout, int *numDefaultACLs)
6801 DefaultACLInfo *daclinfo;
6807 int i_defaclnamespace;
6808 int i_defaclobjtype;
6813 if (fout->remoteVersion < 90000)
6815 *numDefaultACLs = 0;
6819 query = createPQExpBuffer();
6821 /* Make sure we are in proper schema */
6822 selectSourceSchema(fout, "pg_catalog");
6824 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6825 "(%s defaclrole) AS defaclrole, "
6829 "FROM pg_default_acl",
6832 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6834 ntups = PQntuples(res);
6835 *numDefaultACLs = ntups;
6837 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6839 i_oid = PQfnumber(res, "oid");
6840 i_tableoid = PQfnumber(res, "tableoid");
6841 i_defaclrole = PQfnumber(res, "defaclrole");
6842 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6843 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6844 i_defaclacl = PQfnumber(res, "defaclacl");
6846 for (i = 0; i < ntups; i++)
6848 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6850 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6851 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6852 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6853 AssignDumpId(&daclinfo[i].dobj);
6854 /* cheesy ... is it worth coming up with a better object name? */
6855 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6857 if (nspid != InvalidOid)
6858 daclinfo[i].dobj.namespace = findNamespace(fout, nspid,
6859 daclinfo[i].dobj.catId.oid);
6861 daclinfo[i].dobj.namespace = NULL;
6863 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6864 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6865 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6867 /* Decide whether we want to dump it */
6868 selectDumpableDefaultACL(&(daclinfo[i]));
6873 destroyPQExpBuffer(query);
6881 * This routine is used to dump any comments associated with the
6882 * object handed to this routine. The routine takes a constant character
6883 * string for the target part of the comment-creation command, plus
6884 * the namespace and owner of the object (for labeling the ArchiveEntry),
6885 * plus catalog ID and subid which are the lookup key for pg_description,
6886 * plus the dump ID for the object (for setting a dependency).
6887 * If a matching pg_description entry is found, it is dumped.
6889 * Note: although this routine takes a dumpId for dependency purposes,
6890 * that purpose is just to mark the dependency in the emitted dump file
6891 * for possible future use by pg_restore. We do NOT use it for determining
6892 * ordering of the comment in the dump file, because this routine is called
6893 * after dependency sorting occurs. This routine should be called just after
6894 * calling ArchiveEntry() for the specified object.
6897 dumpComment(Archive *fout, const char *target,
6898 const char *namespace, const char *owner,
6899 CatalogId catalogId, int subid, DumpId dumpId)
6901 CommentItem *comments;
6904 /* Comments are schema not data ... except blob comments are data */
6905 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6916 /* Search for comments associated with catalogId, using table */
6917 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6920 /* Is there one matching the subid? */
6921 while (ncomments > 0)
6923 if (comments->objsubid == subid)
6929 /* If a comment exists, build COMMENT ON statement */
6932 PQExpBuffer query = createPQExpBuffer();
6934 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6935 appendStringLiteralAH(query, comments->descr, fout);
6936 appendPQExpBuffer(query, ";\n");
6939 * We mark comments as SECTION_NONE because they really belong in the
6940 * same section as their parent, whether that is pre-data or
6943 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6944 target, namespace, NULL, owner,
6945 false, "COMMENT", SECTION_NONE,
6946 query->data, "", NULL,
6950 destroyPQExpBuffer(query);
6955 * dumpTableComment --
6957 * As above, but dump comments for both the specified table (or view)
6961 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6962 const char *reltypename)
6964 CommentItem *comments;
6969 /* Comments are SCHEMA not data */
6973 /* Search for comments associated with relation, using table */
6974 ncomments = findComments(fout,
6975 tbinfo->dobj.catId.tableoid,
6976 tbinfo->dobj.catId.oid,
6979 /* If comments exist, build COMMENT ON statements */
6983 query = createPQExpBuffer();
6984 target = createPQExpBuffer();
6986 while (ncomments > 0)
6988 const char *descr = comments->descr;
6989 int objsubid = comments->objsubid;
6993 resetPQExpBuffer(target);
6994 appendPQExpBuffer(target, "%s %s", reltypename,
6995 fmtId(tbinfo->dobj.name));
6997 resetPQExpBuffer(query);
6998 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6999 appendStringLiteralAH(query, descr, fout);
7000 appendPQExpBuffer(query, ";\n");
7002 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7004 tbinfo->dobj.namespace->dobj.name,
7005 NULL, tbinfo->rolname,
7006 false, "COMMENT", SECTION_NONE,
7007 query->data, "", NULL,
7008 &(tbinfo->dobj.dumpId), 1,
7011 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
7013 resetPQExpBuffer(target);
7014 appendPQExpBuffer(target, "COLUMN %s.",
7015 fmtId(tbinfo->dobj.name));
7016 appendPQExpBuffer(target, "%s",
7017 fmtId(tbinfo->attnames[objsubid - 1]));
7019 resetPQExpBuffer(query);
7020 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
7021 appendStringLiteralAH(query, descr, fout);
7022 appendPQExpBuffer(query, ";\n");
7024 ArchiveEntry(fout, nilCatalogId, createDumpId(),
7026 tbinfo->dobj.namespace->dobj.name,
7027 NULL, tbinfo->rolname,
7028 false, "COMMENT", SECTION_NONE,
7029 query->data, "", NULL,
7030 &(tbinfo->dobj.dumpId), 1,
7038 destroyPQExpBuffer(query);
7039 destroyPQExpBuffer(target);
7045 * Find the comment(s), if any, associated with the given object. All the
7046 * objsubid values associated with the given classoid/objoid are found with
7050 findComments(Archive *fout, Oid classoid, Oid objoid,
7051 CommentItem **items)
7053 /* static storage for table of comments */
7054 static CommentItem *comments = NULL;
7055 static int ncomments = -1;
7057 CommentItem *middle = NULL;
7062 /* Get comments if we didn't already */
7064 ncomments = collectComments(fout, &comments);
7067 * Pre-7.2, pg_description does not contain classoid, so collectComments
7068 * just stores a zero. If there's a collision on object OID, well, you
7069 * get duplicate comments.
7071 if (fout->remoteVersion < 70200)
7075 * Do binary search to find some item matching the object.
7078 high = &comments[ncomments - 1];
7081 middle = low + (high - low) / 2;
7083 if (classoid < middle->classoid)
7085 else if (classoid > middle->classoid)
7087 else if (objoid < middle->objoid)
7089 else if (objoid > middle->objoid)
7092 break; /* found a match */
7095 if (low > high) /* no matches */
7102 * Now determine how many items match the object. The search loop
7103 * invariant still holds: only items between low and high inclusive could
7107 while (middle > low)
7109 if (classoid != middle[-1].classoid ||
7110 objoid != middle[-1].objoid)
7119 while (middle <= high)
7121 if (classoid != middle->classoid ||
7122 objoid != middle->objoid)
7132 * collectComments --
7134 * Construct a table of all comments available for database objects.
7135 * We used to do per-object queries for the comments, but it's much faster
7136 * to pull them all over at once, and on most databases the memory cost
7139 * The table is sorted by classoid/objid/objsubid for speed in lookup.
7142 collectComments(Archive *fout, CommentItem **items)
7152 CommentItem *comments;
7155 * Note we do NOT change source schema here; preserve the caller's
7159 query = createPQExpBuffer();
7161 if (fout->remoteVersion >= 70300)
7163 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7164 "FROM pg_catalog.pg_description "
7165 "ORDER BY classoid, objoid, objsubid");
7167 else if (fout->remoteVersion >= 70200)
7169 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7170 "FROM pg_description "
7171 "ORDER BY classoid, objoid, objsubid");
7175 /* Note: this will fail to find attribute comments in pre-7.2... */
7176 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7177 "FROM pg_description "
7181 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7183 /* Construct lookup table containing OIDs in numeric form */
7185 i_description = PQfnumber(res, "description");
7186 i_classoid = PQfnumber(res, "classoid");
7187 i_objoid = PQfnumber(res, "objoid");
7188 i_objsubid = PQfnumber(res, "objsubid");
7190 ntups = PQntuples(res);
7192 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7194 for (i = 0; i < ntups; i++)
7196 comments[i].descr = PQgetvalue(res, i, i_description);
7197 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7198 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7199 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7202 /* Do NOT free the PGresult since we are keeping pointers into it */
7203 destroyPQExpBuffer(query);
7210 * dumpDumpableObject
7212 * This routine and its subsidiaries are responsible for creating
7213 * ArchiveEntries (TOC objects) for each object to be dumped.
7216 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7221 switch (dobj->objType)
7226 case DO_FK_CONSTRAINT:
7228 skip = !(dumpSections & DUMP_POST_DATA);
7231 skip = !(dumpSections & DUMP_DATA);
7234 skip = !(dumpSections & DUMP_PRE_DATA);
7240 switch (dobj->objType)
7243 dumpNamespace(fout, (NamespaceInfo *) dobj);
7246 dumpExtension(fout, (ExtensionInfo *) dobj);
7249 dumpType(fout, (TypeInfo *) dobj);
7252 dumpShellType(fout, (ShellTypeInfo *) dobj);
7255 dumpFunc(fout, (FuncInfo *) dobj);
7258 dumpAgg(fout, (AggInfo *) dobj);
7261 dumpOpr(fout, (OprInfo *) dobj);
7264 dumpOpclass(fout, (OpclassInfo *) dobj);
7267 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7270 dumpCollation(fout, (CollInfo *) dobj);
7273 dumpConversion(fout, (ConvInfo *) dobj);
7276 dumpTable(fout, (TableInfo *) dobj);
7279 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7282 dumpIndex(fout, (IndxInfo *) dobj);
7285 dumpRule(fout, (RuleInfo *) dobj);
7288 dumpTrigger(fout, (TriggerInfo *) dobj);
7291 dumpConstraint(fout, (ConstraintInfo *) dobj);
7293 case DO_FK_CONSTRAINT:
7294 dumpConstraint(fout, (ConstraintInfo *) dobj);
7297 dumpProcLang(fout, (ProcLangInfo *) dobj);
7300 dumpCast(fout, (CastInfo *) dobj);
7303 dumpTableData(fout, (TableDataInfo *) dobj);
7306 /* table rowtypes and array types are never dumped separately */
7309 dumpTSParser(fout, (TSParserInfo *) dobj);
7312 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7315 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7318 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7321 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7323 case DO_FOREIGN_SERVER:
7324 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7326 case DO_DEFAULT_ACL:
7327 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7330 dumpBlob(fout, (BlobInfo *) dobj);
7333 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7334 dobj->name, NULL, NULL, "",
7335 false, "BLOBS", SECTION_DATA,
7337 dobj->dependencies, dobj->nDeps,
7345 * writes out to fout the queries to recreate a user-defined namespace
7348 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7355 /* Skip if not to be dumped */
7356 if (!nspinfo->dobj.dump || dataOnly)
7359 /* don't dump dummy namespace from pre-7.3 source */
7360 if (strlen(nspinfo->dobj.name) == 0)
7363 q = createPQExpBuffer();
7364 delq = createPQExpBuffer();
7365 labelq = createPQExpBuffer();
7367 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7369 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7371 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7373 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7376 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7378 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7382 false, "SCHEMA", SECTION_PRE_DATA,
7383 q->data, delq->data, NULL,
7384 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7387 /* Dump Schema Comments and Security Labels */
7388 dumpComment(fout, labelq->data,
7389 NULL, nspinfo->rolname,
7390 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7391 dumpSecLabel(fout, labelq->data,
7392 NULL, nspinfo->rolname,
7393 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7395 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7396 qnspname, NULL, nspinfo->dobj.name, NULL,
7397 nspinfo->rolname, nspinfo->nspacl);
7401 destroyPQExpBuffer(q);
7402 destroyPQExpBuffer(delq);
7403 destroyPQExpBuffer(labelq);
7408 * writes out to fout the queries to recreate an extension
7411 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7418 /* Skip if not to be dumped */
7419 if (!extinfo->dobj.dump || dataOnly)
7422 q = createPQExpBuffer();
7423 delq = createPQExpBuffer();
7424 labelq = createPQExpBuffer();
7426 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7428 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7430 if (!binary_upgrade)
7433 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7434 * problem if the extension already exists in the target database;
7435 * this is essential for installed-by-default extensions such as
7438 * In binary-upgrade mode, that doesn't work well, so instead we skip
7439 * built-in extensions based on their OIDs; see
7440 * selectDumpableExtension.
7442 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7443 qextname, fmtId(extinfo->namespace));
7450 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7451 appendPQExpBuffer(q,
7452 "SELECT binary_upgrade.create_empty_extension(");
7453 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7454 appendPQExpBuffer(q, ", ");
7455 appendStringLiteralAH(q, extinfo->namespace, fout);
7456 appendPQExpBuffer(q, ", ");
7457 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7458 appendStringLiteralAH(q, extinfo->extversion, fout);
7459 appendPQExpBuffer(q, ", ");
7462 * Note that we're pushing extconfig (an OID array) back into
7463 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7464 * preserved in binary upgrade.
7466 if (strlen(extinfo->extconfig) > 2)
7467 appendStringLiteralAH(q, extinfo->extconfig, fout);
7469 appendPQExpBuffer(q, "NULL");
7470 appendPQExpBuffer(q, ", ");
7471 if (strlen(extinfo->extcondition) > 2)
7472 appendStringLiteralAH(q, extinfo->extcondition, fout);
7474 appendPQExpBuffer(q, "NULL");
7475 appendPQExpBuffer(q, ", ");
7476 appendPQExpBuffer(q, "ARRAY[");
7478 for (i = 0; i < extinfo->dobj.nDeps; i++)
7480 DumpableObject *extobj;
7482 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7483 if (extobj && extobj->objType == DO_EXTENSION)
7486 appendPQExpBuffer(q, ",");
7487 appendStringLiteralAH(q, extobj->name, fout);
7490 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7491 appendPQExpBuffer(q, ");\n");
7494 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7496 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7500 false, "EXTENSION", SECTION_PRE_DATA,
7501 q->data, delq->data, NULL,
7502 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7505 /* Dump Extension Comments and Security Labels */
7506 dumpComment(fout, labelq->data,
7508 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7509 dumpSecLabel(fout, labelq->data,
7511 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7515 destroyPQExpBuffer(q);
7516 destroyPQExpBuffer(delq);
7517 destroyPQExpBuffer(labelq);
7522 * writes out to fout the queries to recreate a user-defined type
7525 dumpType(Archive *fout, TypeInfo *tyinfo)
7527 /* Skip if not to be dumped */
7528 if (!tyinfo->dobj.dump || dataOnly)
7531 /* Dump out in proper style */
7532 if (tyinfo->typtype == TYPTYPE_BASE)
7533 dumpBaseType(fout, tyinfo);
7534 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7535 dumpDomain(fout, tyinfo);
7536 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7537 dumpCompositeType(fout, tyinfo);
7538 else if (tyinfo->typtype == TYPTYPE_ENUM)
7539 dumpEnumType(fout, tyinfo);
7540 else if (tyinfo->typtype == TYPTYPE_RANGE)
7541 dumpRangeType(fout, tyinfo);
7543 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7549 * writes out to fout the queries to recreate a user-defined enum type
7552 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7554 PQExpBuffer q = createPQExpBuffer();
7555 PQExpBuffer delq = createPQExpBuffer();
7556 PQExpBuffer labelq = createPQExpBuffer();
7557 PQExpBuffer query = createPQExpBuffer();
7564 /* Set proper schema search path */
7565 selectSourceSchema(fout, "pg_catalog");
7567 if (fout->remoteVersion >= 90100)
7568 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7569 "FROM pg_catalog.pg_enum "
7570 "WHERE enumtypid = '%u'"
7571 "ORDER BY enumsortorder",
7572 tyinfo->dobj.catId.oid);
7574 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7575 "FROM pg_catalog.pg_enum "
7576 "WHERE enumtypid = '%u'"
7578 tyinfo->dobj.catId.oid);
7580 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7582 num = PQntuples(res);
7585 * DROP must be fully qualified in case same name appears in pg_catalog.
7586 * CASCADE shouldn't be required here as for normal types since the I/O
7587 * functions are generic and do not get dropped.
7589 appendPQExpBuffer(delq, "DROP TYPE %s.",
7590 fmtId(tyinfo->dobj.namespace->dobj.name));
7591 appendPQExpBuffer(delq, "%s;\n",
7592 fmtId(tyinfo->dobj.name));
7595 binary_upgrade_set_type_oids_by_type_oid(fout, q,
7596 tyinfo->dobj.catId.oid);
7598 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7599 fmtId(tyinfo->dobj.name));
7601 if (!binary_upgrade)
7603 /* Labels with server-assigned oids */
7604 for (i = 0; i < num; i++)
7606 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7608 appendPQExpBuffer(q, ",");
7609 appendPQExpBuffer(q, "\n ");
7610 appendStringLiteralAH(q, label, fout);
7614 appendPQExpBuffer(q, "\n);\n");
7618 /* Labels with dump-assigned (preserved) oids */
7619 for (i = 0; i < num; i++)
7621 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7622 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7625 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7626 appendPQExpBuffer(q,
7627 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7629 appendPQExpBuffer(q, "ALTER TYPE %s.",
7630 fmtId(tyinfo->dobj.namespace->dobj.name));
7631 appendPQExpBuffer(q, "%s ADD VALUE ",
7632 fmtId(tyinfo->dobj.name));
7633 appendStringLiteralAH(q, label, fout);
7634 appendPQExpBuffer(q, ";\n\n");
7638 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7641 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7643 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7645 tyinfo->dobj.namespace->dobj.name,
7647 tyinfo->rolname, false,
7648 "TYPE", SECTION_PRE_DATA,
7649 q->data, delq->data, NULL,
7650 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7653 /* Dump Type Comments and Security Labels */
7654 dumpComment(fout, labelq->data,
7655 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7656 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7657 dumpSecLabel(fout, labelq->data,
7658 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7659 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7662 destroyPQExpBuffer(q);
7663 destroyPQExpBuffer(delq);
7664 destroyPQExpBuffer(labelq);
7665 destroyPQExpBuffer(query);
7670 * writes out to fout the queries to recreate a user-defined range type
7673 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7675 PQExpBuffer q = createPQExpBuffer();
7676 PQExpBuffer delq = createPQExpBuffer();
7677 PQExpBuffer labelq = createPQExpBuffer();
7678 PQExpBuffer query = createPQExpBuffer();
7684 * select appropriate schema to ensure names in CREATE are properly
7687 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7689 appendPQExpBuffer(query,
7690 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7691 "opc.opcname AS opcname, "
7692 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7693 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7695 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7696 " ELSE rngcollation END AS collation, "
7697 "rngcanonical, rngsubdiff "
7698 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7699 " pg_catalog.pg_opclass opc "
7700 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7702 tyinfo->dobj.catId.oid);
7704 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7705 if (PQntuples(res) != 1)
7707 write_msg(NULL, "query returned %d pg_range entries for range type \"%s\"\n",
7708 PQntuples(res), tyinfo->dobj.name);
7713 * DROP must be fully qualified in case same name appears in pg_catalog.
7714 * CASCADE shouldn't be required here as for normal types since the I/O
7715 * functions are generic and do not get dropped.
7717 appendPQExpBuffer(delq, "DROP TYPE %s.",
7718 fmtId(tyinfo->dobj.namespace->dobj.name));
7719 appendPQExpBuffer(delq, "%s;\n",
7720 fmtId(tyinfo->dobj.name));
7723 binary_upgrade_set_type_oids_by_type_oid(fout,
7724 q, tyinfo->dobj.catId.oid);
7726 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7727 fmtId(tyinfo->dobj.name));
7729 appendPQExpBuffer(q, "\n subtype = %s",
7730 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7732 /* print subtype_opclass only if not default for subtype */
7733 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7735 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7736 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7738 /* always schema-qualify, don't try to be smart */
7739 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7741 appendPQExpBuffer(q, "%s", fmtId(opcname));
7744 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7745 if (OidIsValid(collationOid))
7747 CollInfo *coll = findCollationByOid(collationOid);
7751 /* always schema-qualify, don't try to be smart */
7752 appendPQExpBuffer(q, ",\n collation = %s.",
7753 fmtId(coll->dobj.namespace->dobj.name));
7754 appendPQExpBuffer(q, "%s",
7755 fmtId(coll->dobj.name));
7759 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7760 if (strcmp(procname, "-") != 0)
7761 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7763 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7764 if (strcmp(procname, "-") != 0)
7765 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7767 appendPQExpBuffer(q, "\n);\n");
7769 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7772 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7774 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7776 tyinfo->dobj.namespace->dobj.name,
7778 tyinfo->rolname, false,
7779 "TYPE", SECTION_PRE_DATA,
7780 q->data, delq->data, NULL,
7781 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7784 /* Dump Type Comments and Security Labels */
7785 dumpComment(fout, labelq->data,
7786 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7787 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7788 dumpSecLabel(fout, labelq->data,
7789 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7790 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7793 destroyPQExpBuffer(q);
7794 destroyPQExpBuffer(delq);
7795 destroyPQExpBuffer(labelq);
7796 destroyPQExpBuffer(query);
7801 * writes out to fout the queries to recreate a user-defined base type
7804 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7806 PQExpBuffer q = createPQExpBuffer();
7807 PQExpBuffer delq = createPQExpBuffer();
7808 PQExpBuffer labelq = createPQExpBuffer();
7809 PQExpBuffer query = createPQExpBuffer();
7826 char *typispreferred;
7831 char *typcollatable;
7833 bool typdefault_is_literal = false;
7835 /* Set proper schema search path so regproc references list correctly */
7836 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
7838 /* Fetch type-specific details */
7839 if (fout->remoteVersion >= 90100)
7841 appendPQExpBuffer(query, "SELECT typlen, "
7842 "typinput, typoutput, typreceive, typsend, "
7843 "typmodin, typmodout, typanalyze, "
7844 "typreceive::pg_catalog.oid AS typreceiveoid, "
7845 "typsend::pg_catalog.oid AS typsendoid, "
7846 "typmodin::pg_catalog.oid AS typmodinoid, "
7847 "typmodout::pg_catalog.oid AS typmodoutoid, "
7848 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7849 "typcategory, typispreferred, "
7850 "typdelim, typbyval, typalign, typstorage, "
7851 "(typcollation <> 0) AS typcollatable, "
7852 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7853 "FROM pg_catalog.pg_type "
7854 "WHERE oid = '%u'::pg_catalog.oid",
7855 tyinfo->dobj.catId.oid);
7857 else if (fout->remoteVersion >= 80400)
7859 appendPQExpBuffer(query, "SELECT typlen, "
7860 "typinput, typoutput, typreceive, typsend, "
7861 "typmodin, typmodout, typanalyze, "
7862 "typreceive::pg_catalog.oid AS typreceiveoid, "
7863 "typsend::pg_catalog.oid AS typsendoid, "
7864 "typmodin::pg_catalog.oid AS typmodinoid, "
7865 "typmodout::pg_catalog.oid AS typmodoutoid, "
7866 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7867 "typcategory, typispreferred, "
7868 "typdelim, typbyval, typalign, typstorage, "
7869 "false AS typcollatable, "
7870 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7871 "FROM pg_catalog.pg_type "
7872 "WHERE oid = '%u'::pg_catalog.oid",
7873 tyinfo->dobj.catId.oid);
7875 else if (fout->remoteVersion >= 80300)
7877 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7878 appendPQExpBuffer(query, "SELECT typlen, "
7879 "typinput, typoutput, typreceive, typsend, "
7880 "typmodin, typmodout, typanalyze, "
7881 "typreceive::pg_catalog.oid AS typreceiveoid, "
7882 "typsend::pg_catalog.oid AS typsendoid, "
7883 "typmodin::pg_catalog.oid AS typmodinoid, "
7884 "typmodout::pg_catalog.oid AS typmodoutoid, "
7885 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7886 "'U' AS typcategory, false AS typispreferred, "
7887 "typdelim, typbyval, typalign, typstorage, "
7888 "false AS typcollatable, "
7889 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7890 "FROM pg_catalog.pg_type "
7891 "WHERE oid = '%u'::pg_catalog.oid",
7892 tyinfo->dobj.catId.oid);
7894 else if (fout->remoteVersion >= 80000)
7896 appendPQExpBuffer(query, "SELECT typlen, "
7897 "typinput, typoutput, typreceive, typsend, "
7898 "'-' AS typmodin, '-' AS typmodout, "
7900 "typreceive::pg_catalog.oid AS typreceiveoid, "
7901 "typsend::pg_catalog.oid AS typsendoid, "
7902 "0 AS typmodinoid, 0 AS typmodoutoid, "
7903 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7904 "'U' AS typcategory, false AS typispreferred, "
7905 "typdelim, typbyval, typalign, typstorage, "
7906 "false AS typcollatable, "
7907 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7908 "FROM pg_catalog.pg_type "
7909 "WHERE oid = '%u'::pg_catalog.oid",
7910 tyinfo->dobj.catId.oid);
7912 else if (fout->remoteVersion >= 70400)
7914 appendPQExpBuffer(query, "SELECT typlen, "
7915 "typinput, typoutput, typreceive, typsend, "
7916 "'-' AS typmodin, '-' AS typmodout, "
7917 "'-' AS typanalyze, "
7918 "typreceive::pg_catalog.oid AS typreceiveoid, "
7919 "typsend::pg_catalog.oid AS typsendoid, "
7920 "0 AS typmodinoid, 0 AS typmodoutoid, "
7921 "0 AS typanalyzeoid, "
7922 "'U' AS typcategory, false AS typispreferred, "
7923 "typdelim, typbyval, typalign, typstorage, "
7924 "false AS typcollatable, "
7925 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7926 "FROM pg_catalog.pg_type "
7927 "WHERE oid = '%u'::pg_catalog.oid",
7928 tyinfo->dobj.catId.oid);
7930 else if (fout->remoteVersion >= 70300)
7932 appendPQExpBuffer(query, "SELECT typlen, "
7933 "typinput, typoutput, "
7934 "'-' AS typreceive, '-' AS typsend, "
7935 "'-' AS typmodin, '-' AS typmodout, "
7936 "'-' AS typanalyze, "
7937 "0 AS typreceiveoid, 0 AS typsendoid, "
7938 "0 AS typmodinoid, 0 AS typmodoutoid, "
7939 "0 AS typanalyzeoid, "
7940 "'U' AS typcategory, false AS typispreferred, "
7941 "typdelim, typbyval, typalign, typstorage, "
7942 "false AS typcollatable, "
7943 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7944 "FROM pg_catalog.pg_type "
7945 "WHERE oid = '%u'::pg_catalog.oid",
7946 tyinfo->dobj.catId.oid);
7948 else if (fout->remoteVersion >= 70200)
7951 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7952 * ignore them because they are not right.
7954 appendPQExpBuffer(query, "SELECT typlen, "
7955 "typinput, typoutput, "
7956 "'-' AS typreceive, '-' AS typsend, "
7957 "'-' AS typmodin, '-' AS typmodout, "
7958 "'-' AS typanalyze, "
7959 "0 AS typreceiveoid, 0 AS typsendoid, "
7960 "0 AS typmodinoid, 0 AS typmodoutoid, "
7961 "0 AS typanalyzeoid, "
7962 "'U' AS typcategory, false AS typispreferred, "
7963 "typdelim, typbyval, typalign, typstorage, "
7964 "false AS typcollatable, "
7965 "NULL AS typdefaultbin, typdefault "
7967 "WHERE oid = '%u'::oid",
7968 tyinfo->dobj.catId.oid);
7970 else if (fout->remoteVersion >= 70100)
7973 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7976 appendPQExpBuffer(query, "SELECT typlen, "
7977 "typinput, typoutput, "
7978 "'-' AS typreceive, '-' AS typsend, "
7979 "'-' AS typmodin, '-' AS typmodout, "
7980 "'-' AS typanalyze, "
7981 "0 AS typreceiveoid, 0 AS typsendoid, "
7982 "0 AS typmodinoid, 0 AS typmodoutoid, "
7983 "0 AS typanalyzeoid, "
7984 "'U' AS typcategory, false AS typispreferred, "
7985 "typdelim, typbyval, typalign, typstorage, "
7986 "false AS typcollatable, "
7987 "NULL AS typdefaultbin, NULL AS typdefault "
7989 "WHERE oid = '%u'::oid",
7990 tyinfo->dobj.catId.oid);
7994 appendPQExpBuffer(query, "SELECT typlen, "
7995 "typinput, typoutput, "
7996 "'-' AS typreceive, '-' AS typsend, "
7997 "'-' AS typmodin, '-' AS typmodout, "
7998 "'-' AS typanalyze, "
7999 "0 AS typreceiveoid, 0 AS typsendoid, "
8000 "0 AS typmodinoid, 0 AS typmodoutoid, "
8001 "0 AS typanalyzeoid, "
8002 "'U' AS typcategory, false AS typispreferred, "
8003 "typdelim, typbyval, typalign, "
8004 "'p'::char AS typstorage, "
8005 "false AS typcollatable, "
8006 "NULL AS typdefaultbin, NULL AS typdefault "
8008 "WHERE oid = '%u'::oid",
8009 tyinfo->dobj.catId.oid);
8012 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8014 /* Expecting a single result only */
8015 ntups = PQntuples(res);
8018 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8019 "query returned %d rows instead of one: %s\n",
8021 ntups, query->data);
8025 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
8026 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
8027 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
8028 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
8029 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
8030 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
8031 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
8032 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
8033 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
8034 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
8035 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
8036 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
8037 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
8038 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
8039 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
8040 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
8041 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
8042 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
8043 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
8044 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
8045 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8046 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8047 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8049 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8050 typdefault_is_literal = true; /* it needs quotes */
8056 * DROP must be fully qualified in case same name appears in pg_catalog.
8057 * The reason we include CASCADE is that the circular dependency between
8058 * the type and its I/O functions makes it impossible to drop the type any
8061 appendPQExpBuffer(delq, "DROP TYPE %s.",
8062 fmtId(tyinfo->dobj.namespace->dobj.name));
8063 appendPQExpBuffer(delq, "%s CASCADE;\n",
8064 fmtId(tyinfo->dobj.name));
8066 /* We might already have a shell type, but setting pg_type_oid is harmless */
8068 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8069 tyinfo->dobj.catId.oid);
8071 appendPQExpBuffer(q,
8072 "CREATE TYPE %s (\n"
8073 " INTERNALLENGTH = %s",
8074 fmtId(tyinfo->dobj.name),
8075 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
8077 if (fout->remoteVersion >= 70300)
8079 /* regproc result is correctly quoted as of 7.3 */
8080 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
8081 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
8082 if (OidIsValid(typreceiveoid))
8083 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
8084 if (OidIsValid(typsendoid))
8085 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
8086 if (OidIsValid(typmodinoid))
8087 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
8088 if (OidIsValid(typmodoutoid))
8089 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
8090 if (OidIsValid(typanalyzeoid))
8091 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
8095 /* regproc delivers an unquoted name before 7.3 */
8096 /* cannot combine these because fmtId uses static result area */
8097 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
8098 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
8099 /* receive/send/typmodin/typmodout/analyze need not be printed */
8102 if (strcmp(typcollatable, "t") == 0)
8103 appendPQExpBuffer(q, ",\n COLLATABLE = true");
8105 if (typdefault != NULL)
8107 appendPQExpBuffer(q, ",\n DEFAULT = ");
8108 if (typdefault_is_literal)
8109 appendStringLiteralAH(q, typdefault, fout);
8111 appendPQExpBufferStr(q, typdefault);
8114 if (OidIsValid(tyinfo->typelem))
8118 /* reselect schema in case changed by function dump */
8119 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8120 elemType = getFormattedTypeName(fout, tyinfo->typelem, zeroAsOpaque);
8121 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
8125 if (strcmp(typcategory, "U") != 0)
8127 appendPQExpBuffer(q, ",\n CATEGORY = ");
8128 appendStringLiteralAH(q, typcategory, fout);
8131 if (strcmp(typispreferred, "t") == 0)
8132 appendPQExpBuffer(q, ",\n PREFERRED = true");
8134 if (typdelim && strcmp(typdelim, ",") != 0)
8136 appendPQExpBuffer(q, ",\n DELIMITER = ");
8137 appendStringLiteralAH(q, typdelim, fout);
8140 if (strcmp(typalign, "c") == 0)
8141 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
8142 else if (strcmp(typalign, "s") == 0)
8143 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
8144 else if (strcmp(typalign, "i") == 0)
8145 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
8146 else if (strcmp(typalign, "d") == 0)
8147 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
8149 if (strcmp(typstorage, "p") == 0)
8150 appendPQExpBuffer(q, ",\n STORAGE = plain");
8151 else if (strcmp(typstorage, "e") == 0)
8152 appendPQExpBuffer(q, ",\n STORAGE = external");
8153 else if (strcmp(typstorage, "x") == 0)
8154 appendPQExpBuffer(q, ",\n STORAGE = extended");
8155 else if (strcmp(typstorage, "m") == 0)
8156 appendPQExpBuffer(q, ",\n STORAGE = main");
8158 if (strcmp(typbyval, "t") == 0)
8159 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
8161 appendPQExpBuffer(q, "\n);\n");
8163 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8166 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8168 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8170 tyinfo->dobj.namespace->dobj.name,
8172 tyinfo->rolname, false,
8173 "TYPE", SECTION_PRE_DATA,
8174 q->data, delq->data, NULL,
8175 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8178 /* Dump Type Comments and Security Labels */
8179 dumpComment(fout, labelq->data,
8180 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8181 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8182 dumpSecLabel(fout, labelq->data,
8183 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8184 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8187 destroyPQExpBuffer(q);
8188 destroyPQExpBuffer(delq);
8189 destroyPQExpBuffer(labelq);
8190 destroyPQExpBuffer(query);
8195 * writes out to fout the queries to recreate a user-defined domain
8198 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8200 PQExpBuffer q = createPQExpBuffer();
8201 PQExpBuffer delq = createPQExpBuffer();
8202 PQExpBuffer labelq = createPQExpBuffer();
8203 PQExpBuffer query = createPQExpBuffer();
8211 bool typdefault_is_literal = false;
8213 /* Set proper schema search path so type references list correctly */
8214 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8216 /* Fetch domain specific details */
8217 if (fout->remoteVersion >= 90100)
8219 /* typcollation is new in 9.1 */
8220 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8221 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8222 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8224 "CASE WHEN t.typcollation <> u.typcollation "
8225 "THEN t.typcollation ELSE 0 END AS typcollation "
8226 "FROM pg_catalog.pg_type t "
8227 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8228 "WHERE t.oid = '%u'::pg_catalog.oid",
8229 tyinfo->dobj.catId.oid);
8233 /* We assume here that remoteVersion must be at least 70300 */
8234 appendPQExpBuffer(query, "SELECT typnotnull, "
8235 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8236 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8237 "typdefault, 0 AS typcollation "
8238 "FROM pg_catalog.pg_type "
8239 "WHERE oid = '%u'::pg_catalog.oid",
8240 tyinfo->dobj.catId.oid);
8243 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8245 /* Expecting a single result only */
8246 ntups = PQntuples(res);
8249 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8250 "query returned %d rows instead of one: %s\n",
8252 ntups, query->data);
8256 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8257 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8258 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8259 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8260 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8262 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8263 typdefault_is_literal = true; /* it needs quotes */
8267 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8270 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8271 tyinfo->dobj.catId.oid);
8273 appendPQExpBuffer(q,
8274 "CREATE DOMAIN %s AS %s",
8275 fmtId(tyinfo->dobj.name),
8278 /* Print collation only if different from base type's collation */
8279 if (OidIsValid(typcollation))
8283 coll = findCollationByOid(typcollation);
8286 /* always schema-qualify, don't try to be smart */
8287 appendPQExpBuffer(q, " COLLATE %s.",
8288 fmtId(coll->dobj.namespace->dobj.name));
8289 appendPQExpBuffer(q, "%s",
8290 fmtId(coll->dobj.name));
8294 if (typnotnull[0] == 't')
8295 appendPQExpBuffer(q, " NOT NULL");
8297 if (typdefault != NULL)
8299 appendPQExpBuffer(q, " DEFAULT ");
8300 if (typdefault_is_literal)
8301 appendStringLiteralAH(q, typdefault, fout);
8303 appendPQExpBufferStr(q, typdefault);
8309 * Add any CHECK constraints for the domain
8311 for (i = 0; i < tyinfo->nDomChecks; i++)
8313 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8315 if (!domcheck->separate)
8316 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8317 fmtId(domcheck->dobj.name), domcheck->condef);
8320 appendPQExpBuffer(q, ";\n");
8323 * DROP must be fully qualified in case same name appears in pg_catalog
8325 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8326 fmtId(tyinfo->dobj.namespace->dobj.name));
8327 appendPQExpBuffer(delq, "%s;\n",
8328 fmtId(tyinfo->dobj.name));
8330 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8333 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8335 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8337 tyinfo->dobj.namespace->dobj.name,
8339 tyinfo->rolname, false,
8340 "DOMAIN", SECTION_PRE_DATA,
8341 q->data, delq->data, NULL,
8342 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8345 /* Dump Domain Comments and Security Labels */
8346 dumpComment(fout, labelq->data,
8347 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8348 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8349 dumpSecLabel(fout, labelq->data,
8350 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8351 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8353 destroyPQExpBuffer(q);
8354 destroyPQExpBuffer(delq);
8355 destroyPQExpBuffer(labelq);
8356 destroyPQExpBuffer(query);
8361 * writes out to fout the queries to recreate a user-defined stand-alone
8365 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8367 PQExpBuffer q = createPQExpBuffer();
8368 PQExpBuffer dropped = createPQExpBuffer();
8369 PQExpBuffer delq = createPQExpBuffer();
8370 PQExpBuffer labelq = createPQExpBuffer();
8371 PQExpBuffer query = createPQExpBuffer();
8384 /* Set proper schema search path so type references list correctly */
8385 selectSourceSchema(fout, tyinfo->dobj.namespace->dobj.name);
8387 /* Fetch type specific details */
8388 if (fout->remoteVersion >= 90100)
8391 * attcollation is new in 9.1. Since we only want to dump COLLATE
8392 * clauses for attributes whose collation is different from their
8393 * type's default, we use a CASE here to suppress uninteresting
8394 * attcollations cheaply. atttypid will be 0 for dropped columns;
8395 * collation does not matter for those.
8397 appendPQExpBuffer(query, "SELECT a.attname, "
8398 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8399 "a.attlen, a.attalign, a.attisdropped, "
8400 "CASE WHEN a.attcollation <> at.typcollation "
8401 "THEN a.attcollation ELSE 0 END AS attcollation, "
8403 "FROM pg_catalog.pg_type ct "
8404 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8405 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8406 "WHERE ct.oid = '%u'::pg_catalog.oid "
8407 "ORDER BY a.attnum ",
8408 tyinfo->dobj.catId.oid);
8413 * We assume here that remoteVersion must be at least 70300. Since
8414 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8417 appendPQExpBuffer(query, "SELECT a.attname, "
8418 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8419 "a.attlen, a.attalign, a.attisdropped, "
8420 "0 AS attcollation, "
8422 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8423 "WHERE ct.oid = '%u'::pg_catalog.oid "
8424 "AND a.attrelid = ct.typrelid "
8425 "ORDER BY a.attnum ",
8426 tyinfo->dobj.catId.oid);
8429 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8431 ntups = PQntuples(res);
8433 i_attname = PQfnumber(res, "attname");
8434 i_atttypdefn = PQfnumber(res, "atttypdefn");
8435 i_attlen = PQfnumber(res, "attlen");
8436 i_attalign = PQfnumber(res, "attalign");
8437 i_attisdropped = PQfnumber(res, "attisdropped");
8438 i_attcollation = PQfnumber(res, "attcollation");
8439 i_typrelid = PQfnumber(res, "typrelid");
8443 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8445 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8446 tyinfo->dobj.catId.oid);
8447 binary_upgrade_set_pg_class_oids(fout, q, typrelid, false);
8450 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8451 fmtId(tyinfo->dobj.name));
8454 for (i = 0; i < ntups; i++)
8463 attname = PQgetvalue(res, i, i_attname);
8464 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8465 attlen = PQgetvalue(res, i, i_attlen);
8466 attalign = PQgetvalue(res, i, i_attalign);
8467 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8468 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8470 if (attisdropped && !binary_upgrade)
8473 /* Format properly if not first attr */
8474 if (actual_atts++ > 0)
8475 appendPQExpBuffer(q, ",");
8476 appendPQExpBuffer(q, "\n\t");
8480 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8482 /* Add collation if not default for the column type */
8483 if (OidIsValid(attcollation))
8487 coll = findCollationByOid(attcollation);
8490 /* always schema-qualify, don't try to be smart */
8491 appendPQExpBuffer(q, " COLLATE %s.",
8492 fmtId(coll->dobj.namespace->dobj.name));
8493 appendPQExpBuffer(q, "%s",
8494 fmtId(coll->dobj.name));
8501 * This is a dropped attribute and we're in binary_upgrade mode.
8502 * Insert a placeholder for it in the CREATE TYPE command, and set
8503 * length and alignment with direct UPDATE to the catalogs
8504 * afterwards. See similar code in dumpTableSchema().
8506 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8508 /* stash separately for insertion after the CREATE TYPE */
8509 appendPQExpBuffer(dropped,
8510 "\n-- For binary upgrade, recreate dropped column.\n");
8511 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8513 "attalign = '%s', attbyval = false\n"
8514 "WHERE attname = ", attlen, attalign);
8515 appendStringLiteralAH(dropped, attname, fout);
8516 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8517 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8518 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8520 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8521 fmtId(tyinfo->dobj.name));
8522 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8526 appendPQExpBuffer(q, "\n);\n");
8527 appendPQExpBufferStr(q, dropped->data);
8530 * DROP must be fully qualified in case same name appears in pg_catalog
8532 appendPQExpBuffer(delq, "DROP TYPE %s.",
8533 fmtId(tyinfo->dobj.namespace->dobj.name));
8534 appendPQExpBuffer(delq, "%s;\n",
8535 fmtId(tyinfo->dobj.name));
8537 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8540 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8542 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8544 tyinfo->dobj.namespace->dobj.name,
8546 tyinfo->rolname, false,
8547 "TYPE", SECTION_PRE_DATA,
8548 q->data, delq->data, NULL,
8549 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8553 /* Dump Type Comments and Security Labels */
8554 dumpComment(fout, labelq->data,
8555 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8556 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8557 dumpSecLabel(fout, labelq->data,
8558 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8559 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8562 destroyPQExpBuffer(q);
8563 destroyPQExpBuffer(dropped);
8564 destroyPQExpBuffer(delq);
8565 destroyPQExpBuffer(labelq);
8566 destroyPQExpBuffer(query);
8568 /* Dump any per-column comments */
8569 dumpCompositeTypeColComments(fout, tyinfo);
8573 * dumpCompositeTypeColComments
8574 * writes out to fout the queries to recreate comments on the columns of
8575 * a user-defined stand-alone composite type
8578 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8580 CommentItem *comments;
8591 query = createPQExpBuffer();
8593 /* We assume here that remoteVersion must be at least 70300 */
8594 appendPQExpBuffer(query,
8595 "SELECT c.tableoid, a.attname, a.attnum "
8596 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8597 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8598 " AND NOT a.attisdropped "
8599 "ORDER BY a.attnum ",
8602 /* Fetch column attnames */
8603 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8605 ntups = PQntuples(res);
8609 destroyPQExpBuffer(query);
8613 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8615 /* Search for comments associated with type's pg_class OID */
8616 ncomments = findComments(fout,
8621 /* If no comments exist, we're done */
8625 destroyPQExpBuffer(query);
8629 /* Build COMMENT ON statements */
8630 target = createPQExpBuffer();
8632 i_attnum = PQfnumber(res, "attnum");
8633 i_attname = PQfnumber(res, "attname");
8634 while (ncomments > 0)
8636 const char *attname;
8639 for (i = 0; i < ntups; i++)
8641 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8643 attname = PQgetvalue(res, i, i_attname);
8647 if (attname) /* just in case we don't find it */
8649 const char *descr = comments->descr;
8651 resetPQExpBuffer(target);
8652 appendPQExpBuffer(target, "COLUMN %s.",
8653 fmtId(tyinfo->dobj.name));
8654 appendPQExpBuffer(target, "%s",
8657 resetPQExpBuffer(query);
8658 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8659 appendStringLiteralAH(query, descr, fout);
8660 appendPQExpBuffer(query, ";\n");
8662 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8664 tyinfo->dobj.namespace->dobj.name,
8665 NULL, tyinfo->rolname,
8666 false, "COMMENT", SECTION_NONE,
8667 query->data, "", NULL,
8668 &(tyinfo->dobj.dumpId), 1,
8677 destroyPQExpBuffer(query);
8678 destroyPQExpBuffer(target);
8683 * writes out to fout the queries to create a shell type
8685 * We dump a shell definition in advance of the I/O functions for the type.
8688 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8692 /* Skip if not to be dumped */
8693 if (!stinfo->dobj.dump || dataOnly)
8696 q = createPQExpBuffer();
8699 * Note the lack of a DROP command for the shell type; any required DROP
8700 * is driven off the base type entry, instead. This interacts with
8701 * _printTocEntry()'s use of the presence of a DROP command to decide
8702 * whether an entry needs an ALTER OWNER command. We don't want to alter
8703 * the shell type's owner immediately on creation; that should happen only
8704 * after it's filled in, otherwise the backend complains.
8708 binary_upgrade_set_type_oids_by_type_oid(fout, q,
8709 stinfo->baseType->dobj.catId.oid);
8711 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8712 fmtId(stinfo->dobj.name));
8714 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8716 stinfo->dobj.namespace->dobj.name,
8718 stinfo->baseType->rolname, false,
8719 "SHELL TYPE", SECTION_PRE_DATA,
8721 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8724 destroyPQExpBuffer(q);
8728 * Determine whether we want to dump definitions for procedural languages.
8729 * Since the languages themselves don't have schemas, we can't rely on
8730 * the normal schema-based selection mechanism. We choose to dump them
8731 * whenever neither --schema nor --table was given. (Before 8.1, we used
8732 * the dump flag of the PL's call handler function, but in 8.1 this will
8733 * probably always be false since call handlers are created in pg_catalog.)
8735 * For some backwards compatibility with the older behavior, we forcibly
8736 * dump a PL if its handler function (and validator if any) are in a
8737 * dumpable namespace. That case is not checked here.
8739 * Also, if the PL belongs to an extension, we do not use this heuristic.
8740 * That case isn't checked here either.
8743 shouldDumpProcLangs(void)
8745 if (!include_everything)
8747 /* And they're schema not data */
8755 * writes out to fout the queries to recreate a user-defined
8756 * procedural language
8759 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8768 FuncInfo *inlineInfo = NULL;
8769 FuncInfo *validatorInfo = NULL;
8771 /* Skip if not to be dumped */
8772 if (!plang->dobj.dump || dataOnly)
8776 * Try to find the support function(s). It is not an error if we don't
8777 * find them --- if the functions are in the pg_catalog schema, as is
8778 * standard in 8.1 and up, then we won't have loaded them. (In this case
8779 * we will emit a parameterless CREATE LANGUAGE command, which will
8780 * require PL template knowledge in the backend to reload.)
8783 funcInfo = findFuncByOid(plang->lanplcallfoid);
8784 if (funcInfo != NULL && !funcInfo->dobj.dump)
8785 funcInfo = NULL; /* treat not-dumped same as not-found */
8787 if (OidIsValid(plang->laninline))
8789 inlineInfo = findFuncByOid(plang->laninline);
8790 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8794 if (OidIsValid(plang->lanvalidator))
8796 validatorInfo = findFuncByOid(plang->lanvalidator);
8797 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8798 validatorInfo = NULL;
8802 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8803 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8806 * However, for a language that belongs to an extension, we must not use
8807 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8808 * told to (via dobj.dump). Generally the support functions will belong
8809 * to the same extension and so have the same dump flags ... if they
8810 * don't, this might not work terribly nicely.
8812 useParams = (funcInfo != NULL &&
8813 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8814 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8816 if (!plang->dobj.ext_member)
8818 if (!useParams && !shouldDumpProcLangs())
8822 defqry = createPQExpBuffer();
8823 delqry = createPQExpBuffer();
8824 labelq = createPQExpBuffer();
8826 qlanname = pg_strdup(fmtId(plang->dobj.name));
8829 * If dumping a HANDLER clause, treat the language as being in the handler
8830 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8831 * it doesn't really have a schema.
8834 lanschema = funcInfo->dobj.namespace->dobj.name;
8838 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8843 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8844 plang->lanpltrusted ? "TRUSTED " : "",
8846 appendPQExpBuffer(defqry, " HANDLER %s",
8847 fmtId(funcInfo->dobj.name));
8848 if (OidIsValid(plang->laninline))
8850 appendPQExpBuffer(defqry, " INLINE ");
8851 /* Cope with possibility that inline is in different schema */
8852 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8853 appendPQExpBuffer(defqry, "%s.",
8854 fmtId(inlineInfo->dobj.namespace->dobj.name));
8855 appendPQExpBuffer(defqry, "%s",
8856 fmtId(inlineInfo->dobj.name));
8858 if (OidIsValid(plang->lanvalidator))
8860 appendPQExpBuffer(defqry, " VALIDATOR ");
8861 /* Cope with possibility that validator is in different schema */
8862 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8863 appendPQExpBuffer(defqry, "%s.",
8864 fmtId(validatorInfo->dobj.namespace->dobj.name));
8865 appendPQExpBuffer(defqry, "%s",
8866 fmtId(validatorInfo->dobj.name));
8872 * If not dumping parameters, then use CREATE OR REPLACE so that the
8873 * command will not fail if the language is preinstalled in the target
8874 * database. We restrict the use of REPLACE to this case so as to
8875 * eliminate the risk of replacing a language with incompatible
8876 * parameter settings: this command will only succeed at all if there
8877 * is a pg_pltemplate entry, and if there is one, the existing entry
8878 * must match it too.
8880 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8883 appendPQExpBuffer(defqry, ";\n");
8885 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8888 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8890 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8892 lanschema, NULL, plang->lanowner,
8893 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8894 defqry->data, delqry->data, NULL,
8895 plang->dobj.dependencies, plang->dobj.nDeps,
8898 /* Dump Proc Lang Comments and Security Labels */
8899 dumpComment(fout, labelq->data,
8901 plang->dobj.catId, 0, plang->dobj.dumpId);
8902 dumpSecLabel(fout, labelq->data,
8904 plang->dobj.catId, 0, plang->dobj.dumpId);
8906 if (plang->lanpltrusted)
8907 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8908 qlanname, NULL, plang->dobj.name,
8910 plang->lanowner, plang->lanacl);
8914 destroyPQExpBuffer(defqry);
8915 destroyPQExpBuffer(delqry);
8916 destroyPQExpBuffer(labelq);
8920 * format_function_arguments: generate function name and argument list
8922 * This is used when we can rely on pg_get_function_arguments to format
8923 * the argument list.
8926 format_function_arguments(FuncInfo *finfo, char *funcargs)
8930 initPQExpBuffer(&fn);
8931 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8936 * format_function_arguments_old: generate function name and argument list
8938 * The argument type names are qualified if needed. The function name
8939 * is never qualified.
8941 * This is used only with pre-8.4 servers, so we aren't expecting to see
8942 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8944 * Any or all of allargtypes, argmodes, argnames may be NULL.
8947 format_function_arguments_old(Archive *fout,
8948 FuncInfo *finfo, int nallargs,
8956 initPQExpBuffer(&fn);
8957 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8958 for (j = 0; j < nallargs; j++)
8962 const char *argmode;
8963 const char *argname;
8965 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8966 typname = getFormattedTypeName(fout, typid, zeroAsOpaque);
8970 switch (argmodes[j][0])
8975 case PROARGMODE_OUT:
8978 case PROARGMODE_INOUT:
8982 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8990 argname = argnames ? argnames[j] : (char *) NULL;
8991 if (argname && argname[0] == '\0')
8994 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8995 (j > 0) ? ", " : "",
8997 argname ? fmtId(argname) : "",
9002 appendPQExpBuffer(&fn, ")");
9007 * format_function_signature: generate function name and argument list
9009 * This is like format_function_arguments_old except that only a minimal
9010 * list of input argument types is generated; this is sufficient to
9011 * reference the function, but not to define it.
9013 * If honor_quotes is false then the function name is never quoted.
9014 * This is appropriate for use in TOC tags, but not in SQL commands.
9017 format_function_signature(Archive *fout, FuncInfo *finfo, bool honor_quotes)
9022 initPQExpBuffer(&fn);
9024 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
9026 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
9027 for (j = 0; j < finfo->nargs; j++)
9031 typname = getFormattedTypeName(fout, finfo->argtypes[j],
9034 appendPQExpBuffer(&fn, "%s%s",
9035 (j > 0) ? ", " : "",
9039 appendPQExpBuffer(&fn, ")");
9046 * dump out one function
9049 dumpFunc(Archive *fout, FuncInfo *finfo)
9057 char *funcsig; /* identity signature */
9058 char *funcfullsig; /* full signature */
9067 char *proallargtypes;
9081 char **allargtypes = NULL;
9082 char **argmodes = NULL;
9083 char **argnames = NULL;
9084 char **configitems = NULL;
9085 int nconfigitems = 0;
9088 /* Skip if not to be dumped */
9089 if (!finfo->dobj.dump || dataOnly)
9092 query = createPQExpBuffer();
9093 q = createPQExpBuffer();
9094 delqry = createPQExpBuffer();
9095 labelq = createPQExpBuffer();
9096 asPart = createPQExpBuffer();
9098 /* Set proper schema search path so type references list correctly */
9099 selectSourceSchema(fout, finfo->dobj.namespace->dobj.name);
9101 /* Fetch function-specific details */
9102 if (fout->remoteVersion >= 90200)
9105 * proleakproof was added at v9.2
9107 appendPQExpBuffer(query,
9108 "SELECT proretset, prosrc, probin, "
9109 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9110 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9111 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9112 "proiswindow, provolatile, proisstrict, prosecdef, "
9113 "proleakproof, proconfig, procost, prorows, "
9114 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9115 "FROM pg_catalog.pg_proc "
9116 "WHERE oid = '%u'::pg_catalog.oid",
9117 finfo->dobj.catId.oid);
9119 else if (fout->remoteVersion >= 80400)
9122 * In 8.4 and up we rely on pg_get_function_arguments and
9123 * pg_get_function_result instead of examining proallargtypes etc.
9125 appendPQExpBuffer(query,
9126 "SELECT proretset, prosrc, probin, "
9127 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
9128 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
9129 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
9130 "proiswindow, provolatile, proisstrict, prosecdef, "
9131 "false AS proleakproof, "
9132 " proconfig, procost, prorows, "
9133 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9134 "FROM pg_catalog.pg_proc "
9135 "WHERE oid = '%u'::pg_catalog.oid",
9136 finfo->dobj.catId.oid);
9138 else if (fout->remoteVersion >= 80300)
9140 appendPQExpBuffer(query,
9141 "SELECT proretset, prosrc, probin, "
9142 "proallargtypes, proargmodes, proargnames, "
9143 "false AS proiswindow, "
9144 "provolatile, proisstrict, prosecdef, "
9145 "false AS proleakproof, "
9146 "proconfig, procost, prorows, "
9147 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9148 "FROM pg_catalog.pg_proc "
9149 "WHERE oid = '%u'::pg_catalog.oid",
9150 finfo->dobj.catId.oid);
9152 else if (fout->remoteVersion >= 80100)
9154 appendPQExpBuffer(query,
9155 "SELECT proretset, prosrc, probin, "
9156 "proallargtypes, proargmodes, proargnames, "
9157 "false AS proiswindow, "
9158 "provolatile, proisstrict, prosecdef, "
9159 "false AS proleakproof, "
9160 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9161 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9162 "FROM pg_catalog.pg_proc "
9163 "WHERE oid = '%u'::pg_catalog.oid",
9164 finfo->dobj.catId.oid);
9166 else if (fout->remoteVersion >= 80000)
9168 appendPQExpBuffer(query,
9169 "SELECT proretset, prosrc, probin, "
9170 "null AS proallargtypes, "
9171 "null AS proargmodes, "
9173 "false AS proiswindow, "
9174 "provolatile, proisstrict, prosecdef, "
9175 "false AS proleakproof, "
9176 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9177 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9178 "FROM pg_catalog.pg_proc "
9179 "WHERE oid = '%u'::pg_catalog.oid",
9180 finfo->dobj.catId.oid);
9182 else if (fout->remoteVersion >= 70300)
9184 appendPQExpBuffer(query,
9185 "SELECT proretset, prosrc, probin, "
9186 "null AS proallargtypes, "
9187 "null AS proargmodes, "
9188 "null AS proargnames, "
9189 "false AS proiswindow, "
9190 "provolatile, proisstrict, prosecdef, "
9191 "false AS proleakproof, "
9192 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9193 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9194 "FROM pg_catalog.pg_proc "
9195 "WHERE oid = '%u'::pg_catalog.oid",
9196 finfo->dobj.catId.oid);
9198 else if (fout->remoteVersion >= 70100)
9200 appendPQExpBuffer(query,
9201 "SELECT proretset, prosrc, probin, "
9202 "null AS proallargtypes, "
9203 "null AS proargmodes, "
9204 "null AS proargnames, "
9205 "false AS proiswindow, "
9206 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9208 "false AS prosecdef, "
9209 "false AS proleakproof, "
9210 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9211 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9213 "WHERE oid = '%u'::oid",
9214 finfo->dobj.catId.oid);
9218 appendPQExpBuffer(query,
9219 "SELECT proretset, prosrc, probin, "
9220 "null AS proallargtypes, "
9221 "null AS proargmodes, "
9222 "null AS proargnames, "
9223 "false AS proiswindow, "
9224 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9225 "false AS proisstrict, "
9226 "false AS prosecdef, "
9227 "false AS proleakproof, "
9228 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9229 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9231 "WHERE oid = '%u'::oid",
9232 finfo->dobj.catId.oid);
9235 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9237 /* Expecting a single result only */
9238 ntups = PQntuples(res);
9241 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9242 "query returned %d rows instead of one: %s\n",
9244 ntups, query->data);
9248 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9249 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9250 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9251 if (fout->remoteVersion >= 80400)
9253 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9254 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9255 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9256 proallargtypes = proargmodes = proargnames = NULL;
9260 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9261 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9262 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9263 funcargs = funciargs = funcresult = NULL;
9265 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9266 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9267 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9268 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9269 proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
9270 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9271 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9272 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9273 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9276 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9277 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9278 * versions would set it to "-". There are no known cases in which prosrc
9279 * is unused, so the tests below for "-" are probably useless.
9281 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9283 appendPQExpBuffer(asPart, "AS ");
9284 appendStringLiteralAH(asPart, probin, fout);
9285 if (strcmp(prosrc, "-") != 0)
9287 appendPQExpBuffer(asPart, ", ");
9290 * where we have bin, use dollar quoting if allowed and src
9291 * contains quote or backslash; else use regular quoting.
9293 if (disable_dollar_quoting ||
9294 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9295 appendStringLiteralAH(asPart, prosrc, fout);
9297 appendStringLiteralDQ(asPart, prosrc, NULL);
9302 if (strcmp(prosrc, "-") != 0)
9304 appendPQExpBuffer(asPart, "AS ");
9305 /* with no bin, dollar quote src unconditionally if allowed */
9306 if (disable_dollar_quoting)
9307 appendStringLiteralAH(asPart, prosrc, fout);
9309 appendStringLiteralDQ(asPart, prosrc, NULL);
9313 nallargs = finfo->nargs; /* unless we learn different from allargs */
9315 if (proallargtypes && *proallargtypes)
9319 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9320 nitems < finfo->nargs)
9322 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9331 if (proargmodes && *proargmodes)
9335 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9338 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9345 if (proargnames && *proargnames)
9349 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9352 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9359 if (proconfig && *proconfig)
9361 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9363 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9373 /* 8.4 or later; we rely on server-side code for most of the work */
9374 funcfullsig = format_function_arguments(finfo, funcargs);
9375 funcsig = format_function_arguments(finfo, funciargs);
9379 /* pre-8.4, do it ourselves */
9380 funcsig = format_function_arguments_old(fout,
9381 finfo, nallargs, allargtypes,
9382 argmodes, argnames);
9383 funcfullsig = funcsig;
9386 funcsig_tag = format_function_signature(fout, finfo, false);
9389 * DROP must be fully qualified in case same name appears in pg_catalog
9391 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9392 fmtId(finfo->dobj.namespace->dobj.name),
9395 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9397 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9400 rettypename = getFormattedTypeName(fout, finfo->prorettype,
9402 appendPQExpBuffer(q, "RETURNS %s%s",
9403 (proretset[0] == 't') ? "SETOF " : "",
9408 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9410 if (proiswindow[0] == 't')
9411 appendPQExpBuffer(q, " WINDOW");
9413 if (provolatile[0] != PROVOLATILE_VOLATILE)
9415 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9416 appendPQExpBuffer(q, " IMMUTABLE");
9417 else if (provolatile[0] == PROVOLATILE_STABLE)
9418 appendPQExpBuffer(q, " STABLE");
9419 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9421 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
9427 if (proisstrict[0] == 't')
9428 appendPQExpBuffer(q, " STRICT");
9430 if (prosecdef[0] == 't')
9431 appendPQExpBuffer(q, " SECURITY DEFINER");
9433 if (proleakproof[0] == 't')
9434 appendPQExpBuffer(q, " LEAKPROOF");
9437 * COST and ROWS are emitted only if present and not default, so as not to
9438 * break backwards-compatibility of the dump without need. Keep this code
9439 * in sync with the defaults in functioncmds.c.
9441 if (strcmp(procost, "0") != 0)
9443 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9445 /* default cost is 1 */
9446 if (strcmp(procost, "1") != 0)
9447 appendPQExpBuffer(q, " COST %s", procost);
9451 /* default cost is 100 */
9452 if (strcmp(procost, "100") != 0)
9453 appendPQExpBuffer(q, " COST %s", procost);
9456 if (proretset[0] == 't' &&
9457 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9458 appendPQExpBuffer(q, " ROWS %s", prorows);
9460 for (i = 0; i < nconfigitems; i++)
9462 /* we feel free to scribble on configitems[] here */
9463 char *configitem = configitems[i];
9466 pos = strchr(configitem, '=');
9470 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9473 * Some GUC variable names are 'LIST' type and hence must not be
9476 if (pg_strcasecmp(configitem, "DateStyle") == 0
9477 || pg_strcasecmp(configitem, "search_path") == 0)
9478 appendPQExpBuffer(q, "%s", pos);
9480 appendStringLiteralAH(q, pos, fout);
9483 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9485 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9488 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9490 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9492 finfo->dobj.namespace->dobj.name,
9494 finfo->rolname, false,
9495 "FUNCTION", SECTION_PRE_DATA,
9496 q->data, delqry->data, NULL,
9497 finfo->dobj.dependencies, finfo->dobj.nDeps,
9500 /* Dump Function Comments and Security Labels */
9501 dumpComment(fout, labelq->data,
9502 finfo->dobj.namespace->dobj.name, finfo->rolname,
9503 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9504 dumpSecLabel(fout, labelq->data,
9505 finfo->dobj.namespace->dobj.name, finfo->rolname,
9506 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9508 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9509 funcsig, NULL, funcsig_tag,
9510 finfo->dobj.namespace->dobj.name,
9511 finfo->rolname, finfo->proacl);
9515 destroyPQExpBuffer(query);
9516 destroyPQExpBuffer(q);
9517 destroyPQExpBuffer(delqry);
9518 destroyPQExpBuffer(labelq);
9519 destroyPQExpBuffer(asPart);
9534 * Dump a user-defined cast
9537 dumpCast(Archive *fout, CastInfo *cast)
9542 FuncInfo *funcInfo = NULL;
9544 /* Skip if not to be dumped */
9545 if (!cast->dobj.dump || dataOnly)
9548 /* Cannot dump if we don't have the cast function's info */
9549 if (OidIsValid(cast->castfunc))
9551 funcInfo = findFuncByOid(cast->castfunc);
9552 if (funcInfo == NULL)
9557 * As per discussion we dump casts if one or more of the underlying
9558 * objects (the conversion function and the two data types) are not
9559 * builtin AND if all of the non-builtin objects are included in the dump.
9560 * Builtin meaning, the namespace name does not start with "pg_".
9562 * However, for a cast that belongs to an extension, we must not use this
9563 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9565 if (!cast->dobj.ext_member)
9567 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9568 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9570 if (sourceInfo == NULL || targetInfo == NULL)
9574 * Skip this cast if all objects are from pg_
9576 if ((funcInfo == NULL ||
9577 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9578 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9579 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9583 * Skip cast if function isn't from pg_ and is not to be dumped.
9586 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9587 !funcInfo->dobj.dump)
9591 * Same for the source type
9593 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9594 !sourceInfo->dobj.dump)
9598 * and the target type.
9600 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9601 !targetInfo->dobj.dump)
9605 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9606 selectSourceSchema(fout, "pg_catalog");
9608 defqry = createPQExpBuffer();
9609 delqry = createPQExpBuffer();
9610 labelq = createPQExpBuffer();
9612 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9613 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9614 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9616 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9617 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9618 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9620 switch (cast->castmethod)
9622 case COERCION_METHOD_BINARY:
9623 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9625 case COERCION_METHOD_INOUT:
9626 appendPQExpBuffer(defqry, "WITH INOUT");
9628 case COERCION_METHOD_FUNCTION:
9631 * Always qualify the function name, in case it is not in
9632 * pg_catalog schema (format_function_signature won't qualify it).
9634 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
9635 fmtId(funcInfo->dobj.namespace->dobj.name));
9636 appendPQExpBuffer(defqry, "%s",
9637 format_function_signature(fout, funcInfo, true));
9640 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9643 if (cast->castcontext == 'a')
9644 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9645 else if (cast->castcontext == 'i')
9646 appendPQExpBuffer(defqry, " AS IMPLICIT");
9647 appendPQExpBuffer(defqry, ";\n");
9649 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9650 getFormattedTypeName(fout, cast->castsource, zeroAsNone),
9651 getFormattedTypeName(fout, cast->casttarget, zeroAsNone));
9654 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9656 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9658 "pg_catalog", NULL, "",
9659 false, "CAST", SECTION_PRE_DATA,
9660 defqry->data, delqry->data, NULL,
9661 cast->dobj.dependencies, cast->dobj.nDeps,
9664 /* Dump Cast Comments */
9665 dumpComment(fout, labelq->data,
9667 cast->dobj.catId, 0, cast->dobj.dumpId);
9669 destroyPQExpBuffer(defqry);
9670 destroyPQExpBuffer(delqry);
9671 destroyPQExpBuffer(labelq);
9676 * write out a single operator definition
9679 dumpOpr(Archive *fout, OprInfo *oprinfo)
9686 PQExpBuffer details;
9711 /* Skip if not to be dumped */
9712 if (!oprinfo->dobj.dump || dataOnly)
9716 * some operators are invalid because they were the result of user
9717 * defining operators before commutators exist
9719 if (!OidIsValid(oprinfo->oprcode))
9722 query = createPQExpBuffer();
9723 q = createPQExpBuffer();
9724 delq = createPQExpBuffer();
9725 labelq = createPQExpBuffer();
9726 oprid = createPQExpBuffer();
9727 details = createPQExpBuffer();
9729 /* Make sure we are in proper schema so regoperator works correctly */
9730 selectSourceSchema(fout, oprinfo->dobj.namespace->dobj.name);
9732 if (fout->remoteVersion >= 80300)
9734 appendPQExpBuffer(query, "SELECT oprkind, "
9735 "oprcode::pg_catalog.regprocedure, "
9736 "oprleft::pg_catalog.regtype, "
9737 "oprright::pg_catalog.regtype, "
9738 "oprcom::pg_catalog.regoperator, "
9739 "oprnegate::pg_catalog.regoperator, "
9740 "oprrest::pg_catalog.regprocedure, "
9741 "oprjoin::pg_catalog.regprocedure, "
9742 "oprcanmerge, oprcanhash "
9743 "FROM pg_catalog.pg_operator "
9744 "WHERE oid = '%u'::pg_catalog.oid",
9745 oprinfo->dobj.catId.oid);
9747 else if (fout->remoteVersion >= 70300)
9749 appendPQExpBuffer(query, "SELECT oprkind, "
9750 "oprcode::pg_catalog.regprocedure, "
9751 "oprleft::pg_catalog.regtype, "
9752 "oprright::pg_catalog.regtype, "
9753 "oprcom::pg_catalog.regoperator, "
9754 "oprnegate::pg_catalog.regoperator, "
9755 "oprrest::pg_catalog.regprocedure, "
9756 "oprjoin::pg_catalog.regprocedure, "
9757 "(oprlsortop != 0) AS oprcanmerge, "
9759 "FROM pg_catalog.pg_operator "
9760 "WHERE oid = '%u'::pg_catalog.oid",
9761 oprinfo->dobj.catId.oid);
9763 else if (fout->remoteVersion >= 70100)
9765 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9766 "CASE WHEN oprleft = 0 THEN '-' "
9767 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9768 "CASE WHEN oprright = 0 THEN '-' "
9769 "ELSE format_type(oprright, NULL) END AS oprright, "
9770 "oprcom, oprnegate, oprrest, oprjoin, "
9771 "(oprlsortop != 0) AS oprcanmerge, "
9774 "WHERE oid = '%u'::oid",
9775 oprinfo->dobj.catId.oid);
9779 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9780 "CASE WHEN oprleft = 0 THEN '-'::name "
9781 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9782 "CASE WHEN oprright = 0 THEN '-'::name "
9783 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9784 "oprcom, oprnegate, oprrest, oprjoin, "
9785 "(oprlsortop != 0) AS oprcanmerge, "
9788 "WHERE oid = '%u'::oid",
9789 oprinfo->dobj.catId.oid);
9792 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9794 /* Expecting a single result only */
9795 ntups = PQntuples(res);
9798 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9799 "query returned %d rows instead of one: %s\n",
9801 ntups, query->data);
9805 i_oprkind = PQfnumber(res, "oprkind");
9806 i_oprcode = PQfnumber(res, "oprcode");
9807 i_oprleft = PQfnumber(res, "oprleft");
9808 i_oprright = PQfnumber(res, "oprright");
9809 i_oprcom = PQfnumber(res, "oprcom");
9810 i_oprnegate = PQfnumber(res, "oprnegate");
9811 i_oprrest = PQfnumber(res, "oprrest");
9812 i_oprjoin = PQfnumber(res, "oprjoin");
9813 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9814 i_oprcanhash = PQfnumber(res, "oprcanhash");
9816 oprkind = PQgetvalue(res, 0, i_oprkind);
9817 oprcode = PQgetvalue(res, 0, i_oprcode);
9818 oprleft = PQgetvalue(res, 0, i_oprleft);
9819 oprright = PQgetvalue(res, 0, i_oprright);
9820 oprcom = PQgetvalue(res, 0, i_oprcom);
9821 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9822 oprrest = PQgetvalue(res, 0, i_oprrest);
9823 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9824 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9825 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9827 appendPQExpBuffer(details, " PROCEDURE = %s",
9828 convertRegProcReference(fout, oprcode));
9830 appendPQExpBuffer(oprid, "%s (",
9831 oprinfo->dobj.name);
9834 * right unary means there's a left arg and left unary means there's a
9837 if (strcmp(oprkind, "r") == 0 ||
9838 strcmp(oprkind, "b") == 0)
9840 if (fout->remoteVersion >= 70100)
9843 name = fmtId(oprleft);
9844 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9845 appendPQExpBuffer(oprid, "%s", name);
9848 appendPQExpBuffer(oprid, "NONE");
9850 if (strcmp(oprkind, "l") == 0 ||
9851 strcmp(oprkind, "b") == 0)
9853 if (fout->remoteVersion >= 70100)
9856 name = fmtId(oprright);
9857 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9858 appendPQExpBuffer(oprid, ", %s)", name);
9861 appendPQExpBuffer(oprid, ", NONE)");
9863 name = convertOperatorReference(fout, oprcom);
9865 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9867 name = convertOperatorReference(fout, oprnegate);
9869 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9871 if (strcmp(oprcanmerge, "t") == 0)
9872 appendPQExpBuffer(details, ",\n MERGES");
9874 if (strcmp(oprcanhash, "t") == 0)
9875 appendPQExpBuffer(details, ",\n HASHES");
9877 name = convertRegProcReference(fout, oprrest);
9879 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9881 name = convertRegProcReference(fout, oprjoin);
9883 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9886 * DROP must be fully qualified in case same name appears in pg_catalog
9888 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9889 fmtId(oprinfo->dobj.namespace->dobj.name),
9892 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9893 oprinfo->dobj.name, details->data);
9895 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9898 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9900 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9902 oprinfo->dobj.namespace->dobj.name,
9905 false, "OPERATOR", SECTION_PRE_DATA,
9906 q->data, delq->data, NULL,
9907 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9910 /* Dump Operator Comments */
9911 dumpComment(fout, labelq->data,
9912 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9913 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9917 destroyPQExpBuffer(query);
9918 destroyPQExpBuffer(q);
9919 destroyPQExpBuffer(delq);
9920 destroyPQExpBuffer(labelq);
9921 destroyPQExpBuffer(oprid);
9922 destroyPQExpBuffer(details);
9926 * Convert a function reference obtained from pg_operator
9928 * Returns what to print, or NULL if function references is InvalidOid
9930 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9931 * argument-types part. In prior versions, the input is a REGPROC display.
9934 convertRegProcReference(Archive *fout, const char *proc)
9936 /* In all cases "-" means a null reference */
9937 if (strcmp(proc, "-") == 0)
9940 if (fout->remoteVersion >= 70300)
9946 name = pg_strdup(proc);
9947 /* find non-double-quoted left paren */
9949 for (paren = name; *paren; paren++)
9951 if (*paren == '(' && !inquote)
9962 /* REGPROC before 7.3 does not quote its result */
9967 * Convert an operator cross-reference obtained from pg_operator
9969 * Returns what to print, or NULL to print nothing
9971 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9972 * argument-types part, and add OPERATOR() decoration if the name is
9973 * schema-qualified. In older versions, the input is just a numeric OID,
9974 * which we search our operator list for.
9977 convertOperatorReference(Archive *fout, const char *opr)
9981 /* In all cases "0" means a null reference */
9982 if (strcmp(opr, "0") == 0)
9985 if (fout->remoteVersion >= 70300)
9993 name = pg_strdup(opr);
9994 /* find non-double-quoted left paren, and check for non-quoted dot */
9997 for (ptr = name; *ptr; ptr++)
10000 inquote = !inquote;
10001 else if (*ptr == '.' && !inquote)
10003 else if (*ptr == '(' && !inquote)
10009 /* If not schema-qualified, don't need to add OPERATOR() */
10012 oname = pg_malloc(strlen(name) + 11);
10013 sprintf(oname, "OPERATOR(%s)", name);
10018 oprInfo = findOprByOid(atooid(opr));
10019 if (oprInfo == NULL)
10021 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
10025 return oprInfo->dobj.name;
10029 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
10031 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
10032 * argument lists of these functions are predetermined. Note that the
10033 * caller should ensure we are in the proper schema, because the results
10034 * are search path dependent!
10036 static const char *
10037 convertTSFunction(Archive *fout, Oid funcOid)
10044 snprintf(query, sizeof(query),
10045 "SELECT '%u'::pg_catalog.regproc", funcOid);
10046 res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
10048 ntups = PQntuples(res);
10051 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10052 "query returned %d rows instead of one: %s\n",
10058 result = pg_strdup(PQgetvalue(res, 0, 0));
10068 * write out a single operator class definition
10071 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
10076 PQExpBuffer labelq;
10083 int i_opcfamilyname;
10084 int i_opcfamilynsp;
10086 int i_amopstrategy;
10087 int i_amopreqcheck;
10090 int i_sortfamilynsp;
10093 int i_amproclefttype;
10094 int i_amprocrighttype;
10099 char *opcfamilyname;
10100 char *opcfamilynsp;
10102 char *amopstrategy;
10103 char *amopreqcheck;
10106 char *sortfamilynsp;
10109 char *amproclefttype;
10110 char *amprocrighttype;
10114 /* Skip if not to be dumped */
10115 if (!opcinfo->dobj.dump || dataOnly)
10119 * XXX currently we do not implement dumping of operator classes from
10120 * pre-7.3 databases. This could be done but it seems not worth the
10123 if (fout->remoteVersion < 70300)
10126 query = createPQExpBuffer();
10127 q = createPQExpBuffer();
10128 delq = createPQExpBuffer();
10129 labelq = createPQExpBuffer();
10131 /* Make sure we are in proper schema so regoperator works correctly */
10132 selectSourceSchema(fout, opcinfo->dobj.namespace->dobj.name);
10134 /* Get additional fields from the pg_opclass row */
10135 if (fout->remoteVersion >= 80300)
10137 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10138 "opckeytype::pg_catalog.regtype, "
10139 "opcdefault, opcfamily, "
10140 "opfname AS opcfamilyname, "
10141 "nspname AS opcfamilynsp, "
10142 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
10143 "FROM pg_catalog.pg_opclass c "
10144 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
10145 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10146 "WHERE c.oid = '%u'::pg_catalog.oid",
10147 opcinfo->dobj.catId.oid);
10151 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
10152 "opckeytype::pg_catalog.regtype, "
10153 "opcdefault, NULL AS opcfamily, "
10154 "NULL AS opcfamilyname, "
10155 "NULL AS opcfamilynsp, "
10156 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
10157 "FROM pg_catalog.pg_opclass "
10158 "WHERE oid = '%u'::pg_catalog.oid",
10159 opcinfo->dobj.catId.oid);
10162 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10164 /* Expecting a single result only */
10165 ntups = PQntuples(res);
10168 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10169 "query returned %d rows instead of one: %s\n",
10171 ntups, query->data);
10175 i_opcintype = PQfnumber(res, "opcintype");
10176 i_opckeytype = PQfnumber(res, "opckeytype");
10177 i_opcdefault = PQfnumber(res, "opcdefault");
10178 i_opcfamily = PQfnumber(res, "opcfamily");
10179 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
10180 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
10181 i_amname = PQfnumber(res, "amname");
10183 opcintype = PQgetvalue(res, 0, i_opcintype);
10184 opckeytype = PQgetvalue(res, 0, i_opckeytype);
10185 opcdefault = PQgetvalue(res, 0, i_opcdefault);
10186 /* opcfamily will still be needed after we PQclear res */
10187 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
10188 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
10189 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
10190 /* amname will still be needed after we PQclear res */
10191 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10194 * DROP must be fully qualified in case same name appears in pg_catalog
10196 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10197 fmtId(opcinfo->dobj.namespace->dobj.name));
10198 appendPQExpBuffer(delq, ".%s",
10199 fmtId(opcinfo->dobj.name));
10200 appendPQExpBuffer(delq, " USING %s;\n",
10203 /* Build the fixed portion of the CREATE command */
10204 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10205 fmtId(opcinfo->dobj.name));
10206 if (strcmp(opcdefault, "t") == 0)
10207 appendPQExpBuffer(q, "DEFAULT ");
10208 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10211 if (strlen(opcfamilyname) > 0 &&
10212 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10213 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10215 appendPQExpBuffer(q, " FAMILY ");
10216 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10217 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10218 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10220 appendPQExpBuffer(q, " AS\n ");
10224 if (strcmp(opckeytype, "-") != 0)
10226 appendPQExpBuffer(q, "STORAGE %s",
10234 * Now fetch and print the OPERATOR entries (pg_amop rows).
10236 * Print only those opfamily members that are tied to the opclass by
10237 * pg_depend entries.
10239 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10240 * older server's opclass in which it is used. This is to avoid
10241 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10242 * older server and then reload into that old version. This can go away
10243 * once 8.3 is so old as to not be of interest to anyone.
10245 resetPQExpBuffer(query);
10247 if (fout->remoteVersion >= 90100)
10249 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10250 "amopopr::pg_catalog.regoperator, "
10251 "opfname AS sortfamily, "
10252 "nspname AS sortfamilynsp "
10253 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10254 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10255 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10256 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10257 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10258 "AND refobjid = '%u'::pg_catalog.oid "
10259 "AND amopfamily = '%s'::pg_catalog.oid "
10260 "ORDER BY amopstrategy",
10261 opcinfo->dobj.catId.oid,
10264 else if (fout->remoteVersion >= 80400)
10266 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10267 "amopopr::pg_catalog.regoperator, "
10268 "NULL AS sortfamily, "
10269 "NULL AS sortfamilynsp "
10270 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10271 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10272 "AND refobjid = '%u'::pg_catalog.oid "
10273 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10274 "AND objid = ao.oid "
10275 "ORDER BY amopstrategy",
10276 opcinfo->dobj.catId.oid);
10278 else if (fout->remoteVersion >= 80300)
10280 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10281 "amopopr::pg_catalog.regoperator, "
10282 "NULL AS sortfamily, "
10283 "NULL AS sortfamilynsp "
10284 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10285 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10286 "AND refobjid = '%u'::pg_catalog.oid "
10287 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10288 "AND objid = ao.oid "
10289 "ORDER BY amopstrategy",
10290 opcinfo->dobj.catId.oid);
10295 * Here, we print all entries since there are no opfamilies and hence
10296 * no loose operators to worry about.
10298 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10299 "amopopr::pg_catalog.regoperator, "
10300 "NULL AS sortfamily, "
10301 "NULL AS sortfamilynsp "
10302 "FROM pg_catalog.pg_amop "
10303 "WHERE amopclaid = '%u'::pg_catalog.oid "
10304 "ORDER BY amopstrategy",
10305 opcinfo->dobj.catId.oid);
10308 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10310 ntups = PQntuples(res);
10312 i_amopstrategy = PQfnumber(res, "amopstrategy");
10313 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10314 i_amopopr = PQfnumber(res, "amopopr");
10315 i_sortfamily = PQfnumber(res, "sortfamily");
10316 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10318 for (i = 0; i < ntups; i++)
10320 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10321 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10322 amopopr = PQgetvalue(res, i, i_amopopr);
10323 sortfamily = PQgetvalue(res, i, i_sortfamily);
10324 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10327 appendPQExpBuffer(q, " ,\n ");
10329 appendPQExpBuffer(q, "OPERATOR %s %s",
10330 amopstrategy, amopopr);
10332 if (strlen(sortfamily) > 0)
10334 appendPQExpBuffer(q, " FOR ORDER BY ");
10335 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10336 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10337 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10340 if (strcmp(amopreqcheck, "t") == 0)
10341 appendPQExpBuffer(q, " RECHECK");
10349 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10351 * Print only those opfamily members that are tied to the opclass by
10352 * pg_depend entries.
10354 * We print the amproclefttype/amprocrighttype even though in most cases
10355 * the backend could deduce the right values, because of the corner case
10356 * of a btree sort support function for a cross-type comparison. That's
10357 * only allowed in 9.2 and later, but for simplicity print them in all
10358 * versions that have the columns.
10360 resetPQExpBuffer(query);
10362 if (fout->remoteVersion >= 80300)
10364 appendPQExpBuffer(query, "SELECT amprocnum, "
10365 "amproc::pg_catalog.regprocedure, "
10366 "amproclefttype::pg_catalog.regtype, "
10367 "amprocrighttype::pg_catalog.regtype "
10368 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10369 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10370 "AND refobjid = '%u'::pg_catalog.oid "
10371 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10372 "AND objid = ap.oid "
10373 "ORDER BY amprocnum",
10374 opcinfo->dobj.catId.oid);
10378 appendPQExpBuffer(query, "SELECT amprocnum, "
10379 "amproc::pg_catalog.regprocedure, "
10380 "'' AS amproclefttype, "
10381 "'' AS amprocrighttype "
10382 "FROM pg_catalog.pg_amproc "
10383 "WHERE amopclaid = '%u'::pg_catalog.oid "
10384 "ORDER BY amprocnum",
10385 opcinfo->dobj.catId.oid);
10388 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10390 ntups = PQntuples(res);
10392 i_amprocnum = PQfnumber(res, "amprocnum");
10393 i_amproc = PQfnumber(res, "amproc");
10394 i_amproclefttype = PQfnumber(res, "amproclefttype");
10395 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10397 for (i = 0; i < ntups; i++)
10399 amprocnum = PQgetvalue(res, i, i_amprocnum);
10400 amproc = PQgetvalue(res, i, i_amproc);
10401 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10402 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10405 appendPQExpBuffer(q, " ,\n ");
10407 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10409 if (*amproclefttype && *amprocrighttype)
10410 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10412 appendPQExpBuffer(q, " %s", amproc);
10419 appendPQExpBuffer(q, ";\n");
10421 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10422 fmtId(opcinfo->dobj.name));
10423 appendPQExpBuffer(labelq, " USING %s",
10426 if (binary_upgrade)
10427 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10429 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10430 opcinfo->dobj.name,
10431 opcinfo->dobj.namespace->dobj.name,
10434 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10435 q->data, delq->data, NULL,
10436 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10439 /* Dump Operator Class Comments */
10440 dumpComment(fout, labelq->data,
10441 NULL, opcinfo->rolname,
10442 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10445 destroyPQExpBuffer(query);
10446 destroyPQExpBuffer(q);
10447 destroyPQExpBuffer(delq);
10448 destroyPQExpBuffer(labelq);
10453 * write out a single operator family definition
10455 * Note: this also dumps any "loose" operator members that aren't bound to a
10456 * specific opclass within the opfamily.
10459 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10464 PQExpBuffer labelq;
10467 PGresult *res_procs;
10470 int i_amopstrategy;
10471 int i_amopreqcheck;
10474 int i_sortfamilynsp;
10477 int i_amproclefttype;
10478 int i_amprocrighttype;
10480 char *amopstrategy;
10481 char *amopreqcheck;
10484 char *sortfamilynsp;
10487 char *amproclefttype;
10488 char *amprocrighttype;
10492 /* Skip if not to be dumped */
10493 if (!opfinfo->dobj.dump || dataOnly)
10497 * We want to dump the opfamily only if (1) it contains "loose" operators
10498 * or functions, or (2) it contains an opclass with a different name or
10499 * owner. Otherwise it's sufficient to let it be created during creation
10500 * of the contained opclass, and not dumping it improves portability of
10501 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10505 query = createPQExpBuffer();
10506 q = createPQExpBuffer();
10507 delq = createPQExpBuffer();
10508 labelq = createPQExpBuffer();
10510 /* Make sure we are in proper schema so regoperator works correctly */
10511 selectSourceSchema(fout, opfinfo->dobj.namespace->dobj.name);
10514 * Fetch only those opfamily members that are tied directly to the
10515 * opfamily by pg_depend entries.
10517 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10518 * older server's opclass in which it is used. This is to avoid
10519 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10520 * older server and then reload into that old version. This can go away
10521 * once 8.3 is so old as to not be of interest to anyone.
10523 if (fout->remoteVersion >= 90100)
10525 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10526 "amopopr::pg_catalog.regoperator, "
10527 "opfname AS sortfamily, "
10528 "nspname AS sortfamilynsp "
10529 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10530 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10531 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10532 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10533 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10534 "AND refobjid = '%u'::pg_catalog.oid "
10535 "AND amopfamily = '%u'::pg_catalog.oid "
10536 "ORDER BY amopstrategy",
10537 opfinfo->dobj.catId.oid,
10538 opfinfo->dobj.catId.oid);
10540 else if (fout->remoteVersion >= 80400)
10542 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10543 "amopopr::pg_catalog.regoperator, "
10544 "NULL AS sortfamily, "
10545 "NULL AS sortfamilynsp "
10546 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10547 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10548 "AND refobjid = '%u'::pg_catalog.oid "
10549 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10550 "AND objid = ao.oid "
10551 "ORDER BY amopstrategy",
10552 opfinfo->dobj.catId.oid);
10556 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10557 "amopopr::pg_catalog.regoperator, "
10558 "NULL AS sortfamily, "
10559 "NULL AS sortfamilynsp "
10560 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10561 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10562 "AND refobjid = '%u'::pg_catalog.oid "
10563 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10564 "AND objid = ao.oid "
10565 "ORDER BY amopstrategy",
10566 opfinfo->dobj.catId.oid);
10569 res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10571 resetPQExpBuffer(query);
10573 appendPQExpBuffer(query, "SELECT amprocnum, "
10574 "amproc::pg_catalog.regprocedure, "
10575 "amproclefttype::pg_catalog.regtype, "
10576 "amprocrighttype::pg_catalog.regtype "
10577 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10578 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10579 "AND refobjid = '%u'::pg_catalog.oid "
10580 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10581 "AND objid = ap.oid "
10582 "ORDER BY amprocnum",
10583 opfinfo->dobj.catId.oid);
10585 res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10587 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10589 /* No loose members, so check contained opclasses */
10590 resetPQExpBuffer(query);
10592 appendPQExpBuffer(query, "SELECT 1 "
10593 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10594 "WHERE f.oid = '%u'::pg_catalog.oid "
10595 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10596 "AND refobjid = f.oid "
10597 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10598 "AND objid = c.oid "
10599 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10601 opfinfo->dobj.catId.oid);
10603 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10605 if (PQntuples(res) == 0)
10607 /* no need to dump it, so bail out */
10610 PQclear(res_procs);
10611 destroyPQExpBuffer(query);
10612 destroyPQExpBuffer(q);
10613 destroyPQExpBuffer(delq);
10614 destroyPQExpBuffer(labelq);
10621 /* Get additional fields from the pg_opfamily row */
10622 resetPQExpBuffer(query);
10624 appendPQExpBuffer(query, "SELECT "
10625 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10626 "FROM pg_catalog.pg_opfamily "
10627 "WHERE oid = '%u'::pg_catalog.oid",
10628 opfinfo->dobj.catId.oid);
10630 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10632 /* Expecting a single result only */
10633 ntups = PQntuples(res);
10636 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10637 "query returned %d rows instead of one: %s\n",
10639 ntups, query->data);
10643 i_amname = PQfnumber(res, "amname");
10645 /* amname will still be needed after we PQclear res */
10646 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10649 * DROP must be fully qualified in case same name appears in pg_catalog
10651 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10652 fmtId(opfinfo->dobj.namespace->dobj.name));
10653 appendPQExpBuffer(delq, ".%s",
10654 fmtId(opfinfo->dobj.name));
10655 appendPQExpBuffer(delq, " USING %s;\n",
10658 /* Build the fixed portion of the CREATE command */
10659 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10660 fmtId(opfinfo->dobj.name));
10661 appendPQExpBuffer(q, " USING %s;\n",
10666 /* Do we need an ALTER to add loose members? */
10667 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10669 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10670 fmtId(opfinfo->dobj.name));
10671 appendPQExpBuffer(q, " USING %s ADD\n ",
10677 * Now fetch and print the OPERATOR entries (pg_amop rows).
10679 ntups = PQntuples(res_ops);
10681 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10682 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10683 i_amopopr = PQfnumber(res_ops, "amopopr");
10684 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10685 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10687 for (i = 0; i < ntups; i++)
10689 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10690 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10691 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10692 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10693 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10696 appendPQExpBuffer(q, " ,\n ");
10698 appendPQExpBuffer(q, "OPERATOR %s %s",
10699 amopstrategy, amopopr);
10701 if (strlen(sortfamily) > 0)
10703 appendPQExpBuffer(q, " FOR ORDER BY ");
10704 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10705 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10706 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10709 if (strcmp(amopreqcheck, "t") == 0)
10710 appendPQExpBuffer(q, " RECHECK");
10716 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10718 ntups = PQntuples(res_procs);
10720 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10721 i_amproc = PQfnumber(res_procs, "amproc");
10722 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10723 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10725 for (i = 0; i < ntups; i++)
10727 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10728 amproc = PQgetvalue(res_procs, i, i_amproc);
10729 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10730 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10733 appendPQExpBuffer(q, " ,\n ");
10735 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10736 amprocnum, amproclefttype, amprocrighttype,
10742 appendPQExpBuffer(q, ";\n");
10745 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10746 fmtId(opfinfo->dobj.name));
10747 appendPQExpBuffer(labelq, " USING %s",
10750 if (binary_upgrade)
10751 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10753 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10754 opfinfo->dobj.name,
10755 opfinfo->dobj.namespace->dobj.name,
10758 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10759 q->data, delq->data, NULL,
10760 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10763 /* Dump Operator Family Comments */
10764 dumpComment(fout, labelq->data,
10765 NULL, opfinfo->rolname,
10766 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10770 PQclear(res_procs);
10771 destroyPQExpBuffer(query);
10772 destroyPQExpBuffer(q);
10773 destroyPQExpBuffer(delq);
10774 destroyPQExpBuffer(labelq);
10779 * write out a single collation definition
10782 dumpCollation(Archive *fout, CollInfo *collinfo)
10787 PQExpBuffer labelq;
10792 const char *collcollate;
10793 const char *collctype;
10795 /* Skip if not to be dumped */
10796 if (!collinfo->dobj.dump || dataOnly)
10799 query = createPQExpBuffer();
10800 q = createPQExpBuffer();
10801 delq = createPQExpBuffer();
10802 labelq = createPQExpBuffer();
10804 /* Make sure we are in proper schema */
10805 selectSourceSchema(fout, collinfo->dobj.namespace->dobj.name);
10807 /* Get conversion-specific details */
10808 appendPQExpBuffer(query, "SELECT "
10811 "FROM pg_catalog.pg_collation c "
10812 "WHERE c.oid = '%u'::pg_catalog.oid",
10813 collinfo->dobj.catId.oid);
10815 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10817 /* Expecting a single result only */
10818 ntups = PQntuples(res);
10821 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10822 "query returned %d rows instead of one: %s\n",
10824 ntups, query->data);
10828 i_collcollate = PQfnumber(res, "collcollate");
10829 i_collctype = PQfnumber(res, "collctype");
10831 collcollate = PQgetvalue(res, 0, i_collcollate);
10832 collctype = PQgetvalue(res, 0, i_collctype);
10835 * DROP must be fully qualified in case same name appears in pg_catalog
10837 appendPQExpBuffer(delq, "DROP COLLATION %s",
10838 fmtId(collinfo->dobj.namespace->dobj.name));
10839 appendPQExpBuffer(delq, ".%s;\n",
10840 fmtId(collinfo->dobj.name));
10842 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10843 fmtId(collinfo->dobj.name));
10844 appendStringLiteralAH(q, collcollate, fout);
10845 appendPQExpBuffer(q, ", lc_ctype = ");
10846 appendStringLiteralAH(q, collctype, fout);
10847 appendPQExpBuffer(q, ");\n");
10849 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10851 if (binary_upgrade)
10852 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10854 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10855 collinfo->dobj.name,
10856 collinfo->dobj.namespace->dobj.name,
10859 false, "COLLATION", SECTION_PRE_DATA,
10860 q->data, delq->data, NULL,
10861 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10864 /* Dump Collation Comments */
10865 dumpComment(fout, labelq->data,
10866 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10867 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10871 destroyPQExpBuffer(query);
10872 destroyPQExpBuffer(q);
10873 destroyPQExpBuffer(delq);
10874 destroyPQExpBuffer(labelq);
10879 * write out a single conversion definition
10882 dumpConversion(Archive *fout, ConvInfo *convinfo)
10887 PQExpBuffer labelq;
10890 int i_conforencoding;
10891 int i_contoencoding;
10894 const char *conforencoding;
10895 const char *contoencoding;
10896 const char *conproc;
10899 /* Skip if not to be dumped */
10900 if (!convinfo->dobj.dump || dataOnly)
10903 query = createPQExpBuffer();
10904 q = createPQExpBuffer();
10905 delq = createPQExpBuffer();
10906 labelq = createPQExpBuffer();
10908 /* Make sure we are in proper schema */
10909 selectSourceSchema(fout, convinfo->dobj.namespace->dobj.name);
10911 /* Get conversion-specific details */
10912 appendPQExpBuffer(query, "SELECT "
10913 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10914 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10915 "conproc, condefault "
10916 "FROM pg_catalog.pg_conversion c "
10917 "WHERE c.oid = '%u'::pg_catalog.oid",
10918 convinfo->dobj.catId.oid);
10920 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10922 /* Expecting a single result only */
10923 ntups = PQntuples(res);
10926 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10927 "query returned %d rows instead of one: %s\n",
10929 ntups, query->data);
10933 i_conforencoding = PQfnumber(res, "conforencoding");
10934 i_contoencoding = PQfnumber(res, "contoencoding");
10935 i_conproc = PQfnumber(res, "conproc");
10936 i_condefault = PQfnumber(res, "condefault");
10938 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10939 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10940 conproc = PQgetvalue(res, 0, i_conproc);
10941 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10944 * DROP must be fully qualified in case same name appears in pg_catalog
10946 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10947 fmtId(convinfo->dobj.namespace->dobj.name));
10948 appendPQExpBuffer(delq, ".%s;\n",
10949 fmtId(convinfo->dobj.name));
10951 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10952 (condefault) ? "DEFAULT " : "",
10953 fmtId(convinfo->dobj.name));
10954 appendStringLiteralAH(q, conforencoding, fout);
10955 appendPQExpBuffer(q, " TO ");
10956 appendStringLiteralAH(q, contoencoding, fout);
10957 /* regproc is automatically quoted in 7.3 and above */
10958 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10960 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10962 if (binary_upgrade)
10963 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10965 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10966 convinfo->dobj.name,
10967 convinfo->dobj.namespace->dobj.name,
10970 false, "CONVERSION", SECTION_PRE_DATA,
10971 q->data, delq->data, NULL,
10972 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10975 /* Dump Conversion Comments */
10976 dumpComment(fout, labelq->data,
10977 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10978 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10982 destroyPQExpBuffer(query);
10983 destroyPQExpBuffer(q);
10984 destroyPQExpBuffer(delq);
10985 destroyPQExpBuffer(labelq);
10989 * format_aggregate_signature: generate aggregate name and argument list
10991 * The argument type names are qualified if needed. The aggregate name
10992 * is never qualified.
10995 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10997 PQExpBufferData buf;
11000 initPQExpBuffer(&buf);
11002 appendPQExpBuffer(&buf, "%s",
11003 fmtId(agginfo->aggfn.dobj.name));
11005 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
11007 if (agginfo->aggfn.nargs == 0)
11008 appendPQExpBuffer(&buf, "(*)");
11011 appendPQExpBuffer(&buf, "(");
11012 for (j = 0; j < agginfo->aggfn.nargs; j++)
11016 typname = getFormattedTypeName(fout, agginfo->aggfn.argtypes[j],
11019 appendPQExpBuffer(&buf, "%s%s",
11020 (j > 0) ? ", " : "",
11024 appendPQExpBuffer(&buf, ")");
11031 * write out a single aggregate definition
11034 dumpAgg(Archive *fout, AggInfo *agginfo)
11039 PQExpBuffer labelq;
11040 PQExpBuffer details;
11048 int i_aggtranstype;
11051 const char *aggtransfn;
11052 const char *aggfinalfn;
11053 const char *aggsortop;
11054 const char *aggtranstype;
11055 const char *agginitval;
11058 /* Skip if not to be dumped */
11059 if (!agginfo->aggfn.dobj.dump || dataOnly)
11062 query = createPQExpBuffer();
11063 q = createPQExpBuffer();
11064 delq = createPQExpBuffer();
11065 labelq = createPQExpBuffer();
11066 details = createPQExpBuffer();
11068 /* Make sure we are in proper schema */
11069 selectSourceSchema(fout, agginfo->aggfn.dobj.namespace->dobj.name);
11071 /* Get aggregate-specific details */
11072 if (fout->remoteVersion >= 80100)
11074 appendPQExpBuffer(query, "SELECT aggtransfn, "
11075 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11076 "aggsortop::pg_catalog.regoperator, "
11078 "'t'::boolean AS convertok "
11079 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11080 "WHERE a.aggfnoid = p.oid "
11081 "AND p.oid = '%u'::pg_catalog.oid",
11082 agginfo->aggfn.dobj.catId.oid);
11084 else if (fout->remoteVersion >= 70300)
11086 appendPQExpBuffer(query, "SELECT aggtransfn, "
11087 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
11090 "'t'::boolean AS convertok "
11091 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
11092 "WHERE a.aggfnoid = p.oid "
11093 "AND p.oid = '%u'::pg_catalog.oid",
11094 agginfo->aggfn.dobj.catId.oid);
11096 else if (fout->remoteVersion >= 70100)
11098 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
11099 "format_type(aggtranstype, NULL) AS aggtranstype, "
11102 "'t'::boolean AS convertok "
11103 "FROM pg_aggregate "
11104 "WHERE oid = '%u'::oid",
11105 agginfo->aggfn.dobj.catId.oid);
11109 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
11111 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
11113 "agginitval1 AS agginitval, "
11114 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
11115 "FROM pg_aggregate "
11116 "WHERE oid = '%u'::oid",
11117 agginfo->aggfn.dobj.catId.oid);
11120 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11122 /* Expecting a single result only */
11123 ntups = PQntuples(res);
11126 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11127 "query returned %d rows instead of one: %s\n",
11129 ntups, query->data);
11133 i_aggtransfn = PQfnumber(res, "aggtransfn");
11134 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
11135 i_aggsortop = PQfnumber(res, "aggsortop");
11136 i_aggtranstype = PQfnumber(res, "aggtranstype");
11137 i_agginitval = PQfnumber(res, "agginitval");
11138 i_convertok = PQfnumber(res, "convertok");
11140 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
11141 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
11142 aggsortop = PQgetvalue(res, 0, i_aggsortop);
11143 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
11144 agginitval = PQgetvalue(res, 0, i_agginitval);
11145 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
11147 aggsig = format_aggregate_signature(agginfo, fout, true);
11148 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
11152 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
11157 if (fout->remoteVersion >= 70300)
11159 /* If using 7.3's regproc or regtype, data is already quoted */
11160 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11164 else if (fout->remoteVersion >= 70100)
11166 /* format_type quotes, regproc does not */
11167 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
11173 /* need quotes all around */
11174 appendPQExpBuffer(details, " SFUNC = %s,\n",
11175 fmtId(aggtransfn));
11176 appendPQExpBuffer(details, " STYPE = %s",
11177 fmtId(aggtranstype));
11180 if (!PQgetisnull(res, 0, i_agginitval))
11182 appendPQExpBuffer(details, ",\n INITCOND = ");
11183 appendStringLiteralAH(details, agginitval, fout);
11186 if (strcmp(aggfinalfn, "-") != 0)
11188 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11192 aggsortop = convertOperatorReference(fout, aggsortop);
11195 appendPQExpBuffer(details, ",\n SORTOP = %s",
11200 * DROP must be fully qualified in case same name appears in pg_catalog
11202 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11203 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11206 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11207 aggsig, details->data);
11209 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11211 if (binary_upgrade)
11212 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11214 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11216 agginfo->aggfn.dobj.namespace->dobj.name,
11218 agginfo->aggfn.rolname,
11219 false, "AGGREGATE", SECTION_PRE_DATA,
11220 q->data, delq->data, NULL,
11221 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
11224 /* Dump Aggregate Comments */
11225 dumpComment(fout, labelq->data,
11226 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11227 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11228 dumpSecLabel(fout, labelq->data,
11229 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11230 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11233 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11234 * command look like a function's GRANT; in particular this affects the
11235 * syntax for zero-argument aggregates.
11240 aggsig = format_function_signature(fout, &agginfo->aggfn, true);
11241 aggsig_tag = format_function_signature(fout, &agginfo->aggfn, false);
11243 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11245 aggsig, NULL, aggsig_tag,
11246 agginfo->aggfn.dobj.namespace->dobj.name,
11247 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11254 destroyPQExpBuffer(query);
11255 destroyPQExpBuffer(q);
11256 destroyPQExpBuffer(delq);
11257 destroyPQExpBuffer(labelq);
11258 destroyPQExpBuffer(details);
11263 * write out a single text search parser
11266 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11270 PQExpBuffer labelq;
11272 /* Skip if not to be dumped */
11273 if (!prsinfo->dobj.dump || dataOnly)
11276 q = createPQExpBuffer();
11277 delq = createPQExpBuffer();
11278 labelq = createPQExpBuffer();
11280 /* Make sure we are in proper schema */
11281 selectSourceSchema(fout, prsinfo->dobj.namespace->dobj.name);
11283 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11284 fmtId(prsinfo->dobj.name));
11286 appendPQExpBuffer(q, " START = %s,\n",
11287 convertTSFunction(fout, prsinfo->prsstart));
11288 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11289 convertTSFunction(fout, prsinfo->prstoken));
11290 appendPQExpBuffer(q, " END = %s,\n",
11291 convertTSFunction(fout, prsinfo->prsend));
11292 if (prsinfo->prsheadline != InvalidOid)
11293 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11294 convertTSFunction(fout, prsinfo->prsheadline));
11295 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11296 convertTSFunction(fout, prsinfo->prslextype));
11299 * DROP must be fully qualified in case same name appears in pg_catalog
11301 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11302 fmtId(prsinfo->dobj.namespace->dobj.name));
11303 appendPQExpBuffer(delq, ".%s;\n",
11304 fmtId(prsinfo->dobj.name));
11306 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11307 fmtId(prsinfo->dobj.name));
11309 if (binary_upgrade)
11310 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11312 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11313 prsinfo->dobj.name,
11314 prsinfo->dobj.namespace->dobj.name,
11317 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11318 q->data, delq->data, NULL,
11319 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11322 /* Dump Parser Comments */
11323 dumpComment(fout, labelq->data,
11325 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11327 destroyPQExpBuffer(q);
11328 destroyPQExpBuffer(delq);
11329 destroyPQExpBuffer(labelq);
11334 * write out a single text search dictionary
11337 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11341 PQExpBuffer labelq;
11348 /* Skip if not to be dumped */
11349 if (!dictinfo->dobj.dump || dataOnly)
11352 q = createPQExpBuffer();
11353 delq = createPQExpBuffer();
11354 labelq = createPQExpBuffer();
11355 query = createPQExpBuffer();
11357 /* Fetch name and namespace of the dictionary's template */
11358 selectSourceSchema(fout, "pg_catalog");
11359 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11360 "FROM pg_ts_template p, pg_namespace n "
11361 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11362 dictinfo->dicttemplate);
11363 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11364 ntups = PQntuples(res);
11367 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11368 "query returned %d rows instead of one: %s\n",
11370 ntups, query->data);
11373 nspname = PQgetvalue(res, 0, 0);
11374 tmplname = PQgetvalue(res, 0, 1);
11376 /* Make sure we are in proper schema */
11377 selectSourceSchema(fout, dictinfo->dobj.namespace->dobj.name);
11379 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11380 fmtId(dictinfo->dobj.name));
11382 appendPQExpBuffer(q, " TEMPLATE = ");
11383 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11384 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11385 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11389 /* the dictinitoption can be dumped straight into the command */
11390 if (dictinfo->dictinitoption)
11391 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11393 appendPQExpBuffer(q, " );\n");
11396 * DROP must be fully qualified in case same name appears in pg_catalog
11398 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11399 fmtId(dictinfo->dobj.namespace->dobj.name));
11400 appendPQExpBuffer(delq, ".%s;\n",
11401 fmtId(dictinfo->dobj.name));
11403 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11404 fmtId(dictinfo->dobj.name));
11406 if (binary_upgrade)
11407 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11409 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11410 dictinfo->dobj.name,
11411 dictinfo->dobj.namespace->dobj.name,
11414 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11415 q->data, delq->data, NULL,
11416 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11419 /* Dump Dictionary Comments */
11420 dumpComment(fout, labelq->data,
11421 NULL, dictinfo->rolname,
11422 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11424 destroyPQExpBuffer(q);
11425 destroyPQExpBuffer(delq);
11426 destroyPQExpBuffer(labelq);
11427 destroyPQExpBuffer(query);
11432 * write out a single text search template
11435 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11439 PQExpBuffer labelq;
11441 /* Skip if not to be dumped */
11442 if (!tmplinfo->dobj.dump || dataOnly)
11445 q = createPQExpBuffer();
11446 delq = createPQExpBuffer();
11447 labelq = createPQExpBuffer();
11449 /* Make sure we are in proper schema */
11450 selectSourceSchema(fout, tmplinfo->dobj.namespace->dobj.name);
11452 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11453 fmtId(tmplinfo->dobj.name));
11455 if (tmplinfo->tmplinit != InvalidOid)
11456 appendPQExpBuffer(q, " INIT = %s,\n",
11457 convertTSFunction(fout, tmplinfo->tmplinit));
11458 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11459 convertTSFunction(fout, tmplinfo->tmpllexize));
11462 * DROP must be fully qualified in case same name appears in pg_catalog
11464 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11465 fmtId(tmplinfo->dobj.namespace->dobj.name));
11466 appendPQExpBuffer(delq, ".%s;\n",
11467 fmtId(tmplinfo->dobj.name));
11469 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11470 fmtId(tmplinfo->dobj.name));
11472 if (binary_upgrade)
11473 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11475 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11476 tmplinfo->dobj.name,
11477 tmplinfo->dobj.namespace->dobj.name,
11480 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11481 q->data, delq->data, NULL,
11482 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11485 /* Dump Template Comments */
11486 dumpComment(fout, labelq->data,
11488 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11490 destroyPQExpBuffer(q);
11491 destroyPQExpBuffer(delq);
11492 destroyPQExpBuffer(labelq);
11497 * write out a single text search configuration
11500 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11504 PQExpBuffer labelq;
11514 /* Skip if not to be dumped */
11515 if (!cfginfo->dobj.dump || dataOnly)
11518 q = createPQExpBuffer();
11519 delq = createPQExpBuffer();
11520 labelq = createPQExpBuffer();
11521 query = createPQExpBuffer();
11523 /* Fetch name and namespace of the config's parser */
11524 selectSourceSchema(fout, "pg_catalog");
11525 appendPQExpBuffer(query, "SELECT nspname, prsname "
11526 "FROM pg_ts_parser p, pg_namespace n "
11527 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11528 cfginfo->cfgparser);
11529 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11530 ntups = PQntuples(res);
11533 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11534 "query returned %d rows instead of one: %s\n",
11536 ntups, query->data);
11539 nspname = PQgetvalue(res, 0, 0);
11540 prsname = PQgetvalue(res, 0, 1);
11542 /* Make sure we are in proper schema */
11543 selectSourceSchema(fout, cfginfo->dobj.namespace->dobj.name);
11545 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11546 fmtId(cfginfo->dobj.name));
11548 appendPQExpBuffer(q, " PARSER = ");
11549 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11550 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11551 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11555 resetPQExpBuffer(query);
11556 appendPQExpBuffer(query,
11558 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11559 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11560 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11561 "FROM pg_catalog.pg_ts_config_map AS m \n"
11562 "WHERE m.mapcfg = '%u' \n"
11563 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11564 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11566 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11567 ntups = PQntuples(res);
11569 i_tokenname = PQfnumber(res, "tokenname");
11570 i_dictname = PQfnumber(res, "dictname");
11572 for (i = 0; i < ntups; i++)
11574 char *tokenname = PQgetvalue(res, i, i_tokenname);
11575 char *dictname = PQgetvalue(res, i, i_dictname);
11578 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11580 /* starting a new token type, so start a new command */
11582 appendPQExpBuffer(q, ";\n");
11583 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11584 fmtId(cfginfo->dobj.name));
11585 /* tokenname needs quoting, dictname does NOT */
11586 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11587 fmtId(tokenname), dictname);
11590 appendPQExpBuffer(q, ", %s", dictname);
11594 appendPQExpBuffer(q, ";\n");
11599 * DROP must be fully qualified in case same name appears in pg_catalog
11601 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11602 fmtId(cfginfo->dobj.namespace->dobj.name));
11603 appendPQExpBuffer(delq, ".%s;\n",
11604 fmtId(cfginfo->dobj.name));
11606 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11607 fmtId(cfginfo->dobj.name));
11609 if (binary_upgrade)
11610 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11612 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11613 cfginfo->dobj.name,
11614 cfginfo->dobj.namespace->dobj.name,
11617 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11618 q->data, delq->data, NULL,
11619 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11622 /* Dump Configuration Comments */
11623 dumpComment(fout, labelq->data,
11624 NULL, cfginfo->rolname,
11625 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11627 destroyPQExpBuffer(q);
11628 destroyPQExpBuffer(delq);
11629 destroyPQExpBuffer(labelq);
11630 destroyPQExpBuffer(query);
11634 * dumpForeignDataWrapper
11635 * write out a single foreign-data wrapper definition
11638 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11642 PQExpBuffer labelq;
11645 /* Skip if not to be dumped */
11646 if (!fdwinfo->dobj.dump || dataOnly)
11650 * FDWs that belong to an extension are dumped based on their "dump"
11651 * field. Otherwise omit them if we are only dumping some specific object.
11653 if (!fdwinfo->dobj.ext_member)
11654 if (!include_everything)
11657 q = createPQExpBuffer();
11658 delq = createPQExpBuffer();
11659 labelq = createPQExpBuffer();
11661 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11663 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11666 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11667 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11669 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11670 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11672 if (strlen(fdwinfo->fdwoptions) > 0)
11673 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
11675 appendPQExpBuffer(q, ";\n");
11677 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11680 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11683 if (binary_upgrade)
11684 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11686 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11687 fdwinfo->dobj.name,
11691 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11692 q->data, delq->data, NULL,
11693 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11696 /* Handle the ACL */
11697 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11698 "FOREIGN DATA WRAPPER",
11699 qfdwname, NULL, fdwinfo->dobj.name,
11700 NULL, fdwinfo->rolname,
11703 /* Dump Foreign Data Wrapper Comments */
11704 dumpComment(fout, labelq->data,
11705 NULL, fdwinfo->rolname,
11706 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11710 destroyPQExpBuffer(q);
11711 destroyPQExpBuffer(delq);
11712 destroyPQExpBuffer(labelq);
11716 * dumpForeignServer
11717 * write out a foreign server definition
11720 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11724 PQExpBuffer labelq;
11731 /* Skip if not to be dumped */
11732 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11735 q = createPQExpBuffer();
11736 delq = createPQExpBuffer();
11737 labelq = createPQExpBuffer();
11738 query = createPQExpBuffer();
11740 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11742 /* look up the foreign-data wrapper */
11743 selectSourceSchema(fout, "pg_catalog");
11744 appendPQExpBuffer(query, "SELECT fdwname "
11745 "FROM pg_foreign_data_wrapper w "
11746 "WHERE w.oid = '%u'",
11748 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11749 ntups = PQntuples(res);
11752 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11753 "query returned %d rows instead of one: %s\n",
11755 ntups, query->data);
11758 fdwname = PQgetvalue(res, 0, 0);
11760 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11761 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11763 appendPQExpBuffer(q, " TYPE ");
11764 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11766 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11768 appendPQExpBuffer(q, " VERSION ");
11769 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11772 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11773 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11775 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11776 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
11778 appendPQExpBuffer(q, ";\n");
11780 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11783 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11785 if (binary_upgrade)
11786 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11788 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11789 srvinfo->dobj.name,
11793 false, "SERVER", SECTION_PRE_DATA,
11794 q->data, delq->data, NULL,
11795 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11798 /* Handle the ACL */
11799 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11801 qsrvname, NULL, srvinfo->dobj.name,
11802 NULL, srvinfo->rolname,
11805 /* Dump user mappings */
11806 dumpUserMappings(fout,
11807 srvinfo->dobj.name, NULL,
11809 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11811 /* Dump Foreign Server Comments */
11812 dumpComment(fout, labelq->data,
11813 NULL, srvinfo->rolname,
11814 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11818 destroyPQExpBuffer(q);
11819 destroyPQExpBuffer(delq);
11820 destroyPQExpBuffer(labelq);
11826 * This routine is used to dump any user mappings associated with the
11827 * server handed to this routine. Should be called after ArchiveEntry()
11831 dumpUserMappings(Archive *fout,
11832 const char *servername, const char *namespace,
11834 CatalogId catalogId, DumpId dumpId)
11846 q = createPQExpBuffer();
11847 tag = createPQExpBuffer();
11848 delq = createPQExpBuffer();
11849 query = createPQExpBuffer();
11852 * We read from the publicly accessible view pg_user_mappings, so as not
11853 * to fail if run by a non-superuser. Note that the view will show
11854 * umoptions as null if the user hasn't got privileges for the associated
11855 * server; this means that pg_dump will dump such a mapping, but with no
11856 * OPTIONS clause. A possible alternative is to skip such mappings
11857 * altogether, but it's not clear that that's an improvement.
11859 selectSourceSchema(fout, "pg_catalog");
11861 appendPQExpBuffer(query,
11863 "array_to_string(ARRAY("
11864 "SELECT quote_ident(option_name) || ' ' || "
11865 "quote_literal(option_value) "
11866 "FROM pg_options_to_table(umoptions) "
11867 "ORDER BY option_name"
11868 "), E',\n ') AS umoptions "
11869 "FROM pg_user_mappings "
11870 "WHERE srvid = '%u' "
11871 "ORDER BY usename",
11874 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11876 ntups = PQntuples(res);
11877 i_usename = PQfnumber(res, "usename");
11878 i_umoptions = PQfnumber(res, "umoptions");
11880 for (i = 0; i < ntups; i++)
11885 usename = PQgetvalue(res, i, i_usename);
11886 umoptions = PQgetvalue(res, i, i_umoptions);
11888 resetPQExpBuffer(q);
11889 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11890 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11892 if (umoptions && strlen(umoptions) > 0)
11893 appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
11895 appendPQExpBuffer(q, ";\n");
11897 resetPQExpBuffer(delq);
11898 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11899 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11901 resetPQExpBuffer(tag);
11902 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11903 usename, servername);
11905 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11910 "USER MAPPING", SECTION_PRE_DATA,
11911 q->data, delq->data, NULL,
11918 destroyPQExpBuffer(query);
11919 destroyPQExpBuffer(delq);
11920 destroyPQExpBuffer(q);
11924 * Write out default privileges information
11927 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11933 /* Skip if not to be dumped */
11934 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11937 q = createPQExpBuffer();
11938 tag = createPQExpBuffer();
11940 switch (daclinfo->defaclobjtype)
11942 case DEFACLOBJ_RELATION:
11945 case DEFACLOBJ_SEQUENCE:
11946 type = "SEQUENCES";
11948 case DEFACLOBJ_FUNCTION:
11949 type = "FUNCTIONS";
11952 /* shouldn't get here */
11953 write_msg(NULL, "unknown object type (%d) in default privileges\n",
11954 (int) daclinfo->defaclobjtype);
11956 type = ""; /* keep compiler quiet */
11959 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11961 /* build the actual command(s) for this tuple */
11962 if (!buildDefaultACLCommands(type,
11963 daclinfo->dobj.namespace != NULL ?
11964 daclinfo->dobj.namespace->dobj.name : NULL,
11965 daclinfo->defaclacl,
11966 daclinfo->defaclrole,
11967 fout->remoteVersion,
11970 write_msg(NULL, "could not parse default ACL list (%s)\n",
11971 daclinfo->defaclacl);
11975 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11977 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11979 daclinfo->defaclrole,
11980 false, "DEFAULT ACL", SECTION_NONE,
11982 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11985 destroyPQExpBuffer(tag);
11986 destroyPQExpBuffer(q);
11990 * Write out grant/revoke information
11992 * 'objCatId' is the catalog ID of the underlying object.
11993 * 'objDumpId' is the dump ID of the underlying object.
11994 * 'type' must be one of
11995 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11996 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11997 * 'name' is the formatted name of the object. Must be quoted etc. already.
11998 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11999 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
12000 * 'nspname' is the namespace the object is in (NULL if none).
12001 * 'owner' is the owner, NULL if there is no owner (for languages).
12002 * 'acls' is the string read out of the fooacl system catalog field;
12003 * it will be parsed here.
12007 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
12008 const char *type, const char *name, const char *subname,
12009 const char *tag, const char *nspname, const char *owner,
12014 /* Do nothing if ACL dump is not enabled */
12018 /* --data-only skips ACLs *except* BLOB ACLs */
12019 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
12022 sql = createPQExpBuffer();
12024 if (!buildACLCommands(name, subname, type, acls, owner,
12025 "", fout->remoteVersion, sql))
12027 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
12033 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12036 owner ? owner : "",
12037 false, "ACL", SECTION_NONE,
12038 sql->data, "", NULL,
12042 destroyPQExpBuffer(sql);
12048 * This routine is used to dump any security labels associated with the
12049 * object handed to this routine. The routine takes a constant character
12050 * string for the target part of the security-label command, plus
12051 * the namespace and owner of the object (for labeling the ArchiveEntry),
12052 * plus catalog ID and subid which are the lookup key for pg_seclabel,
12053 * plus the dump ID for the object (for setting a dependency).
12054 * If a matching pg_seclabel entry is found, it is dumped.
12056 * Note: although this routine takes a dumpId for dependency purposes,
12057 * that purpose is just to mark the dependency in the emitted dump file
12058 * for possible future use by pg_restore. We do NOT use it for determining
12059 * ordering of the label in the dump file, because this routine is called
12060 * after dependency sorting occurs. This routine should be called just after
12061 * calling ArchiveEntry() for the specified object.
12064 dumpSecLabel(Archive *fout, const char *target,
12065 const char *namespace, const char *owner,
12066 CatalogId catalogId, int subid, DumpId dumpId)
12068 SecLabelItem *labels;
12073 /* do nothing, if --no-security-labels is supplied */
12074 if (no_security_labels)
12077 /* Comments are schema not data ... except blob comments are data */
12078 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
12089 /* Search for security labels associated with catalogId, using table */
12090 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
12092 query = createPQExpBuffer();
12094 for (i = 0; i < nlabels; i++)
12097 * Ignore label entries for which the subid doesn't match.
12099 if (labels[i].objsubid != subid)
12102 appendPQExpBuffer(query,
12103 "SECURITY LABEL FOR %s ON %s IS ",
12104 fmtId(labels[i].provider), target);
12105 appendStringLiteralAH(query, labels[i].label, fout);
12106 appendPQExpBuffer(query, ";\n");
12109 if (query->len > 0)
12111 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12112 target, namespace, NULL, owner,
12113 false, "SECURITY LABEL", SECTION_NONE,
12114 query->data, "", NULL,
12118 destroyPQExpBuffer(query);
12122 * dumpTableSecLabel
12124 * As above, but dump security label for both the specified table (or view)
12128 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
12130 SecLabelItem *labels;
12134 PQExpBuffer target;
12136 /* do nothing, if --no-security-labels is supplied */
12137 if (no_security_labels)
12140 /* SecLabel are SCHEMA not data */
12144 /* Search for comments associated with relation, using table */
12145 nlabels = findSecLabels(fout,
12146 tbinfo->dobj.catId.tableoid,
12147 tbinfo->dobj.catId.oid,
12150 /* If security labels exist, build SECURITY LABEL statements */
12154 query = createPQExpBuffer();
12155 target = createPQExpBuffer();
12157 for (i = 0; i < nlabels; i++)
12159 const char *colname;
12160 const char *provider = labels[i].provider;
12161 const char *label = labels[i].label;
12162 int objsubid = labels[i].objsubid;
12164 resetPQExpBuffer(target);
12167 appendPQExpBuffer(target, "%s %s", reltypename,
12168 fmtId(tbinfo->dobj.name));
12172 colname = getAttrName(objsubid, tbinfo);
12173 /* first fmtId result must be consumed before calling it again */
12174 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
12175 appendPQExpBuffer(target, ".%s", fmtId(colname));
12177 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
12178 fmtId(provider), target->data);
12179 appendStringLiteralAH(query, label, fout);
12180 appendPQExpBuffer(query, ";\n");
12182 if (query->len > 0)
12184 resetPQExpBuffer(target);
12185 appendPQExpBuffer(target, "%s %s", reltypename,
12186 fmtId(tbinfo->dobj.name));
12187 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12189 tbinfo->dobj.namespace->dobj.name,
12190 NULL, tbinfo->rolname,
12191 false, "SECURITY LABEL", SECTION_NONE,
12192 query->data, "", NULL,
12193 &(tbinfo->dobj.dumpId), 1,
12196 destroyPQExpBuffer(query);
12197 destroyPQExpBuffer(target);
12203 * Find the security label(s), if any, associated with the given object.
12204 * All the objsubid values associated with the given classoid/objoid are
12205 * found with one search.
12208 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12210 /* static storage for table of security labels */
12211 static SecLabelItem *labels = NULL;
12212 static int nlabels = -1;
12214 SecLabelItem *middle = NULL;
12216 SecLabelItem *high;
12219 /* Get security labels if we didn't already */
12221 nlabels = collectSecLabels(fout, &labels);
12223 if (nlabels <= 0) /* no labels, so no match is possible */
12230 * Do binary search to find some item matching the object.
12233 high = &labels[nlabels - 1];
12234 while (low <= high)
12236 middle = low + (high - low) / 2;
12238 if (classoid < middle->classoid)
12240 else if (classoid > middle->classoid)
12242 else if (objoid < middle->objoid)
12244 else if (objoid > middle->objoid)
12247 break; /* found a match */
12250 if (low > high) /* no matches */
12257 * Now determine how many items match the object. The search loop
12258 * invariant still holds: only items between low and high inclusive could
12262 while (middle > low)
12264 if (classoid != middle[-1].classoid ||
12265 objoid != middle[-1].objoid)
12274 while (middle <= high)
12276 if (classoid != middle->classoid ||
12277 objoid != middle->objoid)
12289 * Construct a table of all security labels available for database objects.
12290 * It's much faster to pull them all at once.
12292 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12295 collectSecLabels(Archive *fout, SecLabelItem **items)
12306 SecLabelItem *labels;
12308 query = createPQExpBuffer();
12310 appendPQExpBuffer(query,
12311 "SELECT label, provider, classoid, objoid, objsubid "
12312 "FROM pg_catalog.pg_seclabel "
12313 "ORDER BY classoid, objoid, objsubid");
12315 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12317 /* Construct lookup table containing OIDs in numeric form */
12318 i_label = PQfnumber(res, "label");
12319 i_provider = PQfnumber(res, "provider");
12320 i_classoid = PQfnumber(res, "classoid");
12321 i_objoid = PQfnumber(res, "objoid");
12322 i_objsubid = PQfnumber(res, "objsubid");
12324 ntups = PQntuples(res);
12326 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12328 for (i = 0; i < ntups; i++)
12330 labels[i].label = PQgetvalue(res, i, i_label);
12331 labels[i].provider = PQgetvalue(res, i, i_provider);
12332 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12333 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12334 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12337 /* Do NOT free the PGresult since we are keeping pointers into it */
12338 destroyPQExpBuffer(query);
12346 * write out to fout the declarations (not data) of a user-defined table
12349 dumpTable(Archive *fout, TableInfo *tbinfo)
12351 if (tbinfo->dobj.dump)
12355 if (tbinfo->relkind == RELKIND_SEQUENCE)
12356 dumpSequence(fout, tbinfo);
12357 else if (!dataOnly)
12358 dumpTableSchema(fout, tbinfo);
12360 /* Handle the ACL here */
12361 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12362 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12363 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12365 namecopy, NULL, tbinfo->dobj.name,
12366 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12370 * Handle column ACLs, if any. Note: we pull these with a separate
12371 * query rather than trying to fetch them during getTableAttrs, so
12372 * that we won't miss ACLs on system columns.
12374 if (fout->remoteVersion >= 80400)
12376 PQExpBuffer query = createPQExpBuffer();
12380 appendPQExpBuffer(query,
12381 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12382 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12384 tbinfo->dobj.catId.oid);
12385 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12387 for (i = 0; i < PQntuples(res); i++)
12389 char *attname = PQgetvalue(res, i, 0);
12390 char *attacl = PQgetvalue(res, i, 1);
12394 attnamecopy = pg_strdup(fmtId(attname));
12395 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12396 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12397 /* Column's GRANT type is always TABLE */
12398 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12399 namecopy, attnamecopy, acltag,
12400 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12406 destroyPQExpBuffer(query);
12415 * write the declaration (not data) of one user-defined table or view
12418 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12420 PQExpBuffer query = createPQExpBuffer();
12421 PQExpBuffer q = createPQExpBuffer();
12422 PQExpBuffer delq = createPQExpBuffer();
12423 PQExpBuffer labelq = createPQExpBuffer();
12426 TableInfo **parents;
12427 int actual_atts; /* number of attrs in this CREATE statment */
12428 const char *reltypename;
12435 /* Make sure we are in proper schema */
12436 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
12438 if (binary_upgrade)
12439 binary_upgrade_set_type_oids_by_rel_oid(fout, q,
12440 tbinfo->dobj.catId.oid);
12442 /* Is it a table or a view? */
12443 if (tbinfo->relkind == RELKIND_VIEW)
12447 reltypename = "VIEW";
12449 /* Fetch the view definition */
12450 if (fout->remoteVersion >= 70300)
12452 /* Beginning in 7.3, viewname is not unique; rely on OID */
12453 appendPQExpBuffer(query,
12454 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12455 tbinfo->dobj.catId.oid);
12459 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12460 "FROM pg_views WHERE viewname = ");
12461 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12462 appendPQExpBuffer(query, ";");
12465 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12467 if (PQntuples(res) != 1)
12469 if (PQntuples(res) < 1)
12470 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12471 tbinfo->dobj.name);
12473 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12474 tbinfo->dobj.name);
12478 viewdef = PQgetvalue(res, 0, 0);
12480 if (strlen(viewdef) == 0)
12482 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12483 tbinfo->dobj.name);
12488 * DROP must be fully qualified in case same name appears in
12491 appendPQExpBuffer(delq, "DROP VIEW %s.",
12492 fmtId(tbinfo->dobj.namespace->dobj.name));
12493 appendPQExpBuffer(delq, "%s;\n",
12494 fmtId(tbinfo->dobj.name));
12496 if (binary_upgrade)
12497 binary_upgrade_set_pg_class_oids(fout, q,
12498 tbinfo->dobj.catId.oid, false);
12500 appendPQExpBuffer(q, "CREATE VIEW %s", fmtId(tbinfo->dobj.name));
12501 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12502 appendPQExpBuffer(q, " WITH (%s)", tbinfo->reloptions);
12503 appendPQExpBuffer(q, " AS\n %s\n", viewdef);
12505 appendPQExpBuffer(labelq, "VIEW %s",
12506 fmtId(tbinfo->dobj.name));
12512 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12517 reltypename = "FOREIGN TABLE";
12519 /* retrieve name of foreign server and generic options */
12520 appendPQExpBuffer(query,
12521 "SELECT fs.srvname, "
12522 "pg_catalog.array_to_string(ARRAY("
12523 "SELECT pg_catalog.quote_ident(option_name) || "
12524 "' ' || pg_catalog.quote_literal(option_value) "
12525 "FROM pg_catalog.pg_options_to_table(ftoptions) "
12526 "ORDER BY option_name"
12527 "), E',\n ') AS ftoptions "
12528 "FROM pg_catalog.pg_foreign_table ft "
12529 "JOIN pg_catalog.pg_foreign_server fs "
12530 "ON (fs.oid = ft.ftserver) "
12531 "WHERE ft.ftrelid = '%u'",
12532 tbinfo->dobj.catId.oid);
12533 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
12534 if (PQntuples(res) != 1)
12536 write_msg(NULL, ngettext("query returned %d foreign server entry for foreign table \"%s\"\n",
12537 "query returned %d foreign server entries for foreign table \"%s\"\n",
12539 PQntuples(res), tbinfo->dobj.name);
12542 i_srvname = PQfnumber(res, "srvname");
12543 i_ftoptions = PQfnumber(res, "ftoptions");
12544 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12545 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12550 reltypename = "TABLE";
12554 numParents = tbinfo->numParents;
12555 parents = tbinfo->parents;
12558 * DROP must be fully qualified in case same name appears in
12561 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12562 fmtId(tbinfo->dobj.namespace->dobj.name));
12563 appendPQExpBuffer(delq, "%s;\n",
12564 fmtId(tbinfo->dobj.name));
12566 appendPQExpBuffer(labelq, "%s %s", reltypename,
12567 fmtId(tbinfo->dobj.name));
12569 if (binary_upgrade)
12570 binary_upgrade_set_pg_class_oids(fout, q,
12571 tbinfo->dobj.catId.oid, false);
12573 appendPQExpBuffer(q, "CREATE %s%s %s",
12574 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12577 fmtId(tbinfo->dobj.name));
12580 * Attach to type, if reloftype; except in case of a binary upgrade,
12581 * we dump the table normally and attach it to the type afterward.
12583 if (tbinfo->reloftype && !binary_upgrade)
12584 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12586 /* Dump the attributes */
12588 for (j = 0; j < tbinfo->numatts; j++)
12591 * Normally, dump if it's locally defined in this table, and not
12592 * dropped. But for binary upgrade, we'll dump all the columns,
12593 * and then fix up the dropped and nonlocal cases below.
12595 if (shouldPrintColumn(tbinfo, j))
12598 * Default value --- suppress if to be printed separately.
12600 bool has_default = (tbinfo->attrdefs[j] != NULL &&
12601 !tbinfo->attrdefs[j]->separate);
12604 * Not Null constraint --- suppress if inherited, except in
12605 * binary-upgrade case where that won't work.
12607 bool has_notnull = (tbinfo->notnull[j] &&
12608 (!tbinfo->inhNotNull[j] ||
12611 /* Skip column if fully defined by reloftype */
12612 if (tbinfo->reloftype &&
12613 !has_default && !has_notnull && !binary_upgrade)
12616 /* Format properly if not first attr */
12617 if (actual_atts == 0)
12618 appendPQExpBuffer(q, " (");
12620 appendPQExpBuffer(q, ",");
12621 appendPQExpBuffer(q, "\n ");
12624 /* Attribute name */
12625 appendPQExpBuffer(q, "%s ",
12626 fmtId(tbinfo->attnames[j]));
12628 if (tbinfo->attisdropped[j])
12631 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12632 * so we will not have gotten a valid type name; insert
12633 * INTEGER as a stopgap. We'll clean things up later.
12635 appendPQExpBuffer(q, "INTEGER /* dummy */");
12636 /* Skip all the rest, too */
12640 /* Attribute type */
12641 if (tbinfo->reloftype && !binary_upgrade)
12643 appendPQExpBuffer(q, "WITH OPTIONS");
12645 else if (fout->remoteVersion >= 70100)
12647 appendPQExpBuffer(q, "%s",
12648 tbinfo->atttypnames[j]);
12652 /* If no format_type, fake it */
12653 appendPQExpBuffer(q, "%s",
12654 myFormatType(tbinfo->atttypnames[j],
12655 tbinfo->atttypmod[j]));
12658 /* Add collation if not default for the type */
12659 if (OidIsValid(tbinfo->attcollation[j]))
12663 coll = findCollationByOid(tbinfo->attcollation[j]);
12666 /* always schema-qualify, don't try to be smart */
12667 appendPQExpBuffer(q, " COLLATE %s.",
12668 fmtId(coll->dobj.namespace->dobj.name));
12669 appendPQExpBuffer(q, "%s",
12670 fmtId(coll->dobj.name));
12675 appendPQExpBuffer(q, " DEFAULT %s",
12676 tbinfo->attrdefs[j]->adef_expr);
12679 appendPQExpBuffer(q, " NOT NULL");
12684 * Add non-inherited CHECK constraints, if any.
12686 for (j = 0; j < tbinfo->ncheck; j++)
12688 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12690 if (constr->separate || !constr->conislocal)
12693 if (actual_atts == 0)
12694 appendPQExpBuffer(q, " (\n ");
12696 appendPQExpBuffer(q, ",\n ");
12698 appendPQExpBuffer(q, "CONSTRAINT %s ",
12699 fmtId(constr->dobj.name));
12700 appendPQExpBuffer(q, "%s", constr->condef);
12706 appendPQExpBuffer(q, "\n)");
12707 else if (!(tbinfo->reloftype && !binary_upgrade))
12710 * We must have a parenthesized attribute list, even though empty,
12711 * when not using the OF TYPE syntax.
12713 appendPQExpBuffer(q, " (\n)");
12716 if (numParents > 0 && !binary_upgrade)
12718 appendPQExpBuffer(q, "\nINHERITS (");
12719 for (k = 0; k < numParents; k++)
12721 TableInfo *parentRel = parents[k];
12724 appendPQExpBuffer(q, ", ");
12725 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12726 appendPQExpBuffer(q, "%s.",
12727 fmtId(parentRel->dobj.namespace->dobj.name));
12728 appendPQExpBuffer(q, "%s",
12729 fmtId(parentRel->dobj.name));
12731 appendPQExpBuffer(q, ")");
12734 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12735 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12737 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12738 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12740 bool addcomma = false;
12742 appendPQExpBuffer(q, "\nWITH (");
12743 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12746 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12748 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12750 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12751 tbinfo->toast_reloptions);
12753 appendPQExpBuffer(q, ")");
12756 /* Dump generic options if any */
12757 if (ftoptions && ftoptions[0])
12758 appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
12760 appendPQExpBuffer(q, ";\n");
12763 * To create binary-compatible heap files, we have to ensure the same
12764 * physical column order, including dropped columns, as in the
12765 * original. Therefore, we create dropped columns above and drop them
12766 * here, also updating their attlen/attalign values so that the
12767 * dropped column can be skipped properly. (We do not bother with
12768 * restoring the original attbyval setting.) Also, inheritance
12769 * relationships are set up by doing ALTER INHERIT rather than using
12770 * an INHERITS clause --- the latter would possibly mess up the column
12771 * order. That also means we have to take care about setting
12772 * attislocal correctly, plus fix up any inherited CHECK constraints.
12773 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12775 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12777 for (j = 0; j < tbinfo->numatts; j++)
12779 if (tbinfo->attisdropped[j])
12781 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12782 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12783 "SET attlen = %d, "
12784 "attalign = '%c', attbyval = false\n"
12785 "WHERE attname = ",
12787 tbinfo->attalign[j]);
12788 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12789 appendPQExpBuffer(q, "\n AND attrelid = ");
12790 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12791 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12793 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12794 fmtId(tbinfo->dobj.name));
12795 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12796 fmtId(tbinfo->attnames[j]));
12798 else if (!tbinfo->attislocal[j])
12800 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12801 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12802 "SET attislocal = false\n"
12803 "WHERE attname = ");
12804 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12805 appendPQExpBuffer(q, "\n AND attrelid = ");
12806 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12807 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12811 for (k = 0; k < tbinfo->ncheck; k++)
12813 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12815 if (constr->separate || constr->conislocal)
12818 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12819 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12820 fmtId(tbinfo->dobj.name));
12821 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12822 fmtId(constr->dobj.name));
12823 appendPQExpBuffer(q, "%s;\n", constr->condef);
12824 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12825 "SET conislocal = false\n"
12826 "WHERE contype = 'c' AND conname = ");
12827 appendStringLiteralAH(q, constr->dobj.name, fout);
12828 appendPQExpBuffer(q, "\n AND conrelid = ");
12829 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12830 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12833 if (numParents > 0)
12835 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12836 for (k = 0; k < numParents; k++)
12838 TableInfo *parentRel = parents[k];
12840 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12841 fmtId(tbinfo->dobj.name));
12842 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12843 appendPQExpBuffer(q, "%s.",
12844 fmtId(parentRel->dobj.namespace->dobj.name));
12845 appendPQExpBuffer(q, "%s;\n",
12846 fmtId(parentRel->dobj.name));
12850 if (tbinfo->reloftype)
12852 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12853 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12854 fmtId(tbinfo->dobj.name),
12855 tbinfo->reloftype);
12858 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12859 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12860 "SET relfrozenxid = '%u'\n"
12862 tbinfo->frozenxid);
12863 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12864 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12866 if (tbinfo->toast_oid)
12868 /* We preserve the toast oids, so we can use it during restore */
12869 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12870 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12871 "SET relfrozenxid = '%u'\n"
12872 "WHERE oid = '%u';\n",
12873 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12878 * Dump additional per-column properties that we can't handle in the
12879 * main CREATE TABLE command.
12881 for (j = 0; j < tbinfo->numatts; j++)
12883 /* None of this applies to dropped columns */
12884 if (tbinfo->attisdropped[j])
12888 * If we didn't dump the column definition explicitly above, and
12889 * it is NOT NULL and did not inherit that property from a parent,
12890 * we have to mark it separately.
12892 if (!shouldPrintColumn(tbinfo, j) &&
12893 tbinfo->notnull[j] && !tbinfo->inhNotNull[j])
12895 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12896 fmtId(tbinfo->dobj.name));
12897 appendPQExpBuffer(q, "ALTER COLUMN %s SET NOT NULL;\n",
12898 fmtId(tbinfo->attnames[j]));
12902 * Dump per-column statistics information. We only issue an ALTER
12903 * TABLE statement if the attstattarget entry for this column is
12904 * non-negative (i.e. it's not the default value)
12906 if (tbinfo->attstattarget[j] >= 0)
12908 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12909 fmtId(tbinfo->dobj.name));
12910 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12911 fmtId(tbinfo->attnames[j]));
12912 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12913 tbinfo->attstattarget[j]);
12917 * Dump per-column storage information. The statement is only
12918 * dumped if the storage has been changed from the type's default.
12920 if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
12922 switch (tbinfo->attstorage[j])
12928 storage = "EXTERNAL";
12934 storage = "EXTENDED";
12941 * Only dump the statement if it's a storage type we recognize
12943 if (storage != NULL)
12945 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12946 fmtId(tbinfo->dobj.name));
12947 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12948 fmtId(tbinfo->attnames[j]));
12949 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12955 * Dump per-column attributes.
12957 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12959 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12960 fmtId(tbinfo->dobj.name));
12961 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12962 fmtId(tbinfo->attnames[j]));
12963 appendPQExpBuffer(q, "SET (%s);\n",
12964 tbinfo->attoptions[j]);
12968 * Dump per-column fdw options.
12970 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12971 tbinfo->attfdwoptions[j] &&
12972 tbinfo->attfdwoptions[j][0] != '\0')
12974 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12975 fmtId(tbinfo->dobj.name));
12976 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12977 fmtId(tbinfo->attnames[j]));
12978 appendPQExpBuffer(q, "OPTIONS (\n %s\n);\n",
12979 tbinfo->attfdwoptions[j]);
12984 if (binary_upgrade)
12985 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12987 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12989 tbinfo->dobj.namespace->dobj.name,
12990 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12992 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12993 reltypename, SECTION_PRE_DATA,
12994 q->data, delq->data, NULL,
12995 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12999 /* Dump Table Comments */
13000 dumpTableComment(fout, tbinfo, reltypename);
13002 /* Dump Table Security Labels */
13003 dumpTableSecLabel(fout, tbinfo, reltypename);
13005 /* Dump comments on inlined table constraints */
13006 for (j = 0; j < tbinfo->ncheck; j++)
13008 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
13010 if (constr->separate || !constr->conislocal)
13013 dumpTableConstraintComment(fout, constr);
13016 destroyPQExpBuffer(query);
13017 destroyPQExpBuffer(q);
13018 destroyPQExpBuffer(delq);
13019 destroyPQExpBuffer(labelq);
13023 * dumpAttrDef --- dump an attribute's default-value declaration
13026 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
13028 TableInfo *tbinfo = adinfo->adtable;
13029 int adnum = adinfo->adnum;
13033 /* Skip if table definition not to be dumped */
13034 if (!tbinfo->dobj.dump || dataOnly)
13037 /* Skip if not "separate"; it was dumped in the table's definition */
13038 if (!adinfo->separate)
13041 q = createPQExpBuffer();
13042 delq = createPQExpBuffer();
13044 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
13045 fmtId(tbinfo->dobj.name));
13046 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
13047 fmtId(tbinfo->attnames[adnum - 1]),
13048 adinfo->adef_expr);
13051 * DROP must be fully qualified in case same name appears in pg_catalog
13053 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13054 fmtId(tbinfo->dobj.namespace->dobj.name));
13055 appendPQExpBuffer(delq, "%s ",
13056 fmtId(tbinfo->dobj.name));
13057 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
13058 fmtId(tbinfo->attnames[adnum - 1]));
13060 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
13061 tbinfo->attnames[adnum - 1],
13062 tbinfo->dobj.namespace->dobj.name,
13065 false, "DEFAULT", SECTION_PRE_DATA,
13066 q->data, delq->data, NULL,
13067 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
13070 destroyPQExpBuffer(q);
13071 destroyPQExpBuffer(delq);
13075 * getAttrName: extract the correct name for an attribute
13077 * The array tblInfo->attnames[] only provides names of user attributes;
13078 * if a system attribute number is supplied, we have to fake it.
13079 * We also do a little bit of bounds checking for safety's sake.
13081 static const char *
13082 getAttrName(int attrnum, TableInfo *tblInfo)
13084 if (attrnum > 0 && attrnum <= tblInfo->numatts)
13085 return tblInfo->attnames[attrnum - 1];
13088 case SelfItemPointerAttributeNumber:
13090 case ObjectIdAttributeNumber:
13092 case MinTransactionIdAttributeNumber:
13094 case MinCommandIdAttributeNumber:
13096 case MaxTransactionIdAttributeNumber:
13098 case MaxCommandIdAttributeNumber:
13100 case TableOidAttributeNumber:
13103 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
13104 attrnum, tblInfo->dobj.name);
13106 return NULL; /* keep compiler quiet */
13111 * write out to fout a user-defined index
13114 dumpIndex(Archive *fout, IndxInfo *indxinfo)
13116 TableInfo *tbinfo = indxinfo->indextable;
13119 PQExpBuffer labelq;
13124 q = createPQExpBuffer();
13125 delq = createPQExpBuffer();
13126 labelq = createPQExpBuffer();
13128 appendPQExpBuffer(labelq, "INDEX %s",
13129 fmtId(indxinfo->dobj.name));
13132 * If there's an associated constraint, don't dump the index per se, but
13133 * do dump any comment for it. (This is safe because dependency ordering
13134 * will have ensured the constraint is emitted first.)
13136 if (indxinfo->indexconstraint == 0)
13138 if (binary_upgrade)
13139 binary_upgrade_set_pg_class_oids(fout, q,
13140 indxinfo->dobj.catId.oid, true);
13142 /* Plain secondary index */
13143 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
13145 /* If the index is clustered, we need to record that. */
13146 if (indxinfo->indisclustered)
13148 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13149 fmtId(tbinfo->dobj.name));
13150 appendPQExpBuffer(q, " ON %s;\n",
13151 fmtId(indxinfo->dobj.name));
13155 * DROP must be fully qualified in case same name appears in
13158 appendPQExpBuffer(delq, "DROP INDEX %s.",
13159 fmtId(tbinfo->dobj.namespace->dobj.name));
13160 appendPQExpBuffer(delq, "%s;\n",
13161 fmtId(indxinfo->dobj.name));
13163 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
13164 indxinfo->dobj.name,
13165 tbinfo->dobj.namespace->dobj.name,
13166 indxinfo->tablespace,
13167 tbinfo->rolname, false,
13168 "INDEX", SECTION_POST_DATA,
13169 q->data, delq->data, NULL,
13170 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
13174 /* Dump Index Comments */
13175 dumpComment(fout, labelq->data,
13176 tbinfo->dobj.namespace->dobj.name,
13178 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
13180 destroyPQExpBuffer(q);
13181 destroyPQExpBuffer(delq);
13182 destroyPQExpBuffer(labelq);
13187 * write out to fout a user-defined constraint
13190 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
13192 TableInfo *tbinfo = coninfo->contable;
13196 /* Skip if not to be dumped */
13197 if (!coninfo->dobj.dump || dataOnly)
13200 q = createPQExpBuffer();
13201 delq = createPQExpBuffer();
13203 if (coninfo->contype == 'p' ||
13204 coninfo->contype == 'u' ||
13205 coninfo->contype == 'x')
13207 /* Index-related constraint */
13208 IndxInfo *indxinfo;
13211 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13213 if (indxinfo == NULL)
13215 write_msg(NULL, "missing index for constraint \"%s\"\n",
13216 coninfo->dobj.name);
13220 if (binary_upgrade)
13221 binary_upgrade_set_pg_class_oids(fout, q,
13222 indxinfo->dobj.catId.oid, true);
13224 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13225 fmtId(tbinfo->dobj.name));
13226 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13227 fmtId(coninfo->dobj.name));
13229 if (coninfo->condef)
13231 /* pg_get_constraintdef should have provided everything */
13232 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13236 appendPQExpBuffer(q, "%s (",
13237 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13238 for (k = 0; k < indxinfo->indnkeys; k++)
13240 int indkey = (int) indxinfo->indkeys[k];
13241 const char *attname;
13243 if (indkey == InvalidAttrNumber)
13245 attname = getAttrName(indkey, tbinfo);
13247 appendPQExpBuffer(q, "%s%s",
13248 (k == 0) ? "" : ", ",
13252 appendPQExpBuffer(q, ")");
13254 if (indxinfo->options && strlen(indxinfo->options) > 0)
13255 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13257 if (coninfo->condeferrable)
13259 appendPQExpBuffer(q, " DEFERRABLE");
13260 if (coninfo->condeferred)
13261 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13264 appendPQExpBuffer(q, ";\n");
13267 /* If the index is clustered, we need to record that. */
13268 if (indxinfo->indisclustered)
13270 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13271 fmtId(tbinfo->dobj.name));
13272 appendPQExpBuffer(q, " ON %s;\n",
13273 fmtId(indxinfo->dobj.name));
13277 * DROP must be fully qualified in case same name appears in
13280 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13281 fmtId(tbinfo->dobj.namespace->dobj.name));
13282 appendPQExpBuffer(delq, "%s ",
13283 fmtId(tbinfo->dobj.name));
13284 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13285 fmtId(coninfo->dobj.name));
13287 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13288 coninfo->dobj.name,
13289 tbinfo->dobj.namespace->dobj.name,
13290 indxinfo->tablespace,
13291 tbinfo->rolname, false,
13292 "CONSTRAINT", SECTION_POST_DATA,
13293 q->data, delq->data, NULL,
13294 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13297 else if (coninfo->contype == 'f')
13300 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13301 * current table data is not processed
13303 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13304 fmtId(tbinfo->dobj.name));
13305 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13306 fmtId(coninfo->dobj.name),
13310 * DROP must be fully qualified in case same name appears in
13313 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13314 fmtId(tbinfo->dobj.namespace->dobj.name));
13315 appendPQExpBuffer(delq, "%s ",
13316 fmtId(tbinfo->dobj.name));
13317 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13318 fmtId(coninfo->dobj.name));
13320 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13321 coninfo->dobj.name,
13322 tbinfo->dobj.namespace->dobj.name,
13324 tbinfo->rolname, false,
13325 "FK CONSTRAINT", SECTION_POST_DATA,
13326 q->data, delq->data, NULL,
13327 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13330 else if (coninfo->contype == 'c' && tbinfo)
13332 /* CHECK constraint on a table */
13334 /* Ignore if not to be dumped separately */
13335 if (coninfo->separate)
13337 /* add ONLY if we do not want it to propagate to children */
13338 appendPQExpBuffer(q, "ALTER TABLE %s %s\n",
13339 coninfo->conisonly ? "ONLY" : "", fmtId(tbinfo->dobj.name));
13340 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13341 fmtId(coninfo->dobj.name),
13345 * DROP must be fully qualified in case same name appears in
13348 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13349 fmtId(tbinfo->dobj.namespace->dobj.name));
13350 appendPQExpBuffer(delq, "%s ",
13351 fmtId(tbinfo->dobj.name));
13352 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13353 fmtId(coninfo->dobj.name));
13355 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13356 coninfo->dobj.name,
13357 tbinfo->dobj.namespace->dobj.name,
13359 tbinfo->rolname, false,
13360 "CHECK CONSTRAINT", SECTION_POST_DATA,
13361 q->data, delq->data, NULL,
13362 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13366 else if (coninfo->contype == 'c' && tbinfo == NULL)
13368 /* CHECK constraint on a domain */
13369 TypeInfo *tyinfo = coninfo->condomain;
13371 /* Ignore if not to be dumped separately */
13372 if (coninfo->separate)
13374 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13375 fmtId(tyinfo->dobj.name));
13376 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13377 fmtId(coninfo->dobj.name),
13381 * DROP must be fully qualified in case same name appears in
13384 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13385 fmtId(tyinfo->dobj.namespace->dobj.name));
13386 appendPQExpBuffer(delq, "%s ",
13387 fmtId(tyinfo->dobj.name));
13388 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13389 fmtId(coninfo->dobj.name));
13391 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13392 coninfo->dobj.name,
13393 tyinfo->dobj.namespace->dobj.name,
13395 tyinfo->rolname, false,
13396 "CHECK CONSTRAINT", SECTION_POST_DATA,
13397 q->data, delq->data, NULL,
13398 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13404 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
13408 /* Dump Constraint Comments --- only works for table constraints */
13409 if (tbinfo && coninfo->separate)
13410 dumpTableConstraintComment(fout, coninfo);
13412 destroyPQExpBuffer(q);
13413 destroyPQExpBuffer(delq);
13417 * dumpTableConstraintComment --- dump a constraint's comment if any
13419 * This is split out because we need the function in two different places
13420 * depending on whether the constraint is dumped as part of CREATE TABLE
13421 * or as a separate ALTER command.
13424 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13426 TableInfo *tbinfo = coninfo->contable;
13427 PQExpBuffer labelq = createPQExpBuffer();
13429 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13430 fmtId(coninfo->dobj.name));
13431 appendPQExpBuffer(labelq, "ON %s",
13432 fmtId(tbinfo->dobj.name));
13433 dumpComment(fout, labelq->data,
13434 tbinfo->dobj.namespace->dobj.name,
13436 coninfo->dobj.catId, 0,
13437 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13439 destroyPQExpBuffer(labelq);
13443 * findLastBuiltInOid -
13444 * find the last built in oid
13446 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13447 * pg_database entry for the current database
13450 findLastBuiltinOid_V71(Archive *fout, const char *dbname)
13455 PQExpBuffer query = createPQExpBuffer();
13457 resetPQExpBuffer(query);
13458 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13459 appendStringLiteralAH(query, dbname, fout);
13461 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13463 ntups = PQntuples(res);
13466 write_msg(NULL, "missing pg_database entry for this database\n");
13471 write_msg(NULL, "found more than one pg_database entry for this database\n");
13474 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13476 destroyPQExpBuffer(query);
13481 * findLastBuiltInOid -
13482 * find the last built in oid
13484 * For 7.0, we do this by assuming that the last thing that initdb does is to
13485 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13486 * initdb won't be changing anymore, it'll do.
13489 findLastBuiltinOid_V70(Archive *fout)
13495 res = ExecuteSqlQuery(fout,
13496 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
13498 ntups = PQntuples(res);
13501 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
13506 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
13509 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13515 dumpSequence(Archive *fout, TableInfo *tbinfo)
13528 PQExpBuffer query = createPQExpBuffer();
13529 PQExpBuffer delqry = createPQExpBuffer();
13530 PQExpBuffer labelq = createPQExpBuffer();
13532 /* Make sure we are in proper schema */
13533 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13535 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13536 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13538 if (fout->remoteVersion >= 80400)
13540 appendPQExpBuffer(query,
13541 "SELECT sequence_name, "
13542 "start_value, last_value, increment_by, "
13543 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13544 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13546 "END AS max_value, "
13547 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13548 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13550 "END AS min_value, "
13551 "cache_value, is_cycled, is_called from %s",
13553 fmtId(tbinfo->dobj.name));
13557 appendPQExpBuffer(query,
13558 "SELECT sequence_name, "
13559 "0 AS start_value, last_value, increment_by, "
13560 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13561 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13563 "END AS max_value, "
13564 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13565 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13567 "END AS min_value, "
13568 "cache_value, is_cycled, is_called from %s",
13570 fmtId(tbinfo->dobj.name));
13573 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13575 if (PQntuples(res) != 1)
13577 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13578 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13580 tbinfo->dobj.name, PQntuples(res));
13584 /* Disable this check: it fails if sequence has been renamed */
13586 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13588 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13589 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13594 startv = PQgetvalue(res, 0, 1);
13595 last = PQgetvalue(res, 0, 2);
13596 incby = PQgetvalue(res, 0, 3);
13597 if (!PQgetisnull(res, 0, 4))
13598 maxv = PQgetvalue(res, 0, 4);
13599 if (!PQgetisnull(res, 0, 5))
13600 minv = PQgetvalue(res, 0, 5);
13601 cache = PQgetvalue(res, 0, 6);
13602 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13603 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13606 * The logic we use for restoring sequences is as follows:
13608 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13609 * last_val for start if called is false, else use min_val for start_val).
13610 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13611 * BY command for it.
13613 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13618 * DROP must be fully qualified in case same name appears in
13621 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13622 fmtId(tbinfo->dobj.namespace->dobj.name));
13623 appendPQExpBuffer(delqry, "%s;\n",
13624 fmtId(tbinfo->dobj.name));
13626 resetPQExpBuffer(query);
13628 if (binary_upgrade)
13630 binary_upgrade_set_pg_class_oids(fout, query,
13631 tbinfo->dobj.catId.oid, false);
13632 binary_upgrade_set_type_oids_by_rel_oid(fout, query,
13633 tbinfo->dobj.catId.oid);
13636 appendPQExpBuffer(query,
13637 "CREATE SEQUENCE %s\n",
13638 fmtId(tbinfo->dobj.name));
13640 if (fout->remoteVersion >= 80400)
13641 appendPQExpBuffer(query, " START WITH %s\n", startv);
13645 * Versions before 8.4 did not remember the true start value. If
13646 * is_called is false then the sequence has never been incremented
13647 * so we can use last_val. Otherwise punt and let it default.
13650 appendPQExpBuffer(query, " START WITH %s\n", last);
13653 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13656 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13658 appendPQExpBuffer(query, " NO MINVALUE\n");
13661 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13663 appendPQExpBuffer(query, " NO MAXVALUE\n");
13665 appendPQExpBuffer(query,
13667 cache, (cycled ? "\n CYCLE" : ""));
13669 appendPQExpBuffer(query, ";\n");
13671 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13673 /* binary_upgrade: no need to clear TOAST table oid */
13675 if (binary_upgrade)
13676 binary_upgrade_extension_member(query, &tbinfo->dobj,
13679 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13681 tbinfo->dobj.namespace->dobj.name,
13684 false, "SEQUENCE", SECTION_PRE_DATA,
13685 query->data, delqry->data, NULL,
13686 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13690 * If the sequence is owned by a table column, emit the ALTER for it
13691 * as a separate TOC entry immediately following the sequence's own
13692 * entry. It's OK to do this rather than using full sorting logic,
13693 * because the dependency that tells us it's owned will have forced
13694 * the table to be created first. We can't just include the ALTER in
13695 * the TOC entry because it will fail if we haven't reassigned the
13696 * sequence owner to match the table's owner.
13698 * We need not schema-qualify the table reference because both
13699 * sequence and table must be in the same schema.
13701 if (OidIsValid(tbinfo->owning_tab))
13703 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13705 if (owning_tab && owning_tab->dobj.dump)
13707 resetPQExpBuffer(query);
13708 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13709 fmtId(tbinfo->dobj.name));
13710 appendPQExpBuffer(query, " OWNED BY %s",
13711 fmtId(owning_tab->dobj.name));
13712 appendPQExpBuffer(query, ".%s;\n",
13713 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13715 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13717 tbinfo->dobj.namespace->dobj.name,
13720 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13721 query->data, "", NULL,
13722 &(tbinfo->dobj.dumpId), 1,
13727 /* Dump Sequence Comments and Security Labels */
13728 dumpComment(fout, labelq->data,
13729 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13730 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13731 dumpSecLabel(fout, labelq->data,
13732 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13733 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13738 resetPQExpBuffer(query);
13739 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13740 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13741 appendPQExpBuffer(query, ", %s, %s);\n",
13742 last, (called ? "true" : "false"));
13744 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13746 tbinfo->dobj.namespace->dobj.name,
13749 false, "SEQUENCE SET", SECTION_PRE_DATA,
13750 query->data, "", NULL,
13751 &(tbinfo->dobj.dumpId), 1,
13757 destroyPQExpBuffer(query);
13758 destroyPQExpBuffer(delqry);
13759 destroyPQExpBuffer(labelq);
13763 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13765 TableInfo *tbinfo = tginfo->tgtable;
13767 PQExpBuffer delqry;
13768 PQExpBuffer labelq;
13777 query = createPQExpBuffer();
13778 delqry = createPQExpBuffer();
13779 labelq = createPQExpBuffer();
13782 * DROP must be fully qualified in case same name appears in pg_catalog
13784 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13785 fmtId(tginfo->dobj.name));
13786 appendPQExpBuffer(delqry, "ON %s.",
13787 fmtId(tbinfo->dobj.namespace->dobj.name));
13788 appendPQExpBuffer(delqry, "%s;\n",
13789 fmtId(tbinfo->dobj.name));
13793 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13797 if (tginfo->tgisconstraint)
13799 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13800 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13804 appendPQExpBuffer(query, "CREATE TRIGGER ");
13805 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13807 appendPQExpBuffer(query, "\n ");
13810 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13811 appendPQExpBuffer(query, "BEFORE");
13812 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13813 appendPQExpBuffer(query, "AFTER");
13814 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13815 appendPQExpBuffer(query, "INSTEAD OF");
13818 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13823 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13825 appendPQExpBuffer(query, " INSERT");
13828 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13831 appendPQExpBuffer(query, " OR DELETE");
13833 appendPQExpBuffer(query, " DELETE");
13836 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13839 appendPQExpBuffer(query, " OR UPDATE");
13841 appendPQExpBuffer(query, " UPDATE");
13844 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13847 appendPQExpBuffer(query, " OR TRUNCATE");
13849 appendPQExpBuffer(query, " TRUNCATE");
13852 appendPQExpBuffer(query, " ON %s\n",
13853 fmtId(tbinfo->dobj.name));
13855 if (tginfo->tgisconstraint)
13857 if (OidIsValid(tginfo->tgconstrrelid))
13859 /* If we are using regclass, name is already quoted */
13860 if (fout->remoteVersion >= 70300)
13861 appendPQExpBuffer(query, " FROM %s\n ",
13862 tginfo->tgconstrrelname);
13864 appendPQExpBuffer(query, " FROM %s\n ",
13865 fmtId(tginfo->tgconstrrelname));
13867 if (!tginfo->tgdeferrable)
13868 appendPQExpBuffer(query, "NOT ");
13869 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13870 if (tginfo->tginitdeferred)
13871 appendPQExpBuffer(query, "DEFERRED\n");
13873 appendPQExpBuffer(query, "IMMEDIATE\n");
13876 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13877 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13879 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13881 /* In 7.3, result of regproc is already quoted */
13882 if (fout->remoteVersion >= 70300)
13883 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13886 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13887 fmtId(tginfo->tgfname));
13889 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13892 for (findx = 0; findx < tginfo->tgnargs; findx++)
13894 /* find the embedded null that terminates this trigger argument */
13895 size_t tlen = strlen(p);
13897 if (p + tlen >= tgargs + lentgargs)
13899 /* hm, not found before end of bytea value... */
13900 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13903 tbinfo->dobj.name);
13908 appendPQExpBuffer(query, ", ");
13909 appendStringLiteralAH(query, p, fout);
13913 appendPQExpBuffer(query, ");\n");
13916 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13918 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13919 fmtId(tbinfo->dobj.name));
13920 switch (tginfo->tgenabled)
13924 appendPQExpBuffer(query, "DISABLE");
13927 appendPQExpBuffer(query, "ENABLE ALWAYS");
13930 appendPQExpBuffer(query, "ENABLE REPLICA");
13933 appendPQExpBuffer(query, "ENABLE");
13936 appendPQExpBuffer(query, " TRIGGER %s;\n",
13937 fmtId(tginfo->dobj.name));
13940 appendPQExpBuffer(labelq, "TRIGGER %s ",
13941 fmtId(tginfo->dobj.name));
13942 appendPQExpBuffer(labelq, "ON %s",
13943 fmtId(tbinfo->dobj.name));
13945 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13947 tbinfo->dobj.namespace->dobj.name,
13949 tbinfo->rolname, false,
13950 "TRIGGER", SECTION_POST_DATA,
13951 query->data, delqry->data, NULL,
13952 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13955 dumpComment(fout, labelq->data,
13956 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13957 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13959 destroyPQExpBuffer(query);
13960 destroyPQExpBuffer(delqry);
13961 destroyPQExpBuffer(labelq);
13969 dumpRule(Archive *fout, RuleInfo *rinfo)
13971 TableInfo *tbinfo = rinfo->ruletable;
13974 PQExpBuffer delcmd;
13975 PQExpBuffer labelq;
13978 /* Skip if not to be dumped */
13979 if (!rinfo->dobj.dump || dataOnly)
13983 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13984 * we do not want to dump it as a separate object.
13986 if (!rinfo->separate)
13990 * Make sure we are in proper schema.
13992 selectSourceSchema(fout, tbinfo->dobj.namespace->dobj.name);
13994 query = createPQExpBuffer();
13995 cmd = createPQExpBuffer();
13996 delcmd = createPQExpBuffer();
13997 labelq = createPQExpBuffer();
13999 if (fout->remoteVersion >= 70300)
14001 appendPQExpBuffer(query,
14002 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
14003 rinfo->dobj.catId.oid);
14007 /* Rule name was unique before 7.3 ... */
14008 appendPQExpBuffer(query,
14009 "SELECT pg_get_ruledef('%s') AS definition",
14013 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14015 if (PQntuples(res) != 1)
14017 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
14018 rinfo->dobj.name, tbinfo->dobj.name);
14022 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
14025 * Add the command to alter the rules replication firing semantics if it
14026 * differs from the default.
14028 if (rinfo->ev_enabled != 'O')
14030 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
14031 fmtId(tbinfo->dobj.namespace->dobj.name));
14032 appendPQExpBuffer(cmd, "%s ",
14033 fmtId(tbinfo->dobj.name));
14034 switch (rinfo->ev_enabled)
14037 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
14038 fmtId(rinfo->dobj.name));
14041 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
14042 fmtId(rinfo->dobj.name));
14045 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
14046 fmtId(rinfo->dobj.name));
14052 * DROP must be fully qualified in case same name appears in pg_catalog
14054 appendPQExpBuffer(delcmd, "DROP RULE %s ",
14055 fmtId(rinfo->dobj.name));
14056 appendPQExpBuffer(delcmd, "ON %s.",
14057 fmtId(tbinfo->dobj.namespace->dobj.name));
14058 appendPQExpBuffer(delcmd, "%s;\n",
14059 fmtId(tbinfo->dobj.name));
14061 appendPQExpBuffer(labelq, "RULE %s",
14062 fmtId(rinfo->dobj.name));
14063 appendPQExpBuffer(labelq, " ON %s",
14064 fmtId(tbinfo->dobj.name));
14066 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
14068 tbinfo->dobj.namespace->dobj.name,
14070 tbinfo->rolname, false,
14071 "RULE", SECTION_POST_DATA,
14072 cmd->data, delcmd->data, NULL,
14073 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
14076 /* Dump rule comments */
14077 dumpComment(fout, labelq->data,
14078 tbinfo->dobj.namespace->dobj.name,
14080 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
14084 destroyPQExpBuffer(query);
14085 destroyPQExpBuffer(cmd);
14086 destroyPQExpBuffer(delcmd);
14087 destroyPQExpBuffer(labelq);
14091 * getExtensionMembership --- obtain extension membership data
14094 getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
14105 DumpableObject *dobj,
14108 /* Nothing to do if no extensions */
14109 if (numExtensions == 0)
14112 /* Make sure we are in proper schema */
14113 selectSourceSchema(fout, "pg_catalog");
14115 query = createPQExpBuffer();
14117 /* refclassid constraint is redundant but may speed the search */
14118 appendPQExpBuffer(query, "SELECT "
14119 "classid, objid, refclassid, refobjid "
14121 "WHERE refclassid = 'pg_extension'::regclass "
14122 "AND deptype = 'e' "
14125 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14127 ntups = PQntuples(res);
14129 i_classid = PQfnumber(res, "classid");
14130 i_objid = PQfnumber(res, "objid");
14131 i_refclassid = PQfnumber(res, "refclassid");
14132 i_refobjid = PQfnumber(res, "refobjid");
14135 * Since we ordered the SELECT by referenced ID, we can expect that
14136 * multiple entries for the same extension will appear together; this
14137 * saves on searches.
14141 for (i = 0; i < ntups; i++)
14144 CatalogId refobjId;
14146 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14147 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14148 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14149 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14151 if (refdobj == NULL ||
14152 refdobj->catId.tableoid != refobjId.tableoid ||
14153 refdobj->catId.oid != refobjId.oid)
14154 refdobj = findObjectByCatalogId(refobjId);
14157 * Failure to find objects mentioned in pg_depend is not unexpected,
14158 * since for example we don't collect info about TOAST tables.
14160 if (refdobj == NULL)
14163 fprintf(stderr, "no referenced object %u %u\n",
14164 refobjId.tableoid, refobjId.oid);
14169 dobj = findObjectByCatalogId(objId);
14174 fprintf(stderr, "no referencing object %u %u\n",
14175 objId.tableoid, objId.oid);
14180 /* Record dependency so that getDependencies needn't repeat this */
14181 addObjectDependency(dobj, refdobj->dumpId);
14183 dobj->ext_member = true;
14186 * Normally, mark the member object as not to be dumped. But in
14187 * binary upgrades, we still dump the members individually, since the
14188 * idea is to exactly reproduce the database contents rather than
14189 * replace the extension contents with something different.
14191 if (!binary_upgrade)
14192 dobj->dump = false;
14194 dobj->dump = refdobj->dump;
14200 * Now identify extension configuration tables and create TableDataInfo
14201 * objects for them, ensuring their data will be dumped even though the
14202 * tables themselves won't be.
14204 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
14205 * user data in a configuration table is treated like schema data. This
14206 * seems appropriate since system data in a config table would get
14207 * reloaded by CREATE EXTENSION.
14209 for (i = 0; i < numExtensions; i++)
14211 ExtensionInfo *curext = &(extinfo[i]);
14212 char *extconfig = curext->extconfig;
14213 char *extcondition = curext->extcondition;
14214 char **extconfigarray = NULL;
14215 char **extconditionarray = NULL;
14217 int nconditionitems;
14219 /* Tables of not-to-be-dumped extensions shouldn't be dumped */
14220 if (!curext->dobj.dump)
14223 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14224 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14225 nconfigitems == nconditionitems)
14229 for (j = 0; j < nconfigitems; j++)
14231 TableInfo *configtbl;
14233 configtbl = findTableByOid(atooid(extconfigarray[j]));
14234 if (configtbl == NULL)
14238 * Note: config tables are dumped without OIDs regardless
14239 * of the --oids setting. This is because row filtering
14240 * conditions aren't compatible with dumping OIDs.
14242 makeTableDataInfo(configtbl, false);
14243 if (configtbl->dataObj != NULL)
14245 if (strlen(extconditionarray[j]) > 0)
14246 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14250 if (extconfigarray)
14251 free(extconfigarray);
14252 if (extconditionarray)
14253 free(extconditionarray);
14256 destroyPQExpBuffer(query);
14260 * getDependencies --- obtain available dependency data
14263 getDependencies(Archive *fout)
14274 DumpableObject *dobj,
14277 /* No dependency info available before 7.3 */
14278 if (fout->remoteVersion < 70300)
14282 write_msg(NULL, "reading dependency data\n");
14284 /* Make sure we are in proper schema */
14285 selectSourceSchema(fout, "pg_catalog");
14287 query = createPQExpBuffer();
14290 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14291 * already processed by getExtensionMembership.
14293 appendPQExpBuffer(query, "SELECT "
14294 "classid, objid, refclassid, refobjid, deptype "
14296 "WHERE deptype != 'p' AND deptype != 'e' "
14299 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14301 ntups = PQntuples(res);
14303 i_classid = PQfnumber(res, "classid");
14304 i_objid = PQfnumber(res, "objid");
14305 i_refclassid = PQfnumber(res, "refclassid");
14306 i_refobjid = PQfnumber(res, "refobjid");
14307 i_deptype = PQfnumber(res, "deptype");
14310 * Since we ordered the SELECT by referencing ID, we can expect that
14311 * multiple entries for the same object will appear together; this saves
14316 for (i = 0; i < ntups; i++)
14319 CatalogId refobjId;
14322 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14323 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14324 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14325 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14326 deptype = *(PQgetvalue(res, i, i_deptype));
14328 if (dobj == NULL ||
14329 dobj->catId.tableoid != objId.tableoid ||
14330 dobj->catId.oid != objId.oid)
14331 dobj = findObjectByCatalogId(objId);
14334 * Failure to find objects mentioned in pg_depend is not unexpected,
14335 * since for example we don't collect info about TOAST tables.
14340 fprintf(stderr, "no referencing object %u %u\n",
14341 objId.tableoid, objId.oid);
14346 refdobj = findObjectByCatalogId(refobjId);
14348 if (refdobj == NULL)
14351 fprintf(stderr, "no referenced object %u %u\n",
14352 refobjId.tableoid, refobjId.oid);
14358 * Ordinarily, table rowtypes have implicit dependencies on their
14359 * tables. However, for a composite type the implicit dependency goes
14360 * the other way in pg_depend; which is the right thing for DROP but
14361 * it doesn't produce the dependency ordering we need. So in that one
14362 * case, we reverse the direction of the dependency.
14364 if (deptype == 'i' &&
14365 dobj->objType == DO_TABLE &&
14366 refdobj->objType == DO_TYPE)
14367 addObjectDependency(refdobj, dobj->dumpId);
14370 addObjectDependency(dobj, refdobj->dumpId);
14375 destroyPQExpBuffer(query);
14380 * selectSourceSchema - make the specified schema the active search path
14381 * in the source database.
14383 * NB: pg_catalog is explicitly searched after the specified schema;
14384 * so user names are only qualified if they are cross-schema references,
14385 * and system names are only qualified if they conflict with a user name
14386 * in the current schema.
14388 * Whenever the selected schema is not pg_catalog, be careful to qualify
14389 * references to system catalogs and types in our emitted commands!
14392 selectSourceSchema(Archive *fout, const char *schemaName)
14394 static char *curSchemaName = NULL;
14397 /* Not relevant if fetching from pre-7.3 DB */
14398 if (fout->remoteVersion < 70300)
14400 /* Ignore null schema names */
14401 if (schemaName == NULL || *schemaName == '\0')
14403 /* Optimize away repeated selection of same schema */
14404 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14407 query = createPQExpBuffer();
14408 appendPQExpBuffer(query, "SET search_path = %s",
14409 fmtId(schemaName));
14410 if (strcmp(schemaName, "pg_catalog") != 0)
14411 appendPQExpBuffer(query, ", pg_catalog");
14413 ExecuteSqlStatement(fout, query->data);
14415 destroyPQExpBuffer(query);
14417 free(curSchemaName);
14418 curSchemaName = pg_strdup(schemaName);
14422 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14425 * NB: in 7.3 and up the result may depend on the currently-selected
14426 * schema; this is why we don't try to cache the names.
14429 getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
14438 if ((opts & zeroAsOpaque) != 0)
14439 return pg_strdup(g_opaque_type);
14440 else if ((opts & zeroAsAny) != 0)
14441 return pg_strdup("'any'");
14442 else if ((opts & zeroAsStar) != 0)
14443 return pg_strdup("*");
14444 else if ((opts & zeroAsNone) != 0)
14445 return pg_strdup("NONE");
14448 query = createPQExpBuffer();
14449 if (fout->remoteVersion >= 70300)
14451 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14454 else if (fout->remoteVersion >= 70100)
14456 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14461 appendPQExpBuffer(query, "SELECT typname "
14463 "WHERE oid = '%u'::oid",
14467 res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14469 /* Expecting a single result only */
14470 ntups = PQntuples(res);
14473 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
14474 "query returned %d rows instead of one: %s\n",
14476 ntups, query->data);
14480 if (fout->remoteVersion >= 70100)
14482 /* already quoted */
14483 result = pg_strdup(PQgetvalue(res, 0, 0));
14487 /* may need to quote it */
14488 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14492 destroyPQExpBuffer(query);
14498 * myFormatType --- local implementation of format_type for use with 7.0.
14501 myFormatType(const char *typname, int32 typmod)
14504 bool isarray = false;
14505 PQExpBuffer buf = createPQExpBuffer();
14507 /* Handle array types */
14508 if (typname[0] == '_')
14514 /* Show lengths on bpchar and varchar */
14515 if (strcmp(typname, "bpchar") == 0)
14517 int len = (typmod - VARHDRSZ);
14519 appendPQExpBuffer(buf, "character");
14521 appendPQExpBuffer(buf, "(%d)",
14522 typmod - VARHDRSZ);
14524 else if (strcmp(typname, "varchar") == 0)
14526 appendPQExpBuffer(buf, "character varying");
14528 appendPQExpBuffer(buf, "(%d)",
14529 typmod - VARHDRSZ);
14531 else if (strcmp(typname, "numeric") == 0)
14533 appendPQExpBuffer(buf, "numeric");
14540 tmp_typmod = typmod - VARHDRSZ;
14541 precision = (tmp_typmod >> 16) & 0xffff;
14542 scale = tmp_typmod & 0xffff;
14543 appendPQExpBuffer(buf, "(%d,%d)",
14549 * char is an internal single-byte data type; Let's make sure we force it
14550 * through with quotes. - thomas 1998-12-13
14552 else if (strcmp(typname, "char") == 0)
14553 appendPQExpBuffer(buf, "\"char\"");
14555 appendPQExpBuffer(buf, "%s", fmtId(typname));
14557 /* Append array qualifier for array types */
14559 appendPQExpBuffer(buf, "[]");
14561 result = pg_strdup(buf->data);
14562 destroyPQExpBuffer(buf);
14568 * fmtQualifiedId - convert a qualified name to the proper format for
14569 * the source database.
14571 * Like fmtId, use the result before calling again.
14573 static const char *
14574 fmtQualifiedId(Archive *fout, const char *schema, const char *id)
14576 static PQExpBuffer id_return = NULL;
14578 if (id_return) /* first time through? */
14579 resetPQExpBuffer(id_return);
14581 id_return = createPQExpBuffer();
14583 /* Suppress schema name if fetching from pre-7.3 DB */
14584 if (fout->remoteVersion >= 70300 && schema && *schema)
14586 appendPQExpBuffer(id_return, "%s.",
14589 appendPQExpBuffer(id_return, "%s",
14592 return id_return->data;
14596 * Return a column list clause for the given relation.
14598 * Special case: if there are no undropped columns in the relation, return
14599 * "", not an invalid "()" column list.
14601 static const char *
14602 fmtCopyColumnList(const TableInfo *ti)
14604 static PQExpBuffer q = NULL;
14605 int numatts = ti->numatts;
14606 char **attnames = ti->attnames;
14607 bool *attisdropped = ti->attisdropped;
14611 if (q) /* first time through? */
14612 resetPQExpBuffer(q);
14614 q = createPQExpBuffer();
14616 appendPQExpBuffer(q, "(");
14618 for (i = 0; i < numatts; i++)
14620 if (attisdropped[i])
14623 appendPQExpBuffer(q, ", ");
14624 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14629 return ""; /* no undropped columns */
14631 appendPQExpBuffer(q, ")");