1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2011, 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"
61 #include "dumputils.h"
70 const char *descr; /* comment for an object */
71 Oid classoid; /* object class (catalog OID) */
72 Oid objoid; /* object OID */
73 int objsubid; /* subobject (table column #) */
78 const char *provider; /* label provider of this security label */
79 const char *label; /* security label for an object */
80 Oid classoid; /* object class (catalog OID) */
81 Oid objoid; /* object OID */
82 int objsubid; /* subobject (table column #) */
86 bool g_verbose; /* User wants verbose narration of our
88 Archive *g_fout; /* the script file */
89 PGconn *g_conn; /* the database connection */
91 /* various user-settable parameters */
95 const char *lockWaitTimeout;
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery;
100 /* obsolete as of 7.3: */
101 static Oid g_last_builtin_oid; /* value of the last builtin oid */
104 * Object inclusion/exclusion lists
106 * The string lists record the patterns given by command-line switches,
107 * which we then convert to lists of OIDs of matching objects.
109 static SimpleStringList schema_include_patterns = {NULL, NULL};
110 static SimpleOidList schema_include_oids = {NULL, NULL};
111 static SimpleStringList schema_exclude_patterns = {NULL, NULL};
112 static SimpleOidList schema_exclude_oids = {NULL, NULL};
114 static SimpleStringList table_include_patterns = {NULL, NULL};
115 static SimpleOidList table_include_oids = {NULL, NULL};
116 static SimpleStringList table_exclude_patterns = {NULL, NULL};
117 static SimpleOidList table_exclude_oids = {NULL, NULL};
119 /* default, if no "inclusion" switches appear, is to dump everything */
120 static bool include_everything = true;
122 char g_opaque_type[10]; /* name for the opaque type */
124 /* placeholders for the delimiters for comments */
125 char g_comment_start[10];
126 char g_comment_end[10];
128 static const CatalogId nilCatalogId = {0, 0};
130 /* these are to avoid passing around info for findNamespace() */
131 static NamespaceInfo *g_namespaces;
132 static int g_numNamespaces;
134 /* flags for various command-line long options */
135 static int binary_upgrade = 0;
136 static int disable_dollar_quoting = 0;
137 static int dump_inserts = 0;
138 static int column_inserts = 0;
139 static int no_security_labels = 0;
140 static int no_unlogged_table_data = 0;
141 static int serializable_deferrable = 0;
144 static void help(const char *progname);
145 static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
146 static void expand_schema_name_patterns(SimpleStringList *patterns,
147 SimpleOidList *oids);
148 static void expand_table_name_patterns(SimpleStringList *patterns,
149 SimpleOidList *oids);
150 static NamespaceInfo *findNamespace(Oid nsoid, Oid objoid);
151 static void dumpTableData(Archive *fout, TableDataInfo *tdinfo);
152 static void guessConstraintInheritance(TableInfo *tblinfo, int numTables);
153 static void dumpComment(Archive *fout, const char *target,
154 const char *namespace, const char *owner,
155 CatalogId catalogId, int subid, DumpId dumpId);
156 static int findComments(Archive *fout, Oid classoid, Oid objoid,
157 CommentItem **items);
158 static int collectComments(Archive *fout, CommentItem **items);
159 static void dumpSecLabel(Archive *fout, const char *target,
160 const char *namespace, const char *owner,
161 CatalogId catalogId, int subid, DumpId dumpId);
162 static int findSecLabels(Archive *fout, Oid classoid, Oid objoid,
163 SecLabelItem **items);
164 static int collectSecLabels(Archive *fout, SecLabelItem **items);
165 static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
166 static void dumpNamespace(Archive *fout, NamespaceInfo *nspinfo);
167 static void dumpExtension(Archive *fout, ExtensionInfo *extinfo);
168 static void dumpType(Archive *fout, TypeInfo *tyinfo);
169 static void dumpBaseType(Archive *fout, TypeInfo *tyinfo);
170 static void dumpEnumType(Archive *fout, TypeInfo *tyinfo);
171 static void dumpRangeType(Archive *fout, TypeInfo *tyinfo);
172 static void dumpDomain(Archive *fout, TypeInfo *tyinfo);
173 static void dumpCompositeType(Archive *fout, TypeInfo *tyinfo);
174 static void dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo);
175 static void dumpShellType(Archive *fout, ShellTypeInfo *stinfo);
176 static void dumpProcLang(Archive *fout, ProcLangInfo *plang);
177 static void dumpFunc(Archive *fout, FuncInfo *finfo);
178 static void dumpCast(Archive *fout, CastInfo *cast);
179 static void dumpOpr(Archive *fout, OprInfo *oprinfo);
180 static void dumpOpclass(Archive *fout, OpclassInfo *opcinfo);
181 static void dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo);
182 static void dumpCollation(Archive *fout, CollInfo *convinfo);
183 static void dumpConversion(Archive *fout, ConvInfo *convinfo);
184 static void dumpRule(Archive *fout, RuleInfo *rinfo);
185 static void dumpAgg(Archive *fout, AggInfo *agginfo);
186 static void dumpTrigger(Archive *fout, TriggerInfo *tginfo);
187 static void dumpTable(Archive *fout, TableInfo *tbinfo);
188 static void dumpTableSchema(Archive *fout, TableInfo *tbinfo);
189 static void dumpAttrDef(Archive *fout, AttrDefInfo *adinfo);
190 static void dumpSequence(Archive *fout, TableInfo *tbinfo);
191 static void dumpIndex(Archive *fout, IndxInfo *indxinfo);
192 static void dumpConstraint(Archive *fout, ConstraintInfo *coninfo);
193 static void dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo);
194 static void dumpTSParser(Archive *fout, TSParserInfo *prsinfo);
195 static void dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo);
196 static void dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo);
197 static void dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo);
198 static void dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo);
199 static void dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo);
200 static void dumpUserMappings(Archive *fout,
201 const char *servername, const char *namespace,
202 const char *owner, CatalogId catalogId, DumpId dumpId);
203 static void dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo);
205 static void dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
206 const char *type, const char *name, const char *subname,
207 const char *tag, const char *nspname, const char *owner,
210 static void getDependencies(void);
211 static void getDomainConstraints(TypeInfo *tyinfo);
212 static void getTableData(TableInfo *tblinfo, int numTables, bool oids);
213 static void makeTableDataInfo(TableInfo *tbinfo, bool oids);
214 static void getTableDataFKConstraints(void);
215 static char *format_function_arguments(FuncInfo *finfo, char *funcargs);
216 static char *format_function_arguments_old(FuncInfo *finfo, int nallargs,
220 static char *format_function_signature(FuncInfo *finfo, bool honor_quotes);
221 static const char *convertRegProcReference(const char *proc);
222 static const char *convertOperatorReference(const char *opr);
223 static const char *convertTSFunction(Oid funcOid);
224 static Oid findLastBuiltinOid_V71(const char *);
225 static Oid findLastBuiltinOid_V70(void);
226 static void selectSourceSchema(const char *schemaName);
227 static char *getFormattedTypeName(Oid oid, OidOptions opts);
228 static char *myFormatType(const char *typname, int32 typmod);
229 static const char *fmtQualifiedId(const char *schema, const char *id);
230 static void getBlobs(Archive *AH);
231 static void dumpBlob(Archive *AH, BlobInfo *binfo);
232 static int dumpBlobs(Archive *AH, void *arg);
233 static void dumpDatabase(Archive *AH);
234 static void dumpEncoding(Archive *AH);
235 static void dumpStdStrings(Archive *AH);
236 static void binary_upgrade_set_type_oids_by_type_oid(
237 PQExpBuffer upgrade_buffer, Oid pg_type_oid);
238 static bool binary_upgrade_set_type_oids_by_rel_oid(
239 PQExpBuffer upgrade_buffer, Oid pg_rel_oid);
240 static void binary_upgrade_set_pg_class_oids(PQExpBuffer upgrade_buffer,
241 Oid pg_class_oid, bool is_index);
242 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
243 DumpableObject *dobj,
244 const char *objlabel);
245 static const char *getAttrName(int attrnum, TableInfo *tblInfo);
246 static const char *fmtCopyColumnList(const TableInfo *ti);
247 static void do_sql_command(PGconn *conn, const char *query);
248 static void check_sql_result(PGresult *res, PGconn *conn, const char *query,
249 ExecStatusType expected);
253 main(int argc, char **argv)
256 const char *filename = NULL;
257 const char *format = "p";
258 const char *dbname = NULL;
259 const char *pghost = NULL;
260 const char *pgport = NULL;
261 const char *username = NULL;
262 const char *dumpencoding = NULL;
263 const char *std_strings;
267 DumpableObject **dobjs;
270 enum trivalue prompt_password = TRI_DEFAULT;
271 int compressLevel = -1;
274 int outputCreateDB = 0;
275 bool outputBlobs = false;
276 int outputNoOwner = 0;
277 char *outputSuperuser = NULL;
278 char *use_role = NULL;
281 RestoreOptions *ropt;
282 ArchiveFormat archiveFormat = archUnknown;
283 ArchiveMode archiveMode;
285 static int disable_triggers = 0;
286 static int outputNoTablespaces = 0;
287 static int use_setsessauth = 0;
289 static struct option long_options[] = {
290 {"data-only", no_argument, NULL, 'a'},
291 {"blobs", no_argument, NULL, 'b'},
292 {"clean", no_argument, NULL, 'c'},
293 {"create", no_argument, NULL, 'C'},
294 {"file", required_argument, NULL, 'f'},
295 {"format", required_argument, NULL, 'F'},
296 {"host", required_argument, NULL, 'h'},
297 {"ignore-version", no_argument, NULL, 'i'},
298 {"no-reconnect", no_argument, NULL, 'R'},
299 {"oids", no_argument, NULL, 'o'},
300 {"no-owner", no_argument, NULL, 'O'},
301 {"port", required_argument, NULL, 'p'},
302 {"schema", required_argument, NULL, 'n'},
303 {"exclude-schema", required_argument, NULL, 'N'},
304 {"schema-only", no_argument, NULL, 's'},
305 {"superuser", required_argument, NULL, 'S'},
306 {"table", required_argument, NULL, 't'},
307 {"exclude-table", required_argument, NULL, 'T'},
308 {"no-password", no_argument, NULL, 'w'},
309 {"password", no_argument, NULL, 'W'},
310 {"username", required_argument, NULL, 'U'},
311 {"verbose", no_argument, NULL, 'v'},
312 {"no-privileges", no_argument, NULL, 'x'},
313 {"no-acl", no_argument, NULL, 'x'},
314 {"compress", required_argument, NULL, 'Z'},
315 {"encoding", required_argument, NULL, 'E'},
316 {"help", no_argument, NULL, '?'},
317 {"version", no_argument, NULL, 'V'},
320 * the following options don't have an equivalent short option letter
322 {"attribute-inserts", no_argument, &column_inserts, 1},
323 {"binary-upgrade", no_argument, &binary_upgrade, 1},
324 {"column-inserts", no_argument, &column_inserts, 1},
325 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
326 {"disable-triggers", no_argument, &disable_triggers, 1},
327 {"inserts", no_argument, &dump_inserts, 1},
328 {"lock-wait-timeout", required_argument, NULL, 2},
329 {"no-tablespaces", no_argument, &outputNoTablespaces, 1},
330 {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
331 {"role", required_argument, NULL, 3},
332 {"serializable-deferrable", no_argument, &serializable_deferrable, 1},
333 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
334 {"no-security-labels", no_argument, &no_security_labels, 1},
335 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
340 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
344 strcpy(g_comment_start, "-- ");
345 g_comment_end[0] = '\0';
346 strcpy(g_opaque_type, "opaque");
348 dataOnly = schemaOnly = false;
349 lockWaitTimeout = NULL;
351 progname = get_progname(argv[0]);
353 /* Set default options based on progname */
354 if (strcmp(progname, "pg_backup") == 0)
359 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
364 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
366 puts("pg_dump (PostgreSQL) " PG_VERSION);
371 while ((c = getopt_long(argc, argv, "abcCE:f:F:h:in:N:oOp:RsS:t:T:U:vwWxZ:",
372 long_options, &optindex)) != -1)
376 case 'a': /* Dump data only */
380 case 'b': /* Dump blobs */
384 case 'c': /* clean (i.e., drop) schema prior to create */
388 case 'C': /* Create DB */
392 case 'E': /* Dump encoding */
393 dumpencoding = optarg;
404 case 'h': /* server host */
409 /* ignored, deprecated option */
412 case 'n': /* include schema(s) */
413 simple_string_list_append(&schema_include_patterns, optarg);
414 include_everything = false;
417 case 'N': /* exclude schema(s) */
418 simple_string_list_append(&schema_exclude_patterns, optarg);
421 case 'o': /* Dump oids */
425 case 'O': /* Don't reconnect to match owner */
429 case 'p': /* server port */
434 /* no-op, still accepted for backwards compatibility */
437 case 's': /* dump schema only */
441 case 'S': /* Username for superuser in plain text output */
442 outputSuperuser = pg_strdup(optarg);
445 case 't': /* include table(s) */
446 simple_string_list_append(&table_include_patterns, optarg);
447 include_everything = false;
450 case 'T': /* exclude table(s) */
451 simple_string_list_append(&table_exclude_patterns, optarg);
458 case 'v': /* verbose */
463 prompt_password = TRI_NO;
467 prompt_password = TRI_YES;
470 case 'x': /* skip ACL dump */
474 case 'Z': /* Compression Level */
475 compressLevel = atoi(optarg);
479 /* This covers the long options. */
482 case 2: /* lock-wait-timeout */
483 lockWaitTimeout = optarg;
486 case 3: /* SET ROLE */
491 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
496 /* Get database name from command line */
498 dbname = argv[optind++];
500 /* Complain if any arguments remain */
503 fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
504 progname, argv[optind]);
505 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
510 /* --column-inserts implies --inserts */
514 if (dataOnly && schemaOnly)
516 write_msg(NULL, "options -s/--schema-only and -a/--data-only cannot be used together\n");
520 if (dataOnly && outputClean)
522 write_msg(NULL, "options -c/--clean and -a/--data-only cannot be used together\n");
526 if (dump_inserts && oids)
528 write_msg(NULL, "options --inserts/--column-inserts and -o/--oids cannot be used together\n");
529 write_msg(NULL, "(The INSERT command cannot set OIDs.)\n");
533 /* Identify archive format to emit */
534 archiveFormat = parseArchiveFormat(format, &archiveMode);
536 /* archiveFormat specific setup */
537 if (archiveFormat == archNull)
540 /* Custom and directory formats are compressed by default, others not */
541 if (compressLevel == -1)
543 if (archiveFormat == archCustom || archiveFormat == archDirectory)
544 compressLevel = Z_DEFAULT_COMPRESSION;
549 /* Open the output file */
550 g_fout = CreateArchive(filename, archiveFormat, compressLevel, archiveMode);
554 write_msg(NULL, "could not open output file \"%s\" for writing\n", filename);
558 /* Let the archiver know how noisy to be */
559 g_fout->verbose = g_verbose;
561 my_version = parse_version(PG_VERSION);
564 write_msg(NULL, "could not parse version string \"%s\"\n", PG_VERSION);
569 * We allow the server to be back to 7.0, and up to any minor release of
570 * our own major version. (See also version check in pg_dumpall.c.)
572 g_fout->minRemoteVersion = 70000;
573 g_fout->maxRemoteVersion = (my_version / 100) * 100 + 99;
576 * Open the database using the Archiver, so it knows about it. Errors mean
579 g_conn = ConnectDatabase(g_fout, dbname, pghost, pgport,
580 username, prompt_password);
582 /* Set the client encoding if requested */
585 if (PQsetClientEncoding(g_conn, dumpencoding) < 0)
587 write_msg(NULL, "invalid client encoding \"%s\" specified\n",
594 * Get the active encoding and the standard_conforming_strings setting, so
595 * we know how to escape strings.
597 g_fout->encoding = PQclientEncoding(g_conn);
599 std_strings = PQparameterStatus(g_conn, "standard_conforming_strings");
600 g_fout->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
602 /* Set the role if requested */
603 if (use_role && g_fout->remoteVersion >= 80100)
605 PQExpBuffer query = createPQExpBuffer();
607 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
608 do_sql_command(g_conn, query->data);
609 destroyPQExpBuffer(query);
612 /* Set the datestyle to ISO to ensure the dump's portability */
613 do_sql_command(g_conn, "SET DATESTYLE = ISO");
615 /* Likewise, avoid using sql_standard intervalstyle */
616 if (g_fout->remoteVersion >= 80400)
617 do_sql_command(g_conn, "SET INTERVALSTYLE = POSTGRES");
620 * If supported, set extra_float_digits so that we can dump float data
621 * exactly (given correctly implemented float I/O code, anyway)
623 if (g_fout->remoteVersion >= 90000)
624 do_sql_command(g_conn, "SET extra_float_digits TO 3");
625 else if (g_fout->remoteVersion >= 70400)
626 do_sql_command(g_conn, "SET extra_float_digits TO 2");
629 * If synchronized scanning is supported, disable it, to prevent
630 * unpredictable changes in row ordering across a dump and reload.
632 if (g_fout->remoteVersion >= 80300)
633 do_sql_command(g_conn, "SET synchronize_seqscans TO off");
636 * Disable timeouts if supported.
638 if (g_fout->remoteVersion >= 70300)
639 do_sql_command(g_conn, "SET statement_timeout = 0");
642 * Quote all identifiers, if requested.
644 if (quote_all_identifiers && g_fout->remoteVersion >= 90100)
645 do_sql_command(g_conn, "SET quote_all_identifiers = true");
648 * Disable security label support if server version < v9.1.x (prevents
649 * access to nonexistent pg_seclabel catalog)
651 if (g_fout->remoteVersion < 90100)
652 no_security_labels = 1;
655 * Start transaction-snapshot mode transaction to dump consistent data.
657 do_sql_command(g_conn, "BEGIN");
658 if (g_fout->remoteVersion >= 90100)
660 if (serializable_deferrable)
661 do_sql_command(g_conn,
662 "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, "
663 "READ ONLY, DEFERRABLE");
665 do_sql_command(g_conn,
666 "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ");
669 do_sql_command(g_conn, "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");
671 /* Select the appropriate subquery to convert user IDs to names */
672 if (g_fout->remoteVersion >= 80100)
673 username_subquery = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
674 else if (g_fout->remoteVersion >= 70300)
675 username_subquery = "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
677 username_subquery = "SELECT usename FROM pg_user WHERE usesysid =";
679 /* Find the last built-in OID, if needed */
680 if (g_fout->remoteVersion < 70300)
682 if (g_fout->remoteVersion >= 70100)
683 g_last_builtin_oid = findLastBuiltinOid_V71(PQdb(g_conn));
685 g_last_builtin_oid = findLastBuiltinOid_V70();
687 write_msg(NULL, "last built-in OID is %u\n", g_last_builtin_oid);
690 /* Expand schema selection patterns into OID lists */
691 if (schema_include_patterns.head != NULL)
693 expand_schema_name_patterns(&schema_include_patterns,
694 &schema_include_oids);
695 if (schema_include_oids.head == NULL)
697 write_msg(NULL, "No matching schemas were found\n");
701 expand_schema_name_patterns(&schema_exclude_patterns,
702 &schema_exclude_oids);
703 /* non-matching exclusion patterns aren't an error */
705 /* Expand table selection patterns into OID lists */
706 if (table_include_patterns.head != NULL)
708 expand_table_name_patterns(&table_include_patterns,
709 &table_include_oids);
710 if (table_include_oids.head == NULL)
712 write_msg(NULL, "No matching tables were found\n");
716 expand_table_name_patterns(&table_exclude_patterns,
717 &table_exclude_oids);
718 /* non-matching exclusion patterns aren't an error */
721 * Dumping blobs is now default unless we saw an inclusion switch or -s
722 * ... but even if we did see one of these, -b turns it back on.
724 if (include_everything && !schemaOnly)
728 * Now scan the database and create DumpableObject structs for all the
729 * objects we intend to dump.
731 tblinfo = getSchemaData(&numTables);
733 if (g_fout->remoteVersion < 80400)
734 guessConstraintInheritance(tblinfo, numTables);
738 getTableData(tblinfo, numTables, oids);
740 getTableDataFKConstraints();
747 * Collect dependency data to assist in ordering the objects.
752 * Sort the objects into a safe dump order (no forward references).
754 * In 7.3 or later, we can rely on dependency information to help us
755 * determine a safe order, so the initial sort is mostly for cosmetic
756 * purposes: we sort by name to ensure that logically identical schemas
757 * will dump identically. Before 7.3 we don't have dependencies and we
758 * use OID ordering as an (unreliable) guide to creation order.
760 getDumpableObjects(&dobjs, &numObjs);
762 if (g_fout->remoteVersion >= 70300)
763 sortDumpableObjectsByTypeName(dobjs, numObjs);
765 sortDumpableObjectsByTypeOid(dobjs, numObjs);
767 sortDumpableObjects(dobjs, numObjs);
770 * Create archive TOC entries for all the objects to be dumped, in a safe
774 /* First the special ENCODING and STDSTRINGS entries. */
775 dumpEncoding(g_fout);
776 dumpStdStrings(g_fout);
778 /* The database item is always next, unless we don't want it at all */
779 if (include_everything && !dataOnly)
780 dumpDatabase(g_fout);
782 /* Now the rearrangeable objects. */
783 for (i = 0; i < numObjs; i++)
784 dumpDumpableObject(g_fout, dobjs[i]);
787 * And finally we can do the actual output.
791 ropt = NewRestoreOptions();
792 ropt->filename = (char *) filename;
793 ropt->dropSchema = outputClean;
794 ropt->aclsSkip = aclsSkip;
795 ropt->superuser = outputSuperuser;
796 ropt->createDB = outputCreateDB;
797 ropt->noOwner = outputNoOwner;
798 ropt->noTablespace = outputNoTablespaces;
799 ropt->disable_triggers = disable_triggers;
800 ropt->use_setsessauth = use_setsessauth;
801 ropt->dataOnly = dataOnly;
803 if (compressLevel == -1)
804 ropt->compression = 0;
806 ropt->compression = compressLevel;
808 ropt->suppressDumpWarnings = true; /* We've already shown them */
810 RestoreArchive(g_fout, ropt);
813 CloseArchive(g_fout);
822 help(const char *progname)
824 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
825 printf(_("Usage:\n"));
826 printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
828 printf(_("\nGeneral options:\n"));
829 printf(_(" -f, --file=FILENAME output file or directory name\n"));
830 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar, plain text)\n"));
831 printf(_(" -v, --verbose verbose mode\n"));
832 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
833 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
834 printf(_(" --help show this help, then exit\n"));
835 printf(_(" --version output version information, then exit\n"));
837 printf(_("\nOptions controlling the output content:\n"));
838 printf(_(" -a, --data-only dump only the data, not the schema\n"));
839 printf(_(" -b, --blobs include large objects in dump\n"));
840 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
841 printf(_(" -C, --create include commands to create database in dump\n"));
842 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
843 printf(_(" -n, --schema=SCHEMA dump the named schema(s) only\n"));
844 printf(_(" -N, --exclude-schema=SCHEMA do NOT dump the named schema(s)\n"));
845 printf(_(" -o, --oids include OIDs in dump\n"));
846 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
847 " plain-text format\n"));
848 printf(_(" -s, --schema-only dump only the schema, no data\n"));
849 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
850 printf(_(" -t, --table=TABLE dump the named table(s) only\n"));
851 printf(_(" -T, --exclude-table=TABLE do NOT dump the named table(s)\n"));
852 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
853 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
854 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
855 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
856 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
857 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
858 printf(_(" --no-security-labels do not dump security label assignments\n"));
859 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
860 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
861 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
862 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
863 printf(_(" --use-set-session-authorization\n"
864 " use SET SESSION AUTHORIZATION commands instead of\n"
865 " ALTER OWNER commands to set ownership\n"));
867 printf(_("\nConnection options:\n"));
868 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
869 printf(_(" -p, --port=PORT database server port number\n"));
870 printf(_(" -U, --username=NAME connect as specified database user\n"));
871 printf(_(" -w, --no-password never prompt for password\n"));
872 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
873 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
875 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
876 "variable value is used.\n\n"));
877 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
885 write_msg(NULL, "*** aborted because of error\n");
890 parseArchiveFormat(const char *format, ArchiveMode *mode)
892 ArchiveFormat archiveFormat;
894 *mode = archModeWrite;
896 if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
898 /* This is used by pg_dumpall, and is not documented */
899 archiveFormat = archNull;
900 *mode = archModeAppend;
902 else if (pg_strcasecmp(format, "c") == 0)
903 archiveFormat = archCustom;
904 else if (pg_strcasecmp(format, "custom") == 0)
905 archiveFormat = archCustom;
906 else if (pg_strcasecmp(format, "d") == 0)
907 archiveFormat = archDirectory;
908 else if (pg_strcasecmp(format, "directory") == 0)
909 archiveFormat = archDirectory;
910 else if (pg_strcasecmp(format, "f") == 0 || pg_strcasecmp(format, "file") == 0)
913 * Dump files into the current directory; for demonstration only, not
916 archiveFormat = archFiles;
917 else if (pg_strcasecmp(format, "p") == 0)
918 archiveFormat = archNull;
919 else if (pg_strcasecmp(format, "plain") == 0)
920 archiveFormat = archNull;
921 else if (pg_strcasecmp(format, "t") == 0)
922 archiveFormat = archTar;
923 else if (pg_strcasecmp(format, "tar") == 0)
924 archiveFormat = archTar;
927 write_msg(NULL, "invalid output format \"%s\" specified\n", format);
930 return archiveFormat;
934 * Find the OIDs of all schemas matching the given list of patterns,
935 * and append them to the given OID list.
938 expand_schema_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
942 SimpleStringListCell *cell;
945 if (patterns->head == NULL)
946 return; /* nothing to do */
948 if (g_fout->remoteVersion < 70300)
950 write_msg(NULL, "server version must be at least 7.3 to use schema selection switches\n");
954 query = createPQExpBuffer();
957 * We use UNION ALL rather than UNION; this might sometimes result in
958 * duplicate entries in the OID list, but we don't care.
961 for (cell = patterns->head; cell; cell = cell->next)
963 if (cell != patterns->head)
964 appendPQExpBuffer(query, "UNION ALL\n");
965 appendPQExpBuffer(query,
966 "SELECT oid FROM pg_catalog.pg_namespace n\n");
967 processSQLNamePattern(g_conn, query, cell->val, false, false,
968 NULL, "n.nspname", NULL,
972 res = PQexec(g_conn, query->data);
973 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
975 for (i = 0; i < PQntuples(res); i++)
977 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
981 destroyPQExpBuffer(query);
985 * Find the OIDs of all tables matching the given list of patterns,
986 * and append them to the given OID list.
989 expand_table_name_patterns(SimpleStringList *patterns, SimpleOidList *oids)
993 SimpleStringListCell *cell;
996 if (patterns->head == NULL)
997 return; /* nothing to do */
999 query = createPQExpBuffer();
1002 * We use UNION ALL rather than UNION; this might sometimes result in
1003 * duplicate entries in the OID list, but we don't care.
1006 for (cell = patterns->head; cell; cell = cell->next)
1008 if (cell != patterns->head)
1009 appendPQExpBuffer(query, "UNION ALL\n");
1010 appendPQExpBuffer(query,
1012 "\nFROM pg_catalog.pg_class c"
1013 "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
1014 "\nWHERE c.relkind in ('%c', '%c', '%c', '%c')\n",
1015 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1016 RELKIND_FOREIGN_TABLE);
1017 processSQLNamePattern(g_conn, query, cell->val, true, false,
1018 "n.nspname", "c.relname", NULL,
1019 "pg_catalog.pg_table_is_visible(c.oid)");
1022 res = PQexec(g_conn, query->data);
1023 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
1025 for (i = 0; i < PQntuples(res); i++)
1027 simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1031 destroyPQExpBuffer(query);
1035 * selectDumpableNamespace: policy-setting subroutine
1036 * Mark a namespace as to be dumped or not
1039 selectDumpableNamespace(NamespaceInfo *nsinfo)
1042 * If specific tables are being dumped, do not dump any complete
1043 * namespaces. If specific namespaces are being dumped, dump just those
1044 * namespaces. Otherwise, dump all non-system namespaces.
1046 if (table_include_oids.head != NULL)
1047 nsinfo->dobj.dump = false;
1048 else if (schema_include_oids.head != NULL)
1049 nsinfo->dobj.dump = simple_oid_list_member(&schema_include_oids,
1050 nsinfo->dobj.catId.oid);
1051 else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1052 strcmp(nsinfo->dobj.name, "information_schema") == 0)
1053 nsinfo->dobj.dump = false;
1055 nsinfo->dobj.dump = true;
1058 * In any case, a namespace can be excluded by an exclusion switch
1060 if (nsinfo->dobj.dump &&
1061 simple_oid_list_member(&schema_exclude_oids,
1062 nsinfo->dobj.catId.oid))
1063 nsinfo->dobj.dump = false;
1067 * selectDumpableTable: policy-setting subroutine
1068 * Mark a table as to be dumped or not
1071 selectDumpableTable(TableInfo *tbinfo)
1074 * If specific tables are being dumped, dump just those tables; else, dump
1075 * according to the parent namespace's dump flag.
1077 if (table_include_oids.head != NULL)
1078 tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1079 tbinfo->dobj.catId.oid);
1081 tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump;
1084 * In any case, a table can be excluded by an exclusion switch
1086 if (tbinfo->dobj.dump &&
1087 simple_oid_list_member(&table_exclude_oids,
1088 tbinfo->dobj.catId.oid))
1089 tbinfo->dobj.dump = false;
1093 * selectDumpableType: policy-setting subroutine
1094 * Mark a type as to be dumped or not
1096 * If it's a table's rowtype or an autogenerated array type, we also apply a
1097 * special type code to facilitate sorting into the desired order. (We don't
1098 * want to consider those to be ordinary types because that would bring tables
1099 * up into the datatype part of the dump order.) We still set the object's
1100 * dump flag; that's not going to cause the dummy type to be dumped, but we
1101 * need it so that casts involving such types will be dumped correctly -- see
1102 * dumpCast. This means the flag should be set the same as for the underlying
1103 * object (the table or base type).
1106 selectDumpableType(TypeInfo *tyinfo)
1108 /* skip complex types, except for standalone composite types */
1109 if (OidIsValid(tyinfo->typrelid) &&
1110 tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1112 TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1114 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1115 if (tytable != NULL)
1116 tyinfo->dobj.dump = tytable->dobj.dump;
1118 tyinfo->dobj.dump = false;
1122 /* skip auto-generated array types */
1123 if (tyinfo->isArray)
1125 tyinfo->dobj.objType = DO_DUMMY_TYPE;
1127 * Fall through to set the dump flag; we assume that the subsequent
1128 * rules will do the same thing as they would for the array's base
1129 * type. (We cannot reliably look up the base type here, since
1130 * getTypes may not have processed it yet.)
1134 /* dump only types in dumpable namespaces */
1135 if (!tyinfo->dobj.namespace->dobj.dump)
1136 tyinfo->dobj.dump = false;
1138 /* skip undefined placeholder types */
1139 else if (!tyinfo->isDefined)
1140 tyinfo->dobj.dump = false;
1143 tyinfo->dobj.dump = true;
1147 * selectDumpableDefaultACL: policy-setting subroutine
1148 * Mark a default ACL as to be dumped or not
1150 * For per-schema default ACLs, dump if the schema is to be dumped.
1151 * Otherwise dump if we are dumping "everything". Note that dataOnly
1152 * and aclsSkip are checked separately.
1155 selectDumpableDefaultACL(DefaultACLInfo *dinfo)
1157 if (dinfo->dobj.namespace)
1158 dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump;
1160 dinfo->dobj.dump = include_everything;
1164 * selectDumpableExtension: policy-setting subroutine
1165 * Mark an extension as to be dumped or not
1167 * Normally, we dump all extensions, or none of them if include_everything
1168 * is false (i.e., a --schema or --table switch was given). However, in
1169 * binary-upgrade mode it's necessary to skip built-in extensions, since we
1170 * assume those will already be installed in the target database. We identify
1171 * such extensions by their having OIDs in the range reserved for initdb.
1174 selectDumpableExtension(ExtensionInfo *extinfo)
1176 if (binary_upgrade && extinfo->dobj.catId.oid < (Oid) FirstNormalObjectId)
1177 extinfo->dobj.dump = false;
1179 extinfo->dobj.dump = include_everything;
1183 * selectDumpableObject: policy-setting subroutine
1184 * Mark a generic dumpable object as to be dumped or not
1186 * Use this only for object types without a special-case routine above.
1189 selectDumpableObject(DumpableObject *dobj)
1192 * Default policy is to dump if parent namespace is dumpable, or always
1193 * for non-namespace-associated items.
1195 if (dobj->namespace)
1196 dobj->dump = dobj->namespace->dobj.dump;
1202 * Dump a table's contents for loading using the COPY command
1203 * - this routine is called by the Archiver when it wants the table
1208 dumpTableData_copy(Archive *fout, void *dcontext)
1210 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1211 TableInfo *tbinfo = tdinfo->tdtable;
1212 const char *classname = tbinfo->dobj.name;
1213 const bool hasoids = tbinfo->hasoids;
1214 const bool oids = tdinfo->oids;
1215 PQExpBuffer q = createPQExpBuffer();
1219 const char *column_list;
1222 write_msg(NULL, "dumping contents of table %s\n", classname);
1225 * Make sure we are in proper schema. We will qualify the table name
1226 * below anyway (in case its name conflicts with a pg_catalog table); but
1227 * this ensures reproducible results in case the table contains regproc,
1228 * regclass, etc columns.
1230 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1233 * If possible, specify the column list explicitly so that we have no
1234 * possibility of retrieving data in the wrong column order. (The default
1235 * column ordering of COPY will not be what we want in certain corner
1236 * cases involving ADD COLUMN and inheritance.)
1238 if (g_fout->remoteVersion >= 70300)
1239 column_list = fmtCopyColumnList(tbinfo);
1241 column_list = ""; /* can't select columns in COPY */
1243 if (oids && hasoids)
1245 appendPQExpBuffer(q, "COPY %s %s WITH OIDS TO stdout;",
1246 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1250 else if (tdinfo->filtercond)
1252 /* Note: this syntax is only supported in 8.2 and up */
1253 appendPQExpBufferStr(q, "COPY (SELECT ");
1254 /* klugery to get rid of parens in column list */
1255 if (strlen(column_list) > 2)
1257 appendPQExpBufferStr(q, column_list + 1);
1258 q->data[q->len - 1] = ' ';
1261 appendPQExpBufferStr(q, "* ");
1262 appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
1263 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1265 tdinfo->filtercond);
1269 appendPQExpBuffer(q, "COPY %s %s TO stdout;",
1270 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1274 res = PQexec(g_conn, q->data);
1275 check_sql_result(res, g_conn, q->data, PGRES_COPY_OUT);
1280 ret = PQgetCopyData(g_conn, ©buf, 0);
1283 break; /* done or error */
1287 WriteData(fout, copybuf, ret);
1294 * There was considerable discussion in late July, 2000 regarding
1295 * slowing down pg_dump when backing up large tables. Users with both
1296 * slow & fast (multi-processor) machines experienced performance
1297 * degradation when doing a backup.
1299 * Initial attempts based on sleeping for a number of ms for each ms
1300 * of work were deemed too complex, then a simple 'sleep in each loop'
1301 * implementation was suggested. The latter failed because the loop
1302 * was too tight. Finally, the following was implemented:
1304 * If throttle is non-zero, then
1305 * See how long since the last sleep.
1306 * Work out how long to sleep (based on ratio).
1307 * If sleep is more than 100ms, then
1313 * where the throttle value was the number of ms to sleep per ms of
1314 * work. The calculation was done in each loop.
1316 * Most of the hard work is done in the backend, and this solution
1317 * still did not work particularly well: on slow machines, the ratio
1318 * was 50:1, and on medium paced machines, 1:1, and on fast
1319 * multi-processor machines, it had little or no effect, for reasons
1320 * that were unclear.
1322 * Further discussion ensued, and the proposal was dropped.
1324 * For those people who want this feature, it can be implemented using
1325 * gettimeofday in each loop, calculating the time since last sleep,
1326 * multiplying that by the sleep ratio, then if the result is more
1327 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1328 * function to sleep for a subsecond period ie.
1330 * select(0, NULL, NULL, NULL, &tvi);
1332 * This will return after the interval specified in the structure tvi.
1333 * Finally, call gettimeofday again to save the 'last sleep time'.
1337 archprintf(fout, "\\.\n\n\n");
1341 /* copy data transfer failed */
1342 write_msg(NULL, "Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.\n", classname);
1343 write_msg(NULL, "Error message from server: %s", PQerrorMessage(g_conn));
1344 write_msg(NULL, "The command was: %s\n", q->data);
1348 /* Check command status and return to normal libpq state */
1349 res = PQgetResult(g_conn);
1350 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1353 destroyPQExpBuffer(q);
1358 dumpTableData_insert(Archive *fout, void *dcontext)
1360 TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
1361 TableInfo *tbinfo = tdinfo->tdtable;
1362 const char *classname = tbinfo->dobj.name;
1363 PQExpBuffer q = createPQExpBuffer();
1370 * Make sure we are in proper schema. We will qualify the table name
1371 * below anyway (in case its name conflicts with a pg_catalog table); but
1372 * this ensures reproducible results in case the table contains regproc,
1373 * regclass, etc columns.
1375 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
1377 if (fout->remoteVersion >= 70100)
1379 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1380 "SELECT * FROM ONLY %s",
1381 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1386 appendPQExpBuffer(q, "DECLARE _pg_dump_cursor CURSOR FOR "
1388 fmtQualifiedId(tbinfo->dobj.namespace->dobj.name,
1391 if (tdinfo->filtercond)
1392 appendPQExpBuffer(q, " %s", tdinfo->filtercond);
1394 res = PQexec(g_conn, q->data);
1395 check_sql_result(res, g_conn, q->data, PGRES_COMMAND_OK);
1401 res = PQexec(g_conn, "FETCH 100 FROM _pg_dump_cursor");
1402 check_sql_result(res, g_conn, "FETCH 100 FROM _pg_dump_cursor",
1404 nfields = PQnfields(res);
1405 for (tuple = 0; tuple < PQntuples(res); tuple++)
1407 archprintf(fout, "INSERT INTO %s ", fmtId(classname));
1410 /* corner case for zero-column table */
1411 archprintf(fout, "DEFAULT VALUES;\n");
1416 resetPQExpBuffer(q);
1417 appendPQExpBuffer(q, "(");
1418 for (field = 0; field < nfields; field++)
1421 appendPQExpBuffer(q, ", ");
1422 appendPQExpBufferStr(q, fmtId(PQfname(res, field)));
1424 appendPQExpBuffer(q, ") ");
1425 archputs(q->data, fout);
1427 archprintf(fout, "VALUES (");
1428 for (field = 0; field < nfields; field++)
1431 archprintf(fout, ", ");
1432 if (PQgetisnull(res, tuple, field))
1434 archprintf(fout, "NULL");
1438 /* XXX This code is partially duplicated in ruleutils.c */
1439 switch (PQftype(res, field))
1450 * These types are printed without quotes unless
1451 * they contain values that aren't accepted by the
1452 * scanner unquoted (e.g., 'NaN'). Note that
1453 * strtod() and friends might accept NaN, so we
1454 * can't use that to test.
1456 * In reality we only need to defend against
1457 * infinity and NaN, so we need not get too crazy
1458 * about pattern matching here.
1460 const char *s = PQgetvalue(res, tuple, field);
1462 if (strspn(s, "0123456789 +-eE.") == strlen(s))
1463 archprintf(fout, "%s", s);
1465 archprintf(fout, "'%s'", s);
1471 archprintf(fout, "B'%s'",
1472 PQgetvalue(res, tuple, field));
1476 if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
1477 archprintf(fout, "true");
1479 archprintf(fout, "false");
1483 /* All other types are printed as string literals. */
1484 resetPQExpBuffer(q);
1485 appendStringLiteralAH(q,
1486 PQgetvalue(res, tuple, field),
1488 archputs(q->data, fout);
1492 archprintf(fout, ");\n");
1494 } while (PQntuples(res) > 0);
1498 archprintf(fout, "\n\n");
1500 do_sql_command(g_conn, "CLOSE _pg_dump_cursor");
1502 destroyPQExpBuffer(q);
1509 * dump the contents of a single table
1511 * Actually, this just makes an ArchiveEntry for the table contents.
1514 dumpTableData(Archive *fout, TableDataInfo *tdinfo)
1516 TableInfo *tbinfo = tdinfo->tdtable;
1517 PQExpBuffer copyBuf = createPQExpBuffer();
1518 DataDumperPtr dumpFn;
1523 /* Dump/restore using COPY */
1524 dumpFn = dumpTableData_copy;
1525 /* must use 2 steps here 'cause fmtId is nonreentrant */
1526 appendPQExpBuffer(copyBuf, "COPY %s ",
1527 fmtId(tbinfo->dobj.name));
1528 appendPQExpBuffer(copyBuf, "%s %sFROM stdin;\n",
1529 fmtCopyColumnList(tbinfo),
1530 (tdinfo->oids && tbinfo->hasoids) ? "WITH OIDS " : "");
1531 copyStmt = copyBuf->data;
1535 /* Restore using INSERT */
1536 dumpFn = dumpTableData_insert;
1540 ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
1541 tbinfo->dobj.name, tbinfo->dobj.namespace->dobj.name,
1542 NULL, tbinfo->rolname,
1543 false, "TABLE DATA", SECTION_DATA,
1545 tdinfo->dobj.dependencies, tdinfo->dobj.nDeps,
1548 destroyPQExpBuffer(copyBuf);
1553 * set up dumpable objects representing the contents of tables
1556 getTableData(TableInfo *tblinfo, int numTables, bool oids)
1560 for (i = 0; i < numTables; i++)
1562 /* Skip VIEWs (no data to dump) */
1563 if (tblinfo[i].relkind == RELKIND_VIEW)
1565 /* Skip SEQUENCEs (handled elsewhere) */
1566 if (tblinfo[i].relkind == RELKIND_SEQUENCE)
1568 /* Skip FOREIGN TABLEs (no data to dump) */
1569 if (tblinfo[i].relkind == RELKIND_FOREIGN_TABLE)
1571 /* Skip unlogged tables if so requested */
1572 if (tblinfo[i].relpersistence == RELPERSISTENCE_UNLOGGED
1573 && no_unlogged_table_data)
1576 if (tblinfo[i].dobj.dump && tblinfo[i].dataObj == NULL)
1577 makeTableDataInfo(&(tblinfo[i]), oids);
1582 * Make a dumpable object for the data of this specific table
1585 makeTableDataInfo(TableInfo *tbinfo, bool oids)
1587 TableDataInfo *tdinfo;
1589 tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
1591 tdinfo->dobj.objType = DO_TABLE_DATA;
1594 * Note: use tableoid 0 so that this object won't be mistaken for
1595 * something that pg_depend entries apply to.
1597 tdinfo->dobj.catId.tableoid = 0;
1598 tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
1599 AssignDumpId(&tdinfo->dobj);
1600 tdinfo->dobj.name = tbinfo->dobj.name;
1601 tdinfo->dobj.namespace = tbinfo->dobj.namespace;
1602 tdinfo->tdtable = tbinfo;
1603 tdinfo->oids = oids;
1604 tdinfo->filtercond = NULL; /* might get set later */
1605 addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
1607 tbinfo->dataObj = tdinfo;
1611 * getTableDataFKConstraints -
1612 * add dump-order dependencies reflecting foreign key constraints
1614 * This code is executed only in a data-only dump --- in schema+data dumps
1615 * we handle foreign key issues by not creating the FK constraints until
1616 * after the data is loaded. In a data-only dump, however, we want to
1617 * order the table data objects in such a way that a table's referenced
1618 * tables are restored first. (In the presence of circular references or
1619 * self-references this may be impossible; we'll detect and complain about
1620 * that during the dependency sorting step.)
1623 getTableDataFKConstraints(void)
1625 DumpableObject **dobjs;
1629 /* Search through all the dumpable objects for FK constraints */
1630 getDumpableObjects(&dobjs, &numObjs);
1631 for (i = 0; i < numObjs; i++)
1633 if (dobjs[i]->objType == DO_FK_CONSTRAINT)
1635 ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
1638 /* Not interesting unless both tables are to be dumped */
1639 if (cinfo->contable == NULL ||
1640 cinfo->contable->dataObj == NULL)
1642 ftable = findTableByOid(cinfo->confrelid);
1643 if (ftable == NULL ||
1644 ftable->dataObj == NULL)
1648 * Okay, make referencing table's TABLE_DATA object depend on the
1649 * referenced table's TABLE_DATA object.
1651 addObjectDependency(&cinfo->contable->dataObj->dobj,
1652 ftable->dataObj->dobj.dumpId);
1660 * guessConstraintInheritance:
1661 * In pre-8.4 databases, we can't tell for certain which constraints
1662 * are inherited. We assume a CHECK constraint is inherited if its name
1663 * matches the name of any constraint in the parent. Originally this code
1664 * tried to compare the expression texts, but that can fail for various
1665 * reasons --- for example, if the parent and child tables are in different
1666 * schemas, reverse-listing of function calls may produce different text
1667 * (schema-qualified or not) depending on search path.
1669 * In 8.4 and up we can rely on the conislocal field to decide which
1670 * constraints must be dumped; much safer.
1672 * This function assumes all conislocal flags were initialized to TRUE.
1673 * It clears the flag on anything that seems to be inherited.
1676 guessConstraintInheritance(TableInfo *tblinfo, int numTables)
1682 for (i = 0; i < numTables; i++)
1684 TableInfo *tbinfo = &(tblinfo[i]);
1686 TableInfo **parents;
1689 /* Sequences and views never have parents */
1690 if (tbinfo->relkind == RELKIND_SEQUENCE ||
1691 tbinfo->relkind == RELKIND_VIEW)
1694 /* Don't bother computing anything for non-target tables, either */
1695 if (!tbinfo->dobj.dump)
1698 numParents = tbinfo->numParents;
1699 parents = tbinfo->parents;
1701 if (numParents == 0)
1702 continue; /* nothing to see here, move along */
1704 /* scan for inherited CHECK constraints */
1705 for (j = 0; j < tbinfo->ncheck; j++)
1707 ConstraintInfo *constr;
1709 constr = &(tbinfo->checkexprs[j]);
1711 for (k = 0; k < numParents; k++)
1715 parent = parents[k];
1716 for (l = 0; l < parent->ncheck; l++)
1718 ConstraintInfo *pconstr = &(parent->checkexprs[l]);
1720 if (strcmp(pconstr->dobj.name, constr->dobj.name) == 0)
1722 constr->conislocal = false;
1726 if (!constr->conislocal)
1736 * dump the database definition
1739 dumpDatabase(Archive *AH)
1741 PQExpBuffer dbQry = createPQExpBuffer();
1742 PQExpBuffer delQry = createPQExpBuffer();
1743 PQExpBuffer creaQry = createPQExpBuffer();
1756 const char *datname,
1764 datname = PQdb(g_conn);
1767 write_msg(NULL, "saving database definition\n");
1769 /* Make sure we are in proper schema */
1770 selectSourceSchema("pg_catalog");
1772 /* Get the database owner and parameters from pg_database */
1773 if (g_fout->remoteVersion >= 80400)
1775 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1776 "(%s datdba) AS dba, "
1777 "pg_encoding_to_char(encoding) AS encoding, "
1778 "datcollate, datctype, datfrozenxid, "
1779 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1780 "shobj_description(oid, 'pg_database') AS description "
1785 appendStringLiteralAH(dbQry, datname, AH);
1787 else if (g_fout->remoteVersion >= 80200)
1789 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1790 "(%s datdba) AS dba, "
1791 "pg_encoding_to_char(encoding) AS encoding, "
1792 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1793 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
1794 "shobj_description(oid, 'pg_database') AS description "
1799 appendStringLiteralAH(dbQry, datname, AH);
1801 else if (g_fout->remoteVersion >= 80000)
1803 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1804 "(%s datdba) AS dba, "
1805 "pg_encoding_to_char(encoding) AS encoding, "
1806 "NULL AS datcollate, NULL AS datctype, datfrozenxid, "
1807 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
1811 appendStringLiteralAH(dbQry, datname, AH);
1813 else if (g_fout->remoteVersion >= 70100)
1815 appendPQExpBuffer(dbQry, "SELECT tableoid, oid, "
1816 "(%s datdba) AS dba, "
1817 "pg_encoding_to_char(encoding) AS encoding, "
1818 "NULL AS datcollate, NULL AS datctype, "
1819 "0 AS datfrozenxid, "
1820 "NULL AS tablespace "
1824 appendStringLiteralAH(dbQry, datname, AH);
1828 appendPQExpBuffer(dbQry, "SELECT "
1829 "(SELECT oid FROM pg_class WHERE relname = 'pg_database') AS tableoid, "
1831 "(%s datdba) AS dba, "
1832 "pg_encoding_to_char(encoding) AS encoding, "
1833 "NULL AS datcollate, NULL AS datctype, "
1834 "0 AS datfrozenxid, "
1835 "NULL AS tablespace "
1839 appendStringLiteralAH(dbQry, datname, AH);
1842 res = PQexec(g_conn, dbQry->data);
1843 check_sql_result(res, g_conn, dbQry->data, PGRES_TUPLES_OK);
1845 ntups = PQntuples(res);
1849 write_msg(NULL, "missing pg_database entry for database \"%s\"\n",
1856 write_msg(NULL, "query returned more than one (%d) pg_database entry for database \"%s\"\n",
1861 i_tableoid = PQfnumber(res, "tableoid");
1862 i_oid = PQfnumber(res, "oid");
1863 i_dba = PQfnumber(res, "dba");
1864 i_encoding = PQfnumber(res, "encoding");
1865 i_collate = PQfnumber(res, "datcollate");
1866 i_ctype = PQfnumber(res, "datctype");
1867 i_frozenxid = PQfnumber(res, "datfrozenxid");
1868 i_tablespace = PQfnumber(res, "tablespace");
1870 dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
1871 dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
1872 dba = PQgetvalue(res, 0, i_dba);
1873 encoding = PQgetvalue(res, 0, i_encoding);
1874 collate = PQgetvalue(res, 0, i_collate);
1875 ctype = PQgetvalue(res, 0, i_ctype);
1876 frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
1877 tablespace = PQgetvalue(res, 0, i_tablespace);
1879 appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
1881 if (strlen(encoding) > 0)
1883 appendPQExpBuffer(creaQry, " ENCODING = ");
1884 appendStringLiteralAH(creaQry, encoding, AH);
1886 if (strlen(collate) > 0)
1888 appendPQExpBuffer(creaQry, " LC_COLLATE = ");
1889 appendStringLiteralAH(creaQry, collate, AH);
1891 if (strlen(ctype) > 0)
1893 appendPQExpBuffer(creaQry, " LC_CTYPE = ");
1894 appendStringLiteralAH(creaQry, ctype, AH);
1896 if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0)
1897 appendPQExpBuffer(creaQry, " TABLESPACE = %s",
1899 appendPQExpBuffer(creaQry, ";\n");
1903 appendPQExpBuffer(creaQry, "\n-- For binary upgrade, set datfrozenxid.\n");
1904 appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
1905 "SET datfrozenxid = '%u'\n"
1908 appendStringLiteralAH(creaQry, datname, AH);
1909 appendPQExpBuffer(creaQry, ";\n");
1913 appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
1916 dbDumpId = createDumpId();
1919 dbCatId, /* catalog ID */
1920 dbDumpId, /* dump ID */
1922 NULL, /* Namespace */
1923 NULL, /* Tablespace */
1925 false, /* with oids */
1926 "DATABASE", /* Desc */
1927 SECTION_PRE_DATA, /* Section */
1928 creaQry->data, /* Create */
1929 delQry->data, /* Del */
1934 NULL); /* Dumper Arg */
1937 * pg_largeobject and pg_largeobject_metadata come from the old system
1938 * intact, so set their relfrozenxids.
1943 PQExpBuffer loFrozenQry = createPQExpBuffer();
1944 PQExpBuffer loOutQry = createPQExpBuffer();
1950 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1951 "FROM pg_catalog.pg_class\n"
1952 "WHERE oid = %u;\n",
1953 LargeObjectRelationId);
1955 lo_res = PQexec(g_conn, loFrozenQry->data);
1956 check_sql_result(lo_res, g_conn, loFrozenQry->data, PGRES_TUPLES_OK);
1958 if (PQntuples(lo_res) != 1)
1960 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject.relfrozenxid\n");
1964 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
1966 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject.relfrozenxid\n");
1967 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
1968 "SET relfrozenxid = '%u'\n"
1969 "WHERE oid = %u;\n",
1970 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
1971 LargeObjectRelationId);
1972 ArchiveEntry(AH, nilCatalogId, createDumpId(),
1973 "pg_largeobject", NULL, NULL, "",
1974 false, "pg_largeobject", SECTION_PRE_DATA,
1975 loOutQry->data, "", NULL,
1982 * pg_largeobject_metadata
1984 if (g_fout->remoteVersion >= 90000)
1986 resetPQExpBuffer(loFrozenQry);
1987 resetPQExpBuffer(loOutQry);
1989 appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid\n"
1990 "FROM pg_catalog.pg_class\n"
1991 "WHERE oid = %u;\n",
1992 LargeObjectMetadataRelationId);
1994 lo_res = PQexec(g_conn, loFrozenQry->data);
1995 check_sql_result(lo_res, g_conn, loFrozenQry->data, PGRES_TUPLES_OK);
1997 if (PQntuples(lo_res) != 1)
1999 write_msg(NULL, "dumpDatabase(): could not find pg_largeobject_metadata.relfrozenxid\n");
2003 i_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
2005 appendPQExpBuffer(loOutQry, "\n-- For binary upgrade, set pg_largeobject_metadata.relfrozenxid\n");
2006 appendPQExpBuffer(loOutQry, "UPDATE pg_catalog.pg_class\n"
2007 "SET relfrozenxid = '%u'\n"
2008 "WHERE oid = %u;\n",
2009 atoi(PQgetvalue(lo_res, 0, i_relfrozenxid)),
2010 LargeObjectMetadataRelationId);
2011 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2012 "pg_largeobject_metadata", NULL, NULL, "",
2013 false, "pg_largeobject_metadata", SECTION_PRE_DATA,
2014 loOutQry->data, "", NULL,
2021 destroyPQExpBuffer(loFrozenQry);
2022 destroyPQExpBuffer(loOutQry);
2025 /* Dump DB comment if any */
2026 if (g_fout->remoteVersion >= 80200)
2029 * 8.2 keeps comments on shared objects in a shared table, so we
2030 * cannot use the dumpComment used for other database objects.
2032 char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
2034 if (comment && strlen(comment))
2036 resetPQExpBuffer(dbQry);
2039 * Generates warning when loaded into a differently-named
2042 appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", fmtId(datname));
2043 appendStringLiteralAH(dbQry, comment, AH);
2044 appendPQExpBuffer(dbQry, ";\n");
2046 ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
2047 dba, false, "COMMENT", SECTION_NONE,
2048 dbQry->data, "", NULL,
2049 &dbDumpId, 1, NULL, NULL);
2054 resetPQExpBuffer(dbQry);
2055 appendPQExpBuffer(dbQry, "DATABASE %s", fmtId(datname));
2056 dumpComment(AH, dbQry->data, NULL, "",
2057 dbCatId, 0, dbDumpId);
2062 /* Dump shared security label. */
2063 if (!no_security_labels && g_fout->remoteVersion >= 90200)
2065 PQExpBuffer seclabelQry = createPQExpBuffer();
2067 buildShSecLabelQuery(g_conn, "pg_database", dbCatId.oid, seclabelQry);
2068 res = PQexec(g_conn, seclabelQry->data);
2069 check_sql_result(res, g_conn, seclabelQry->data, PGRES_TUPLES_OK);
2070 resetPQExpBuffer(seclabelQry);
2071 emitShSecLabels(g_conn, res, seclabelQry, "DATABASE", datname);
2072 if (strlen(seclabelQry->data))
2073 ArchiveEntry(AH, dbCatId, createDumpId(), datname, NULL, NULL,
2074 dba, false, "SECURITY LABEL", SECTION_NONE,
2075 seclabelQry->data, "", NULL,
2076 &dbDumpId, 1, NULL, NULL);
2077 destroyPQExpBuffer(seclabelQry);
2080 destroyPQExpBuffer(dbQry);
2081 destroyPQExpBuffer(delQry);
2082 destroyPQExpBuffer(creaQry);
2087 * dumpEncoding: put the correct encoding into the archive
2090 dumpEncoding(Archive *AH)
2092 const char *encname = pg_encoding_to_char(AH->encoding);
2093 PQExpBuffer qry = createPQExpBuffer();
2096 write_msg(NULL, "saving encoding = %s\n", encname);
2098 appendPQExpBuffer(qry, "SET client_encoding = ");
2099 appendStringLiteralAH(qry, encname, AH);
2100 appendPQExpBuffer(qry, ";\n");
2102 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2103 "ENCODING", NULL, NULL, "",
2104 false, "ENCODING", SECTION_PRE_DATA,
2105 qry->data, "", NULL,
2109 destroyPQExpBuffer(qry);
2114 * dumpStdStrings: put the correct escape string behavior into the archive
2117 dumpStdStrings(Archive *AH)
2119 const char *stdstrings = AH->std_strings ? "on" : "off";
2120 PQExpBuffer qry = createPQExpBuffer();
2123 write_msg(NULL, "saving standard_conforming_strings = %s\n",
2126 appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
2129 ArchiveEntry(AH, nilCatalogId, createDumpId(),
2130 "STDSTRINGS", NULL, NULL, "",
2131 false, "STDSTRINGS", SECTION_PRE_DATA,
2132 qry->data, "", NULL,
2136 destroyPQExpBuffer(qry);
2142 * Collect schema-level data about large objects
2145 getBlobs(Archive *AH)
2147 PQExpBuffer blobQry = createPQExpBuffer();
2149 DumpableObject *bdata;
2154 /* Verbose message */
2156 write_msg(NULL, "reading large objects\n");
2158 /* Make sure we are in proper schema */
2159 selectSourceSchema("pg_catalog");
2161 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
2162 if (AH->remoteVersion >= 90000)
2163 appendPQExpBuffer(blobQry,
2164 "SELECT oid, (%s lomowner) AS rolname, lomacl"
2165 " FROM pg_largeobject_metadata",
2167 else if (AH->remoteVersion >= 70100)
2168 appendPQExpBuffer(blobQry,
2169 "SELECT DISTINCT loid, NULL::oid, NULL::oid"
2170 " FROM pg_largeobject");
2172 appendPQExpBuffer(blobQry,
2173 "SELECT oid, NULL::oid, NULL::oid"
2174 " FROM pg_class WHERE relkind = 'l'");
2176 res = PQexec(g_conn, blobQry->data);
2177 check_sql_result(res, g_conn, blobQry->data, PGRES_TUPLES_OK);
2179 ntups = PQntuples(res);
2183 * Each large object has its own BLOB archive entry.
2185 binfo = (BlobInfo *) pg_malloc(ntups * sizeof(BlobInfo));
2187 for (i = 0; i < ntups; i++)
2189 binfo[i].dobj.objType = DO_BLOB;
2190 binfo[i].dobj.catId.tableoid = LargeObjectRelationId;
2191 binfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, 0));
2192 AssignDumpId(&binfo[i].dobj);
2194 binfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, 0));
2195 if (!PQgetisnull(res, i, 1))
2196 binfo[i].rolname = pg_strdup(PQgetvalue(res, i, 1));
2198 binfo[i].rolname = "";
2199 if (!PQgetisnull(res, i, 2))
2200 binfo[i].blobacl = pg_strdup(PQgetvalue(res, i, 2));
2202 binfo[i].blobacl = NULL;
2206 * If we have any large objects, a "BLOBS" archive entry is needed.
2207 * This is just a placeholder for sorting; it carries no data now.
2209 bdata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
2210 bdata->objType = DO_BLOB_DATA;
2211 bdata->catId = nilCatalogId;
2212 AssignDumpId(bdata);
2213 bdata->name = pg_strdup("BLOBS");
2217 destroyPQExpBuffer(blobQry);
2223 * dump the definition (metadata) of the given large object
2226 dumpBlob(Archive *AH, BlobInfo *binfo)
2228 PQExpBuffer cquery = createPQExpBuffer();
2229 PQExpBuffer dquery = createPQExpBuffer();
2231 appendPQExpBuffer(cquery,
2232 "SELECT pg_catalog.lo_create('%s');\n",
2235 appendPQExpBuffer(dquery,
2236 "SELECT pg_catalog.lo_unlink('%s');\n",
2239 ArchiveEntry(AH, binfo->dobj.catId, binfo->dobj.dumpId,
2242 binfo->rolname, false,
2243 "BLOB", SECTION_PRE_DATA,
2244 cquery->data, dquery->data, NULL,
2245 binfo->dobj.dependencies, binfo->dobj.nDeps,
2248 /* set up tag for comment and/or ACL */
2249 resetPQExpBuffer(cquery);
2250 appendPQExpBuffer(cquery, "LARGE OBJECT %s", binfo->dobj.name);
2252 /* Dump comment if any */
2253 dumpComment(AH, cquery->data,
2254 NULL, binfo->rolname,
2255 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2257 /* Dump security label if any */
2258 dumpSecLabel(AH, cquery->data,
2259 NULL, binfo->rolname,
2260 binfo->dobj.catId, 0, binfo->dobj.dumpId);
2262 /* Dump ACL if any */
2264 dumpACL(AH, binfo->dobj.catId, binfo->dobj.dumpId, "LARGE OBJECT",
2265 binfo->dobj.name, NULL, cquery->data,
2266 NULL, binfo->rolname, binfo->blobacl);
2268 destroyPQExpBuffer(cquery);
2269 destroyPQExpBuffer(dquery);
2274 * dump the data contents of all large objects
2277 dumpBlobs(Archive *AH, void *arg)
2279 const char *blobQry;
2280 const char *blobFetchQry;
2282 char buf[LOBBUFSIZE];
2288 write_msg(NULL, "saving large objects\n");
2290 /* Make sure we are in proper schema */
2291 selectSourceSchema("pg_catalog");
2294 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
2295 * the already-in-memory dumpable objects instead...
2297 if (AH->remoteVersion >= 90000)
2298 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_largeobject_metadata";
2299 else if (AH->remoteVersion >= 70100)
2300 blobQry = "DECLARE bloboid CURSOR FOR SELECT DISTINCT loid FROM pg_largeobject";
2302 blobQry = "DECLARE bloboid CURSOR FOR SELECT oid FROM pg_class WHERE relkind = 'l'";
2304 res = PQexec(g_conn, blobQry);
2305 check_sql_result(res, g_conn, blobQry, PGRES_COMMAND_OK);
2307 /* Command to fetch from cursor */
2308 blobFetchQry = "FETCH 1000 IN bloboid";
2315 res = PQexec(g_conn, blobFetchQry);
2316 check_sql_result(res, g_conn, blobFetchQry, PGRES_TUPLES_OK);
2318 /* Process the tuples, if any */
2319 ntups = PQntuples(res);
2320 for (i = 0; i < ntups; i++)
2325 blobOid = atooid(PQgetvalue(res, i, 0));
2327 loFd = lo_open(g_conn, blobOid, INV_READ);
2330 write_msg(NULL, "could not open large object %u: %s",
2331 blobOid, PQerrorMessage(g_conn));
2335 StartBlob(AH, blobOid);
2337 /* Now read it in chunks, sending data to archive */
2340 cnt = lo_read(g_conn, loFd, buf, LOBBUFSIZE);
2343 write_msg(NULL, "error reading large object %u: %s",
2344 blobOid, PQerrorMessage(g_conn));
2348 WriteData(AH, buf, cnt);
2351 lo_close(g_conn, loFd);
2353 EndBlob(AH, blobOid);
2355 } while (ntups > 0);
2363 binary_upgrade_set_type_oids_by_type_oid(PQExpBuffer upgrade_buffer,
2366 PQExpBuffer upgrade_query = createPQExpBuffer();
2368 PGresult *upgrade_res;
2369 Oid pg_type_array_oid;
2371 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
2372 appendPQExpBuffer(upgrade_buffer,
2373 "SELECT binary_upgrade.set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2376 /* we only support old >= 8.3 for binary upgrades */
2377 appendPQExpBuffer(upgrade_query,
2379 "FROM pg_catalog.pg_type "
2380 "WHERE pg_type.oid = '%u'::pg_catalog.oid;",
2383 upgrade_res = PQexec(g_conn, upgrade_query->data);
2384 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2386 /* Expecting a single result only */
2387 ntups = PQntuples(upgrade_res);
2390 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2391 "query returned %d rows instead of one: %s\n",
2393 ntups, upgrade_query->data);
2397 pg_type_array_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "typarray")));
2399 if (OidIsValid(pg_type_array_oid))
2401 appendPQExpBuffer(upgrade_buffer,
2402 "\n-- For binary upgrade, must preserve pg_type array oid\n");
2403 appendPQExpBuffer(upgrade_buffer,
2404 "SELECT binary_upgrade.set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2408 PQclear(upgrade_res);
2409 destroyPQExpBuffer(upgrade_query);
2413 binary_upgrade_set_type_oids_by_rel_oid(PQExpBuffer upgrade_buffer,
2416 PQExpBuffer upgrade_query = createPQExpBuffer();
2418 PGresult *upgrade_res;
2420 bool toast_set = false;
2422 /* we only support old >= 8.3 for binary upgrades */
2423 appendPQExpBuffer(upgrade_query,
2424 "SELECT c.reltype AS crel, t.reltype AS trel "
2425 "FROM pg_catalog.pg_class c "
2426 "LEFT JOIN pg_catalog.pg_class t ON "
2427 " (c.reltoastrelid = t.oid) "
2428 "WHERE c.oid = '%u'::pg_catalog.oid;",
2431 upgrade_res = PQexec(g_conn, upgrade_query->data);
2432 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2434 /* Expecting a single result only */
2435 ntups = PQntuples(upgrade_res);
2438 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2439 "query returned %d rows instead of one: %s\n",
2441 ntups, upgrade_query->data);
2445 pg_type_oid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "crel")));
2447 binary_upgrade_set_type_oids_by_type_oid(upgrade_buffer, pg_type_oid);
2449 if (!PQgetisnull(upgrade_res, 0, PQfnumber(upgrade_res, "trel")))
2451 /* Toast tables do not have pg_type array rows */
2452 Oid pg_type_toast_oid = atooid(PQgetvalue(upgrade_res, 0,
2453 PQfnumber(upgrade_res, "trel")));
2455 appendPQExpBuffer(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
2456 appendPQExpBuffer(upgrade_buffer,
2457 "SELECT binary_upgrade.set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
2463 PQclear(upgrade_res);
2464 destroyPQExpBuffer(upgrade_query);
2470 binary_upgrade_set_pg_class_oids(PQExpBuffer upgrade_buffer, Oid pg_class_oid,
2473 PQExpBuffer upgrade_query = createPQExpBuffer();
2475 PGresult *upgrade_res;
2476 Oid pg_class_reltoastrelid;
2477 Oid pg_class_reltoastidxid;
2479 appendPQExpBuffer(upgrade_query,
2480 "SELECT c.reltoastrelid, t.reltoastidxid "
2481 "FROM pg_catalog.pg_class c LEFT JOIN "
2482 "pg_catalog.pg_class t ON (c.reltoastrelid = t.oid) "
2483 "WHERE c.oid = '%u'::pg_catalog.oid;",
2486 upgrade_res = PQexec(g_conn, upgrade_query->data);
2487 check_sql_result(upgrade_res, g_conn, upgrade_query->data, PGRES_TUPLES_OK);
2489 /* Expecting a single result only */
2490 ntups = PQntuples(upgrade_res);
2493 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
2494 "query returned %d rows instead of one: %s\n",
2496 ntups, upgrade_query->data);
2500 pg_class_reltoastrelid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastrelid")));
2501 pg_class_reltoastidxid = atooid(PQgetvalue(upgrade_res, 0, PQfnumber(upgrade_res, "reltoastidxid")));
2503 appendPQExpBuffer(upgrade_buffer,
2504 "\n-- For binary upgrade, must preserve pg_class oids\n");
2508 appendPQExpBuffer(upgrade_buffer,
2509 "SELECT binary_upgrade.set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
2511 /* only tables have toast tables, not indexes */
2512 if (OidIsValid(pg_class_reltoastrelid))
2515 * One complexity is that the table definition might not require
2516 * the creation of a TOAST table, and the TOAST table might have
2517 * been created long after table creation, when the table was
2518 * loaded with wide data. By setting the TOAST oid we force
2519 * creation of the TOAST heap and TOAST index by the backend so we
2520 * can cleanly copy the files during binary upgrade.
2523 appendPQExpBuffer(upgrade_buffer,
2524 "SELECT binary_upgrade.set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
2525 pg_class_reltoastrelid);
2527 /* every toast table has an index */
2528 appendPQExpBuffer(upgrade_buffer,
2529 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2530 pg_class_reltoastidxid);
2534 appendPQExpBuffer(upgrade_buffer,
2535 "SELECT binary_upgrade.set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
2538 appendPQExpBuffer(upgrade_buffer, "\n");
2540 PQclear(upgrade_res);
2541 destroyPQExpBuffer(upgrade_query);
2545 * If the DumpableObject is a member of an extension, add a suitable
2546 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
2549 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
2550 DumpableObject *dobj,
2551 const char *objlabel)
2553 DumpableObject *extobj = NULL;
2556 if (!dobj->ext_member)
2560 * Find the parent extension. We could avoid this search if we wanted to
2561 * add a link field to DumpableObject, but the space costs of that would
2562 * be considerable. We assume that member objects could only have a
2563 * direct dependency on their own extension, not any others.
2565 for (i = 0; i < dobj->nDeps; i++)
2567 extobj = findObjectByDumpId(dobj->dependencies[i]);
2568 if (extobj && extobj->objType == DO_EXTENSION)
2574 write_msg(NULL, "could not find parent extension for %s", objlabel);
2578 appendPQExpBuffer(upgrade_buffer,
2579 "\n-- For binary upgrade, handle extension membership the hard way\n");
2580 appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s;\n",
2581 fmtId(extobj->name),
2587 * read all namespaces in the system catalogs and return them in the
2588 * NamespaceInfo* structure
2590 * numNamespaces is set to the number of namespaces read in
2593 getNamespaces(int *numNamespaces)
2599 NamespaceInfo *nsinfo;
2607 * Before 7.3, there are no real namespaces; create two dummy entries, one
2608 * for user stuff and one for system stuff.
2610 if (g_fout->remoteVersion < 70300)
2612 nsinfo = (NamespaceInfo *) pg_malloc(2 * sizeof(NamespaceInfo));
2614 nsinfo[0].dobj.objType = DO_NAMESPACE;
2615 nsinfo[0].dobj.catId.tableoid = 0;
2616 nsinfo[0].dobj.catId.oid = 0;
2617 AssignDumpId(&nsinfo[0].dobj);
2618 nsinfo[0].dobj.name = pg_strdup("public");
2619 nsinfo[0].rolname = pg_strdup("");
2620 nsinfo[0].nspacl = pg_strdup("");
2622 selectDumpableNamespace(&nsinfo[0]);
2624 nsinfo[1].dobj.objType = DO_NAMESPACE;
2625 nsinfo[1].dobj.catId.tableoid = 0;
2626 nsinfo[1].dobj.catId.oid = 1;
2627 AssignDumpId(&nsinfo[1].dobj);
2628 nsinfo[1].dobj.name = pg_strdup("pg_catalog");
2629 nsinfo[1].rolname = pg_strdup("");
2630 nsinfo[1].nspacl = pg_strdup("");
2632 selectDumpableNamespace(&nsinfo[1]);
2634 g_namespaces = nsinfo;
2635 g_numNamespaces = *numNamespaces = 2;
2640 query = createPQExpBuffer();
2642 /* Make sure we are in proper schema */
2643 selectSourceSchema("pg_catalog");
2646 * we fetch all namespaces including system ones, so that every object we
2647 * read in can be linked to a containing namespace.
2649 appendPQExpBuffer(query, "SELECT tableoid, oid, nspname, "
2650 "(%s nspowner) AS rolname, "
2651 "nspacl FROM pg_namespace",
2654 res = PQexec(g_conn, query->data);
2655 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2657 ntups = PQntuples(res);
2659 nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
2661 i_tableoid = PQfnumber(res, "tableoid");
2662 i_oid = PQfnumber(res, "oid");
2663 i_nspname = PQfnumber(res, "nspname");
2664 i_rolname = PQfnumber(res, "rolname");
2665 i_nspacl = PQfnumber(res, "nspacl");
2667 for (i = 0; i < ntups; i++)
2669 nsinfo[i].dobj.objType = DO_NAMESPACE;
2670 nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2671 nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2672 AssignDumpId(&nsinfo[i].dobj);
2673 nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
2674 nsinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2675 nsinfo[i].nspacl = pg_strdup(PQgetvalue(res, i, i_nspacl));
2677 /* Decide whether to dump this namespace */
2678 selectDumpableNamespace(&nsinfo[i]);
2680 if (strlen(nsinfo[i].rolname) == 0)
2681 write_msg(NULL, "WARNING: owner of schema \"%s\" appears to be invalid\n",
2682 nsinfo[i].dobj.name);
2686 destroyPQExpBuffer(query);
2688 g_namespaces = nsinfo;
2689 g_numNamespaces = *numNamespaces = ntups;
2696 * given a namespace OID and an object OID, look up the info read by
2699 * NB: for pre-7.3 source database, we use object OID to guess whether it's
2700 * a system object or not. In 7.3 and later there is no guessing.
2702 static NamespaceInfo *
2703 findNamespace(Oid nsoid, Oid objoid)
2707 if (g_fout->remoteVersion >= 70300)
2709 for (i = 0; i < g_numNamespaces; i++)
2711 NamespaceInfo *nsinfo = &g_namespaces[i];
2713 if (nsoid == nsinfo->dobj.catId.oid)
2716 write_msg(NULL, "schema with OID %u does not exist\n", nsoid);
2721 /* This code depends on the layout set up by getNamespaces. */
2722 if (objoid > g_last_builtin_oid)
2723 i = 0; /* user object */
2725 i = 1; /* system object */
2726 return &g_namespaces[i];
2729 return NULL; /* keep compiler quiet */
2734 * read all extensions in the system catalogs and return them in the
2735 * ExtensionInfo* structure
2737 * numExtensions is set to the number of extensions read in
2740 getExtensions(int *numExtensions)
2746 ExtensionInfo *extinfo;
2751 int i_extrelocatable;
2757 * Before 9.1, there are no extensions.
2759 if (g_fout->remoteVersion < 90100)
2765 query = createPQExpBuffer();
2767 /* Make sure we are in proper schema */
2768 selectSourceSchema("pg_catalog");
2770 appendPQExpBuffer(query, "SELECT x.tableoid, x.oid, "
2771 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
2772 "FROM pg_extension x "
2773 "JOIN pg_namespace n ON n.oid = x.extnamespace");
2775 res = PQexec(g_conn, query->data);
2776 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2778 ntups = PQntuples(res);
2780 extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
2782 i_tableoid = PQfnumber(res, "tableoid");
2783 i_oid = PQfnumber(res, "oid");
2784 i_extname = PQfnumber(res, "extname");
2785 i_nspname = PQfnumber(res, "nspname");
2786 i_extrelocatable = PQfnumber(res, "extrelocatable");
2787 i_extversion = PQfnumber(res, "extversion");
2788 i_extconfig = PQfnumber(res, "extconfig");
2789 i_extcondition = PQfnumber(res, "extcondition");
2791 for (i = 0; i < ntups; i++)
2793 extinfo[i].dobj.objType = DO_EXTENSION;
2794 extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2795 extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2796 AssignDumpId(&extinfo[i].dobj);
2797 extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
2798 extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
2799 extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
2800 extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
2801 extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
2802 extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
2804 /* Decide whether we want to dump it */
2805 selectDumpableExtension(&(extinfo[i]));
2809 destroyPQExpBuffer(query);
2811 *numExtensions = ntups;
2818 * read all types in the system catalogs and return them in the
2819 * TypeInfo* structure
2821 * numTypes is set to the number of types read in
2823 * NB: this must run after getFuncs() because we assume we can do
2827 getTypes(int *numTypes)
2832 PQExpBuffer query = createPQExpBuffer();
2834 ShellTypeInfo *stinfo;
2850 * we include even the built-in types because those may be used as array
2851 * elements by user-defined types
2853 * we filter out the built-in types when we dump out the types
2855 * same approach for undefined (shell) types and array types
2857 * Note: as of 8.3 we can reliably detect whether a type is an
2858 * auto-generated array type by checking the element type's typarray.
2859 * (Before that the test is capable of generating false positives.) We
2860 * still check for name beginning with '_', though, so as to avoid the
2861 * cost of the subselect probe for all standard types. This would have to
2862 * be revisited if the backend ever allows renaming of array types.
2865 /* Make sure we are in proper schema */
2866 selectSourceSchema("pg_catalog");
2868 if (g_fout->remoteVersion >= 80300)
2870 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2872 "(%s typowner) AS rolname, "
2873 "typinput::oid AS typinput, "
2874 "typoutput::oid AS typoutput, typelem, typrelid, "
2875 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2876 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2877 "typtype, typisdefined, "
2878 "typname[0] = '_' AND typelem != 0 AND "
2879 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
2883 else if (g_fout->remoteVersion >= 70300)
2885 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2887 "(%s typowner) AS rolname, "
2888 "typinput::oid AS typinput, "
2889 "typoutput::oid AS typoutput, typelem, typrelid, "
2890 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2891 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2892 "typtype, typisdefined, "
2893 "typname[0] = '_' AND typelem != 0 AS isarray "
2897 else if (g_fout->remoteVersion >= 70100)
2899 appendPQExpBuffer(query, "SELECT tableoid, oid, typname, "
2900 "0::oid AS typnamespace, "
2901 "(%s typowner) AS rolname, "
2902 "typinput::oid AS typinput, "
2903 "typoutput::oid AS typoutput, typelem, typrelid, "
2904 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2905 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2906 "typtype, typisdefined, "
2907 "typname[0] = '_' AND typelem != 0 AS isarray "
2913 appendPQExpBuffer(query, "SELECT "
2914 "(SELECT oid FROM pg_class WHERE relname = 'pg_type') AS tableoid, "
2916 "0::oid AS typnamespace, "
2917 "(%s typowner) AS rolname, "
2918 "typinput::oid AS typinput, "
2919 "typoutput::oid AS typoutput, typelem, typrelid, "
2920 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
2921 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
2922 "typtype, typisdefined, "
2923 "typname[0] = '_' AND typelem != 0 AS isarray "
2928 res = PQexec(g_conn, query->data);
2929 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
2931 ntups = PQntuples(res);
2933 tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
2935 i_tableoid = PQfnumber(res, "tableoid");
2936 i_oid = PQfnumber(res, "oid");
2937 i_typname = PQfnumber(res, "typname");
2938 i_typnamespace = PQfnumber(res, "typnamespace");
2939 i_rolname = PQfnumber(res, "rolname");
2940 i_typinput = PQfnumber(res, "typinput");
2941 i_typoutput = PQfnumber(res, "typoutput");
2942 i_typelem = PQfnumber(res, "typelem");
2943 i_typrelid = PQfnumber(res, "typrelid");
2944 i_typrelkind = PQfnumber(res, "typrelkind");
2945 i_typtype = PQfnumber(res, "typtype");
2946 i_typisdefined = PQfnumber(res, "typisdefined");
2947 i_isarray = PQfnumber(res, "isarray");
2949 for (i = 0; i < ntups; i++)
2951 tyinfo[i].dobj.objType = DO_TYPE;
2952 tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
2953 tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
2954 AssignDumpId(&tyinfo[i].dobj);
2955 tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
2956 tyinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)),
2957 tyinfo[i].dobj.catId.oid);
2958 tyinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
2959 tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
2960 tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
2961 tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
2962 tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
2963 tyinfo[i].shellType = NULL;
2965 if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
2966 tyinfo[i].isDefined = true;
2968 tyinfo[i].isDefined = false;
2970 if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
2971 tyinfo[i].isArray = true;
2973 tyinfo[i].isArray = false;
2975 /* Decide whether we want to dump it */
2976 selectDumpableType(&tyinfo[i]);
2979 * If it's a domain, fetch info about its constraints, if any
2981 tyinfo[i].nDomChecks = 0;
2982 tyinfo[i].domChecks = NULL;
2983 if (tyinfo[i].dobj.dump && tyinfo[i].typtype == TYPTYPE_DOMAIN)
2984 getDomainConstraints(&(tyinfo[i]));
2987 * If it's a base type, make a DumpableObject representing a shell
2988 * definition of the type. We will need to dump that ahead of the I/O
2989 * functions for the type. Similarly, range types need a shell
2990 * definition in case they have a canonicalize function.
2992 * Note: the shell type doesn't have a catId. You might think it
2993 * should copy the base type's catId, but then it might capture the
2994 * pg_depend entries for the type, which we don't want.
2996 if (tyinfo[i].dobj.dump && (tyinfo[i].typtype == TYPTYPE_BASE ||
2997 tyinfo[i].typtype == TYPTYPE_RANGE))
2999 stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
3000 stinfo->dobj.objType = DO_SHELL_TYPE;
3001 stinfo->dobj.catId = nilCatalogId;
3002 AssignDumpId(&stinfo->dobj);
3003 stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
3004 stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
3005 stinfo->baseType = &(tyinfo[i]);
3006 tyinfo[i].shellType = stinfo;
3009 * Initially mark the shell type as not to be dumped. We'll only
3010 * dump it if the I/O or canonicalize functions need to be dumped;
3011 * this is taken care of while sorting dependencies.
3013 stinfo->dobj.dump = false;
3016 * However, if dumping from pre-7.3, there will be no dependency
3017 * info so we have to fake it here. We only need to worry about
3018 * typinput and typoutput since the other functions only exist
3021 if (g_fout->remoteVersion < 70300)
3027 typinput = atooid(PQgetvalue(res, i, i_typinput));
3028 typoutput = atooid(PQgetvalue(res, i, i_typoutput));
3030 funcInfo = findFuncByOid(typinput);
3031 if (funcInfo && funcInfo->dobj.dump)
3033 /* base type depends on function */
3034 addObjectDependency(&tyinfo[i].dobj,
3035 funcInfo->dobj.dumpId);
3036 /* function depends on shell type */
3037 addObjectDependency(&funcInfo->dobj,
3038 stinfo->dobj.dumpId);
3039 /* mark shell type as to be dumped */
3040 stinfo->dobj.dump = true;
3043 funcInfo = findFuncByOid(typoutput);
3044 if (funcInfo && funcInfo->dobj.dump)
3046 /* base type depends on function */
3047 addObjectDependency(&tyinfo[i].dobj,
3048 funcInfo->dobj.dumpId);
3049 /* function depends on shell type */
3050 addObjectDependency(&funcInfo->dobj,
3051 stinfo->dobj.dumpId);
3052 /* mark shell type as to be dumped */
3053 stinfo->dobj.dump = true;
3058 if (strlen(tyinfo[i].rolname) == 0 && tyinfo[i].isDefined)
3059 write_msg(NULL, "WARNING: owner of data type \"%s\" appears to be invalid\n",
3060 tyinfo[i].dobj.name);
3067 destroyPQExpBuffer(query);
3074 * read all operators in the system catalogs and return them in the
3075 * OprInfo* structure
3077 * numOprs is set to the number of operators read in
3080 getOperators(int *numOprs)
3085 PQExpBuffer query = createPQExpBuffer();
3095 * find all operators, including builtin operators; we filter out
3096 * system-defined operators at dump-out time.
3099 /* Make sure we are in proper schema */
3100 selectSourceSchema("pg_catalog");
3102 if (g_fout->remoteVersion >= 70300)
3104 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3106 "(%s oprowner) AS rolname, "
3107 "oprcode::oid AS oprcode "
3111 else if (g_fout->remoteVersion >= 70100)
3113 appendPQExpBuffer(query, "SELECT tableoid, oid, oprname, "
3114 "0::oid AS oprnamespace, "
3115 "(%s oprowner) AS rolname, "
3116 "oprcode::oid AS oprcode "
3122 appendPQExpBuffer(query, "SELECT "
3123 "(SELECT oid FROM pg_class WHERE relname = 'pg_operator') AS tableoid, "
3125 "0::oid AS oprnamespace, "
3126 "(%s oprowner) AS rolname, "
3127 "oprcode::oid AS oprcode "
3132 res = PQexec(g_conn, query->data);
3133 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3135 ntups = PQntuples(res);
3138 oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
3140 i_tableoid = PQfnumber(res, "tableoid");
3141 i_oid = PQfnumber(res, "oid");
3142 i_oprname = PQfnumber(res, "oprname");
3143 i_oprnamespace = PQfnumber(res, "oprnamespace");
3144 i_rolname = PQfnumber(res, "rolname");
3145 i_oprcode = PQfnumber(res, "oprcode");
3147 for (i = 0; i < ntups; i++)
3149 oprinfo[i].dobj.objType = DO_OPERATOR;
3150 oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3151 oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3152 AssignDumpId(&oprinfo[i].dobj);
3153 oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
3154 oprinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)),
3155 oprinfo[i].dobj.catId.oid);
3156 oprinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3157 oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
3159 /* Decide whether we want to dump it */
3160 selectDumpableObject(&(oprinfo[i].dobj));
3162 if (strlen(oprinfo[i].rolname) == 0)
3163 write_msg(NULL, "WARNING: owner of operator \"%s\" appears to be invalid\n",
3164 oprinfo[i].dobj.name);
3169 destroyPQExpBuffer(query);
3176 * read all collations in the system catalogs and return them in the
3177 * CollInfo* structure
3179 * numCollations is set to the number of collations read in
3182 getCollations(int *numCollations)
3187 PQExpBuffer query = createPQExpBuffer();
3192 int i_collnamespace;
3195 /* Collations didn't exist pre-9.1 */
3196 if (g_fout->remoteVersion < 90100)
3203 * find all collations, including builtin collations; we filter out
3204 * system-defined collations at dump-out time.
3207 /* Make sure we are in proper schema */
3208 selectSourceSchema("pg_catalog");
3210 appendPQExpBuffer(query, "SELECT tableoid, oid, collname, "
3212 "(%s collowner) AS rolname "
3213 "FROM pg_collation",
3216 res = PQexec(g_conn, query->data);
3217 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3219 ntups = PQntuples(res);
3220 *numCollations = ntups;
3222 collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
3224 i_tableoid = PQfnumber(res, "tableoid");
3225 i_oid = PQfnumber(res, "oid");
3226 i_collname = PQfnumber(res, "collname");
3227 i_collnamespace = PQfnumber(res, "collnamespace");
3228 i_rolname = PQfnumber(res, "rolname");
3230 for (i = 0; i < ntups; i++)
3232 collinfo[i].dobj.objType = DO_COLLATION;
3233 collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3234 collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3235 AssignDumpId(&collinfo[i].dobj);
3236 collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
3237 collinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_collnamespace)),
3238 collinfo[i].dobj.catId.oid);
3239 collinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3241 /* Decide whether we want to dump it */
3242 selectDumpableObject(&(collinfo[i].dobj));
3247 destroyPQExpBuffer(query);
3254 * read all conversions in the system catalogs and return them in the
3255 * ConvInfo* structure
3257 * numConversions is set to the number of conversions read in
3260 getConversions(int *numConversions)
3265 PQExpBuffer query = createPQExpBuffer();
3273 /* Conversions didn't exist pre-7.3 */
3274 if (g_fout->remoteVersion < 70300)
3276 *numConversions = 0;
3281 * find all conversions, including builtin conversions; we filter out
3282 * system-defined conversions at dump-out time.
3285 /* Make sure we are in proper schema */
3286 selectSourceSchema("pg_catalog");
3288 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
3290 "(%s conowner) AS rolname "
3291 "FROM pg_conversion",
3294 res = PQexec(g_conn, query->data);
3295 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3297 ntups = PQntuples(res);
3298 *numConversions = ntups;
3300 convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
3302 i_tableoid = PQfnumber(res, "tableoid");
3303 i_oid = PQfnumber(res, "oid");
3304 i_conname = PQfnumber(res, "conname");
3305 i_connamespace = PQfnumber(res, "connamespace");
3306 i_rolname = PQfnumber(res, "rolname");
3308 for (i = 0; i < ntups; i++)
3310 convinfo[i].dobj.objType = DO_CONVERSION;
3311 convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3312 convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3313 AssignDumpId(&convinfo[i].dobj);
3314 convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
3315 convinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_connamespace)),
3316 convinfo[i].dobj.catId.oid);
3317 convinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3319 /* Decide whether we want to dump it */
3320 selectDumpableObject(&(convinfo[i].dobj));
3325 destroyPQExpBuffer(query);
3332 * read all opclasses in the system catalogs and return them in the
3333 * OpclassInfo* structure
3335 * numOpclasses is set to the number of opclasses read in
3338 getOpclasses(int *numOpclasses)
3343 PQExpBuffer query = createPQExpBuffer();
3344 OpclassInfo *opcinfo;
3352 * find all opclasses, including builtin opclasses; we filter out
3353 * system-defined opclasses at dump-out time.
3356 /* Make sure we are in proper schema */
3357 selectSourceSchema("pg_catalog");
3359 if (g_fout->remoteVersion >= 70300)
3361 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3363 "(%s opcowner) AS rolname "
3367 else if (g_fout->remoteVersion >= 70100)
3369 appendPQExpBuffer(query, "SELECT tableoid, oid, opcname, "
3370 "0::oid AS opcnamespace, "
3371 "''::name AS rolname "
3376 appendPQExpBuffer(query, "SELECT "
3377 "(SELECT oid FROM pg_class WHERE relname = 'pg_opclass') AS tableoid, "
3379 "0::oid AS opcnamespace, "
3380 "''::name AS rolname "
3384 res = PQexec(g_conn, query->data);
3385 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3387 ntups = PQntuples(res);
3388 *numOpclasses = ntups;
3390 opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
3392 i_tableoid = PQfnumber(res, "tableoid");
3393 i_oid = PQfnumber(res, "oid");
3394 i_opcname = PQfnumber(res, "opcname");
3395 i_opcnamespace = PQfnumber(res, "opcnamespace");
3396 i_rolname = PQfnumber(res, "rolname");
3398 for (i = 0; i < ntups; i++)
3400 opcinfo[i].dobj.objType = DO_OPCLASS;
3401 opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3402 opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3403 AssignDumpId(&opcinfo[i].dobj);
3404 opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
3405 opcinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)),
3406 opcinfo[i].dobj.catId.oid);
3407 opcinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3409 /* Decide whether we want to dump it */
3410 selectDumpableObject(&(opcinfo[i].dobj));
3412 if (g_fout->remoteVersion >= 70300)
3414 if (strlen(opcinfo[i].rolname) == 0)
3415 write_msg(NULL, "WARNING: owner of operator class \"%s\" appears to be invalid\n",
3416 opcinfo[i].dobj.name);
3422 destroyPQExpBuffer(query);
3429 * read all opfamilies in the system catalogs and return them in the
3430 * OpfamilyInfo* structure
3432 * numOpfamilies is set to the number of opfamilies read in
3435 getOpfamilies(int *numOpfamilies)
3441 OpfamilyInfo *opfinfo;
3448 /* Before 8.3, there is no separate concept of opfamilies */
3449 if (g_fout->remoteVersion < 80300)
3455 query = createPQExpBuffer();
3458 * find all opfamilies, including builtin opfamilies; we filter out
3459 * system-defined opfamilies at dump-out time.
3462 /* Make sure we are in proper schema */
3463 selectSourceSchema("pg_catalog");
3465 appendPQExpBuffer(query, "SELECT tableoid, oid, opfname, "
3467 "(%s opfowner) AS rolname "
3471 res = PQexec(g_conn, query->data);
3472 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3474 ntups = PQntuples(res);
3475 *numOpfamilies = ntups;
3477 opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
3479 i_tableoid = PQfnumber(res, "tableoid");
3480 i_oid = PQfnumber(res, "oid");
3481 i_opfname = PQfnumber(res, "opfname");
3482 i_opfnamespace = PQfnumber(res, "opfnamespace");
3483 i_rolname = PQfnumber(res, "rolname");
3485 for (i = 0; i < ntups; i++)
3487 opfinfo[i].dobj.objType = DO_OPFAMILY;
3488 opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3489 opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3490 AssignDumpId(&opfinfo[i].dobj);
3491 opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
3492 opfinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_opfnamespace)),
3493 opfinfo[i].dobj.catId.oid);
3494 opfinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3496 /* Decide whether we want to dump it */
3497 selectDumpableObject(&(opfinfo[i].dobj));
3499 if (g_fout->remoteVersion >= 70300)
3501 if (strlen(opfinfo[i].rolname) == 0)
3502 write_msg(NULL, "WARNING: owner of operator family \"%s\" appears to be invalid\n",
3503 opfinfo[i].dobj.name);
3509 destroyPQExpBuffer(query);
3516 * read all the user-defined aggregates in the system catalogs and
3517 * return them in the AggInfo* structure
3519 * numAggs is set to the number of aggregates read in
3522 getAggregates(int *numAggs)
3527 PQExpBuffer query = createPQExpBuffer();
3538 /* Make sure we are in proper schema */
3539 selectSourceSchema("pg_catalog");
3542 * Find all user-defined aggregates. See comment in getFuncs() for the
3543 * rationale behind the filtering logic.
3546 if (g_fout->remoteVersion >= 80200)
3548 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3549 "pronamespace AS aggnamespace, "
3550 "pronargs, proargtypes, "
3551 "(%s proowner) AS rolname, "
3554 "WHERE proisagg AND ("
3556 "(SELECT oid FROM pg_namespace "
3557 "WHERE nspname = 'pg_catalog')",
3559 if (binary_upgrade && g_fout->remoteVersion >= 90100)
3560 appendPQExpBuffer(query,
3561 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3562 "classid = 'pg_proc'::regclass AND "
3563 "objid = p.oid AND "
3564 "refclassid = 'pg_extension'::regclass AND "
3566 appendPQExpBuffer(query, ")");
3568 else if (g_fout->remoteVersion >= 70300)
3570 appendPQExpBuffer(query, "SELECT tableoid, oid, proname AS aggname, "
3571 "pronamespace AS aggnamespace, "
3572 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
3574 "(%s proowner) AS rolname, "
3578 "AND pronamespace != "
3579 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
3582 else if (g_fout->remoteVersion >= 70100)
3584 appendPQExpBuffer(query, "SELECT tableoid, oid, aggname, "
3585 "0::oid AS aggnamespace, "
3586 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3587 "aggbasetype AS proargtypes, "
3588 "(%s aggowner) AS rolname, "
3590 "FROM pg_aggregate "
3591 "where oid > '%u'::oid",
3593 g_last_builtin_oid);
3597 appendPQExpBuffer(query, "SELECT "
3598 "(SELECT oid FROM pg_class WHERE relname = 'pg_aggregate') AS tableoid, "
3600 "0::oid AS aggnamespace, "
3601 "CASE WHEN aggbasetype = 0 THEN 0 ELSE 1 END AS pronargs, "
3602 "aggbasetype AS proargtypes, "
3603 "(%s aggowner) AS rolname, "
3605 "FROM pg_aggregate "
3606 "where oid > '%u'::oid",
3608 g_last_builtin_oid);
3611 res = PQexec(g_conn, query->data);
3612 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3614 ntups = PQntuples(res);
3617 agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
3619 i_tableoid = PQfnumber(res, "tableoid");
3620 i_oid = PQfnumber(res, "oid");
3621 i_aggname = PQfnumber(res, "aggname");
3622 i_aggnamespace = PQfnumber(res, "aggnamespace");
3623 i_pronargs = PQfnumber(res, "pronargs");
3624 i_proargtypes = PQfnumber(res, "proargtypes");
3625 i_rolname = PQfnumber(res, "rolname");
3626 i_aggacl = PQfnumber(res, "aggacl");
3628 for (i = 0; i < ntups; i++)
3630 agginfo[i].aggfn.dobj.objType = DO_AGG;
3631 agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3632 agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3633 AssignDumpId(&agginfo[i].aggfn.dobj);
3634 agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
3635 agginfo[i].aggfn.dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)),
3636 agginfo[i].aggfn.dobj.catId.oid);
3637 agginfo[i].aggfn.rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3638 if (strlen(agginfo[i].aggfn.rolname) == 0)
3639 write_msg(NULL, "WARNING: owner of aggregate function \"%s\" appears to be invalid\n",
3640 agginfo[i].aggfn.dobj.name);
3641 agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
3642 agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
3643 agginfo[i].aggfn.proacl = pg_strdup(PQgetvalue(res, i, i_aggacl));
3644 agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
3645 if (agginfo[i].aggfn.nargs == 0)
3646 agginfo[i].aggfn.argtypes = NULL;
3649 agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
3650 if (g_fout->remoteVersion >= 70300)
3651 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3652 agginfo[i].aggfn.argtypes,
3653 agginfo[i].aggfn.nargs);
3655 /* it's just aggbasetype */
3656 agginfo[i].aggfn.argtypes[0] = atooid(PQgetvalue(res, i, i_proargtypes));
3659 /* Decide whether we want to dump it */
3660 selectDumpableObject(&(agginfo[i].aggfn.dobj));
3665 destroyPQExpBuffer(query);
3672 * read all the user-defined functions in the system catalogs and
3673 * return them in the FuncInfo* structure
3675 * numFuncs is set to the number of functions read in
3678 getFuncs(int *numFuncs)
3683 PQExpBuffer query = createPQExpBuffer();
3696 /* Make sure we are in proper schema */
3697 selectSourceSchema("pg_catalog");
3700 * Find all user-defined functions. Normally we can exclude functions in
3701 * pg_catalog, which is worth doing since there are several thousand of
3702 * 'em. However, there are some extensions that create functions in
3703 * pg_catalog. In normal dumps we can still ignore those --- but in
3704 * binary-upgrade mode, we must dump the member objects of the extension,
3705 * so be sure to fetch any such functions.
3707 * Also, in 9.2 and up, exclude functions that are internally dependent on
3708 * something else, since presumably those will be created as a result of
3709 * creating the something else. This currently only acts to suppress
3710 * constructor functions for range types. Note that this is OK only
3711 * because the constructors don't have any dependencies the range type
3712 * doesn't have; otherwise we might not get creation ordering correct.
3715 if (g_fout->remoteVersion >= 70300)
3717 appendPQExpBuffer(query,
3718 "SELECT tableoid, oid, proname, prolang, "
3719 "pronargs, proargtypes, prorettype, proacl, "
3721 "(%s proowner) AS rolname "
3723 "WHERE NOT proisagg AND ("
3725 "(SELECT oid FROM pg_namespace "
3726 "WHERE nspname = 'pg_catalog')",
3728 if (g_fout->remoteVersion >= 90200)
3729 appendPQExpBuffer(query,
3730 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
3731 "WHERE classid = 'pg_proc'::regclass AND "
3732 "objid = p.oid AND deptype = 'i')");
3733 if (binary_upgrade && g_fout->remoteVersion >= 90100)
3734 appendPQExpBuffer(query,
3735 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
3736 "classid = 'pg_proc'::regclass AND "
3737 "objid = p.oid AND "
3738 "refclassid = 'pg_extension'::regclass AND "
3740 appendPQExpBuffer(query, ")");
3742 else if (g_fout->remoteVersion >= 70100)
3744 appendPQExpBuffer(query,
3745 "SELECT tableoid, oid, proname, prolang, "
3746 "pronargs, proargtypes, prorettype, "
3747 "'{=X}' AS proacl, "
3748 "0::oid AS pronamespace, "
3749 "(%s proowner) AS rolname "
3751 "WHERE pg_proc.oid > '%u'::oid",
3753 g_last_builtin_oid);
3757 appendPQExpBuffer(query,
3759 "(SELECT oid FROM pg_class "
3760 " WHERE relname = 'pg_proc') AS tableoid, "
3761 "oid, proname, prolang, "
3762 "pronargs, proargtypes, prorettype, "
3763 "'{=X}' AS proacl, "
3764 "0::oid AS pronamespace, "
3765 "(%s proowner) AS rolname "
3767 "where pg_proc.oid > '%u'::oid",
3769 g_last_builtin_oid);
3772 res = PQexec(g_conn, query->data);
3773 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
3775 ntups = PQntuples(res);
3779 finfo = (FuncInfo *) pg_calloc(ntups, sizeof(FuncInfo));
3781 i_tableoid = PQfnumber(res, "tableoid");
3782 i_oid = PQfnumber(res, "oid");
3783 i_proname = PQfnumber(res, "proname");
3784 i_pronamespace = PQfnumber(res, "pronamespace");
3785 i_rolname = PQfnumber(res, "rolname");
3786 i_prolang = PQfnumber(res, "prolang");
3787 i_pronargs = PQfnumber(res, "pronargs");
3788 i_proargtypes = PQfnumber(res, "proargtypes");
3789 i_prorettype = PQfnumber(res, "prorettype");
3790 i_proacl = PQfnumber(res, "proacl");
3792 for (i = 0; i < ntups; i++)
3794 finfo[i].dobj.objType = DO_FUNC;
3795 finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
3796 finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
3797 AssignDumpId(&finfo[i].dobj);
3798 finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
3799 finfo[i].dobj.namespace =
3800 findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)),
3801 finfo[i].dobj.catId.oid);
3802 finfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
3803 finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
3804 finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
3805 finfo[i].proacl = pg_strdup(PQgetvalue(res, i, i_proacl));
3806 finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
3807 if (finfo[i].nargs == 0)
3808 finfo[i].argtypes = NULL;
3811 finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
3812 parseOidArray(PQgetvalue(res, i, i_proargtypes),
3813 finfo[i].argtypes, finfo[i].nargs);
3816 /* Decide whether we want to dump it */
3817 selectDumpableObject(&(finfo[i].dobj));
3819 if (strlen(finfo[i].rolname) == 0)
3821 "WARNING: owner of function \"%s\" appears to be invalid\n",
3822 finfo[i].dobj.name);
3827 destroyPQExpBuffer(query);
3834 * read all the user-defined tables (no indexes, no catalogs)
3835 * in the system catalogs return them in the TableInfo* structure
3837 * numTables is set to the number of tables read in
3840 getTables(int *numTables)
3845 PQExpBuffer query = createPQExpBuffer();
3855 int i_relhastriggers;
3861 int i_toastfrozenxid;
3862 int i_relpersistence;
3865 int i_reltablespace;
3867 int i_toastreloptions;
3870 /* Make sure we are in proper schema */
3871 selectSourceSchema("pg_catalog");
3874 * Find all the tables (including views and sequences).
3876 * We include system catalogs, so that we can work if a user table is
3877 * defined to inherit from a system catalog (pretty weird, but...)
3879 * We ignore tables that are not type 'r' (ordinary relation), 'S'
3880 * (sequence), 'v' (view), or 'c' (composite type).
3882 * Composite-type table entries won't be dumped as such, but we have to
3883 * make a DumpableObject for them so that we can track dependencies of the
3884 * composite type (pg_depend entries for columns of the composite type
3885 * link to the pg_class entry not the pg_type entry).
3887 * Note: in this phase we should collect only a minimal amount of
3888 * information about each table, basically just enough to decide if it is
3889 * interesting. We must fetch all tables in this phase because otherwise
3890 * we cannot correctly identify inherited columns, owned sequences, etc.
3893 if (g_fout->remoteVersion >= 90100)
3896 * Left join to pick up dependency info linking sequences to their
3897 * owning column, if any (note this dependency is AUTO as of 8.2)
3899 appendPQExpBuffer(query,
3900 "SELECT c.tableoid, c.oid, c.relname, "
3901 "c.relacl, c.relkind, c.relnamespace, "
3902 "(%s c.relowner) AS rolname, "
3903 "c.relchecks, c.relhastriggers, "
3904 "c.relhasindex, c.relhasrules, c.relhasoids, "
3905 "c.relfrozenxid, tc.oid AS toid, "
3906 "tc.relfrozenxid AS tfrozenxid, "
3907 "c.relpersistence, "
3908 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3909 "d.refobjid AS owning_tab, "
3910 "d.refobjsubid AS owning_col, "
3911 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3912 "array_to_string(c.reloptions, ', ') AS reloptions, "
3913 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3915 "LEFT JOIN pg_depend d ON "
3916 "(c.relkind = '%c' AND "
3917 "d.classid = c.tableoid AND d.objid = c.oid AND "
3918 "d.objsubid = 0 AND "
3919 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3920 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3921 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c') "
3925 RELKIND_RELATION, RELKIND_SEQUENCE,
3926 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE,
3927 RELKIND_FOREIGN_TABLE);
3929 else if (g_fout->remoteVersion >= 90000)
3932 * Left join to pick up dependency info linking sequences to their
3933 * owning column, if any (note this dependency is AUTO as of 8.2)
3935 appendPQExpBuffer(query,
3936 "SELECT c.tableoid, c.oid, c.relname, "
3937 "c.relacl, c.relkind, c.relnamespace, "
3938 "(%s c.relowner) AS rolname, "
3939 "c.relchecks, c.relhastriggers, "
3940 "c.relhasindex, c.relhasrules, c.relhasoids, "
3941 "c.relfrozenxid, tc.oid AS toid, "
3942 "tc.relfrozenxid AS tfrozenxid, "
3943 "'p' AS relpersistence, "
3944 "CASE WHEN c.reloftype <> 0 THEN c.reloftype::pg_catalog.regtype ELSE NULL END AS reloftype, "
3945 "d.refobjid AS owning_tab, "
3946 "d.refobjsubid AS owning_col, "
3947 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3948 "array_to_string(c.reloptions, ', ') AS reloptions, "
3949 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3951 "LEFT JOIN pg_depend d ON "
3952 "(c.relkind = '%c' AND "
3953 "d.classid = c.tableoid AND d.objid = c.oid AND "
3954 "d.objsubid = 0 AND "
3955 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3956 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3957 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3961 RELKIND_RELATION, RELKIND_SEQUENCE,
3962 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3964 else if (g_fout->remoteVersion >= 80400)
3967 * Left join to pick up dependency info linking sequences to their
3968 * owning column, if any (note this dependency is AUTO as of 8.2)
3970 appendPQExpBuffer(query,
3971 "SELECT c.tableoid, c.oid, c.relname, "
3972 "c.relacl, c.relkind, c.relnamespace, "
3973 "(%s c.relowner) AS rolname, "
3974 "c.relchecks, c.relhastriggers, "
3975 "c.relhasindex, c.relhasrules, c.relhasoids, "
3976 "c.relfrozenxid, tc.oid AS toid, "
3977 "tc.relfrozenxid AS tfrozenxid, "
3978 "'p' AS relpersistence, "
3979 "NULL AS reloftype, "
3980 "d.refobjid AS owning_tab, "
3981 "d.refobjsubid AS owning_col, "
3982 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
3983 "array_to_string(c.reloptions, ', ') AS reloptions, "
3984 "array_to_string(array(SELECT 'toast.' || x FROM unnest(tc.reloptions) x), ', ') AS toast_reloptions "
3986 "LEFT JOIN pg_depend d ON "
3987 "(c.relkind = '%c' AND "
3988 "d.classid = c.tableoid AND d.objid = c.oid AND "
3989 "d.objsubid = 0 AND "
3990 "d.refclassid = c.tableoid AND d.deptype = 'a') "
3991 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
3992 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
3996 RELKIND_RELATION, RELKIND_SEQUENCE,
3997 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
3999 else if (g_fout->remoteVersion >= 80200)
4002 * Left join to pick up dependency info linking sequences to their
4003 * owning column, if any (note this dependency is AUTO as of 8.2)
4005 appendPQExpBuffer(query,
4006 "SELECT c.tableoid, c.oid, c.relname, "
4007 "c.relacl, c.relkind, c.relnamespace, "
4008 "(%s c.relowner) AS rolname, "
4009 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
4010 "c.relhasindex, c.relhasrules, c.relhasoids, "
4011 "c.relfrozenxid, tc.oid AS toid, "
4012 "tc.relfrozenxid AS tfrozenxid, "
4013 "'p' AS relpersistence, "
4014 "NULL AS reloftype, "
4015 "d.refobjid AS owning_tab, "
4016 "d.refobjsubid AS owning_col, "
4017 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4018 "array_to_string(c.reloptions, ', ') AS reloptions, "
4019 "NULL AS toast_reloptions "
4021 "LEFT JOIN pg_depend d ON "
4022 "(c.relkind = '%c' AND "
4023 "d.classid = c.tableoid AND d.objid = c.oid AND "
4024 "d.objsubid = 0 AND "
4025 "d.refclassid = c.tableoid AND d.deptype = 'a') "
4026 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
4027 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
4031 RELKIND_RELATION, RELKIND_SEQUENCE,
4032 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4034 else if (g_fout->remoteVersion >= 80000)
4037 * Left join to pick up dependency info linking sequences to their
4038 * owning column, if any
4040 appendPQExpBuffer(query,
4041 "SELECT c.tableoid, c.oid, relname, "
4042 "relacl, relkind, relnamespace, "
4043 "(%s relowner) AS rolname, "
4044 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4045 "relhasindex, relhasrules, relhasoids, "
4046 "0 AS relfrozenxid, "
4049 "'p' AS relpersistence, "
4050 "NULL AS reloftype, "
4051 "d.refobjid AS owning_tab, "
4052 "d.refobjsubid AS owning_col, "
4053 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
4054 "NULL AS reloptions, "
4055 "NULL AS toast_reloptions "
4057 "LEFT JOIN pg_depend d ON "
4058 "(c.relkind = '%c' AND "
4059 "d.classid = c.tableoid AND d.objid = c.oid AND "
4060 "d.objsubid = 0 AND "
4061 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4062 "WHERE relkind in ('%c', '%c', '%c', '%c') "
4066 RELKIND_RELATION, RELKIND_SEQUENCE,
4067 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4069 else if (g_fout->remoteVersion >= 70300)
4072 * Left join to pick up dependency info linking sequences to their
4073 * owning column, if any
4075 appendPQExpBuffer(query,
4076 "SELECT c.tableoid, c.oid, relname, "
4077 "relacl, relkind, relnamespace, "
4078 "(%s relowner) AS rolname, "
4079 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4080 "relhasindex, relhasrules, relhasoids, "
4081 "0 AS relfrozenxid, "
4084 "'p' AS relpersistence, "
4085 "NULL AS reloftype, "
4086 "d.refobjid AS owning_tab, "
4087 "d.refobjsubid AS owning_col, "
4088 "NULL AS reltablespace, "
4089 "NULL AS reloptions, "
4090 "NULL AS toast_reloptions "
4092 "LEFT JOIN pg_depend d ON "
4093 "(c.relkind = '%c' AND "
4094 "d.classid = c.tableoid AND d.objid = c.oid AND "
4095 "d.objsubid = 0 AND "
4096 "d.refclassid = c.tableoid AND d.deptype = 'i') "
4097 "WHERE relkind IN ('%c', '%c', '%c', '%c') "
4101 RELKIND_RELATION, RELKIND_SEQUENCE,
4102 RELKIND_VIEW, RELKIND_COMPOSITE_TYPE);
4104 else if (g_fout->remoteVersion >= 70200)
4106 appendPQExpBuffer(query,
4107 "SELECT tableoid, oid, relname, relacl, relkind, "
4108 "0::oid AS relnamespace, "
4109 "(%s relowner) AS rolname, "
4110 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4111 "relhasindex, relhasrules, relhasoids, "
4112 "0 AS relfrozenxid, "
4115 "'p' AS relpersistence, "
4116 "NULL AS reloftype, "
4117 "NULL::oid AS owning_tab, "
4118 "NULL::int4 AS owning_col, "
4119 "NULL AS reltablespace, "
4120 "NULL AS reloptions, "
4121 "NULL AS toast_reloptions "
4123 "WHERE relkind IN ('%c', '%c', '%c') "
4126 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4128 else if (g_fout->remoteVersion >= 70100)
4130 /* all tables have oids in 7.1 */
4131 appendPQExpBuffer(query,
4132 "SELECT tableoid, oid, relname, relacl, relkind, "
4133 "0::oid AS relnamespace, "
4134 "(%s relowner) AS rolname, "
4135 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4136 "relhasindex, relhasrules, "
4137 "'t'::bool AS relhasoids, "
4138 "0 AS relfrozenxid, "
4141 "'p' AS relpersistence, "
4142 "NULL AS reloftype, "
4143 "NULL::oid AS owning_tab, "
4144 "NULL::int4 AS owning_col, "
4145 "NULL AS reltablespace, "
4146 "NULL AS reloptions, "
4147 "NULL AS toast_reloptions "
4149 "WHERE relkind IN ('%c', '%c', '%c') "
4152 RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW);
4157 * Before 7.1, view relkind was not set to 'v', so we must check if we
4158 * have a view by looking for a rule in pg_rewrite.
4160 appendPQExpBuffer(query,
4162 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4163 "oid, relname, relacl, "
4164 "CASE WHEN relhasrules and relkind = 'r' "
4165 " and EXISTS(SELECT rulename FROM pg_rewrite r WHERE "
4166 " r.ev_class = c.oid AND r.ev_type = '1') "
4167 "THEN '%c'::\"char\" "
4168 "ELSE relkind END AS relkind,"
4169 "0::oid AS relnamespace, "
4170 "(%s relowner) AS rolname, "
4171 "relchecks, (reltriggers <> 0) AS relhastriggers, "
4172 "relhasindex, relhasrules, "
4173 "'t'::bool AS relhasoids, "
4174 "0 as relfrozenxid, "
4177 "'p' AS relpersistence, "
4178 "NULL AS reloftype, "
4179 "NULL::oid AS owning_tab, "
4180 "NULL::int4 AS owning_col, "
4181 "NULL AS reltablespace, "
4182 "NULL AS reloptions, "
4183 "NULL AS toast_reloptions "
4185 "WHERE relkind IN ('%c', '%c') "
4189 RELKIND_RELATION, RELKIND_SEQUENCE);
4192 res = PQexec(g_conn, query->data);
4193 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4195 ntups = PQntuples(res);
4200 * Extract data from result and lock dumpable tables. We do the locking
4201 * before anything else, to minimize the window wherein a table could
4202 * disappear under us.
4204 * Note that we have to save info about all tables here, even when dumping
4205 * only one, because we don't yet know which tables might be inheritance
4206 * ancestors of the target table.
4208 tblinfo = (TableInfo *) pg_calloc(ntups, sizeof(TableInfo));
4210 i_reltableoid = PQfnumber(res, "tableoid");
4211 i_reloid = PQfnumber(res, "oid");
4212 i_relname = PQfnumber(res, "relname");
4213 i_relnamespace = PQfnumber(res, "relnamespace");
4214 i_relacl = PQfnumber(res, "relacl");
4215 i_relkind = PQfnumber(res, "relkind");
4216 i_rolname = PQfnumber(res, "rolname");
4217 i_relchecks = PQfnumber(res, "relchecks");
4218 i_relhastriggers = PQfnumber(res, "relhastriggers");
4219 i_relhasindex = PQfnumber(res, "relhasindex");
4220 i_relhasrules = PQfnumber(res, "relhasrules");
4221 i_relhasoids = PQfnumber(res, "relhasoids");
4222 i_relfrozenxid = PQfnumber(res, "relfrozenxid");
4223 i_toastoid = PQfnumber(res, "toid");
4224 i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
4225 i_relpersistence = PQfnumber(res, "relpersistence");
4226 i_owning_tab = PQfnumber(res, "owning_tab");
4227 i_owning_col = PQfnumber(res, "owning_col");
4228 i_reltablespace = PQfnumber(res, "reltablespace");
4229 i_reloptions = PQfnumber(res, "reloptions");
4230 i_toastreloptions = PQfnumber(res, "toast_reloptions");
4231 i_reloftype = PQfnumber(res, "reloftype");
4233 if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
4236 * Arrange to fail instead of waiting forever for a table lock.
4238 * NB: this coding assumes that the only queries issued within the
4239 * following loop are LOCK TABLEs; else the timeout may be undesirably
4240 * applied to other things too.
4242 resetPQExpBuffer(query);
4243 appendPQExpBuffer(query, "SET statement_timeout = ");
4244 appendStringLiteralConn(query, lockWaitTimeout, g_conn);
4245 do_sql_command(g_conn, query->data);
4248 for (i = 0; i < ntups; i++)
4250 tblinfo[i].dobj.objType = DO_TABLE;
4251 tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
4252 tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
4253 AssignDumpId(&tblinfo[i].dobj);
4254 tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
4255 tblinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)),
4256 tblinfo[i].dobj.catId.oid);
4257 tblinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
4258 tblinfo[i].relacl = pg_strdup(PQgetvalue(res, i, i_relacl));
4259 tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
4260 tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
4261 tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
4262 tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
4263 tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
4264 tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
4265 tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
4266 tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
4267 tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
4268 if (PQgetisnull(res, i, i_reloftype))
4269 tblinfo[i].reloftype = NULL;
4271 tblinfo[i].reloftype = pg_strdup(PQgetvalue(res, i, i_reloftype));
4272 tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
4273 if (PQgetisnull(res, i, i_owning_tab))
4275 tblinfo[i].owning_tab = InvalidOid;
4276 tblinfo[i].owning_col = 0;
4280 tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
4281 tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
4283 tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
4284 tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
4285 tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
4287 /* other fields were zeroed above */
4290 * Decide whether we want to dump this table.
4292 if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
4293 tblinfo[i].dobj.dump = false;
4295 selectDumpableTable(&tblinfo[i]);
4296 tblinfo[i].interesting = tblinfo[i].dobj.dump;
4299 * Read-lock target tables to make sure they aren't DROPPED or altered
4300 * in schema before we get around to dumping them.
4302 * Note that we don't explicitly lock parents of the target tables; we
4303 * assume our lock on the child is enough to prevent schema
4304 * alterations to parent tables.
4306 * NOTE: it'd be kinda nice to lock other relations too, not only
4307 * plain tables, but the backend doesn't presently allow that.
4309 if (tblinfo[i].dobj.dump && tblinfo[i].relkind == RELKIND_RELATION)
4311 resetPQExpBuffer(query);
4312 appendPQExpBuffer(query,
4313 "LOCK TABLE %s IN ACCESS SHARE MODE",
4314 fmtQualifiedId(tblinfo[i].dobj.namespace->dobj.name,
4315 tblinfo[i].dobj.name));
4316 do_sql_command(g_conn, query->data);
4319 /* Emit notice if join for owner failed */
4320 if (strlen(tblinfo[i].rolname) == 0)
4321 write_msg(NULL, "WARNING: owner of table \"%s\" appears to be invalid\n",
4322 tblinfo[i].dobj.name);
4325 if (lockWaitTimeout && g_fout->remoteVersion >= 70300)
4327 do_sql_command(g_conn, "SET statement_timeout = 0");
4333 * Force sequences that are "owned" by table columns to be dumped whenever
4334 * their owning table is being dumped.
4336 for (i = 0; i < ntups; i++)
4338 TableInfo *seqinfo = &tblinfo[i];
4341 if (!OidIsValid(seqinfo->owning_tab))
4342 continue; /* not an owned sequence */
4343 if (seqinfo->dobj.dump)
4344 continue; /* no need to search */
4346 /* can't use findTableByOid yet, unfortunately */
4347 for (j = 0; j < ntups; j++)
4349 if (tblinfo[j].dobj.catId.oid == seqinfo->owning_tab)
4351 if (tblinfo[j].dobj.dump)
4353 seqinfo->interesting = true;
4354 seqinfo->dobj.dump = true;
4361 destroyPQExpBuffer(query);
4368 * read all the inheritance information
4369 * from the system catalogs return them in the InhInfo* structure
4371 * numInherits is set to the number of pairs read in
4374 getInherits(int *numInherits)
4379 PQExpBuffer query = createPQExpBuffer();
4385 /* Make sure we are in proper schema */
4386 selectSourceSchema("pg_catalog");
4388 /* find all the inheritance information */
4390 appendPQExpBuffer(query, "SELECT inhrelid, inhparent FROM pg_inherits");
4392 res = PQexec(g_conn, query->data);
4393 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4395 ntups = PQntuples(res);
4397 *numInherits = ntups;
4399 inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
4401 i_inhrelid = PQfnumber(res, "inhrelid");
4402 i_inhparent = PQfnumber(res, "inhparent");
4404 for (i = 0; i < ntups; i++)
4406 inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
4407 inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
4412 destroyPQExpBuffer(query);
4419 * get information about every index on a dumpable table
4421 * Note: index data is not returned directly to the caller, but it
4422 * does get entered into the DumpableObject tables.
4425 getIndexes(TableInfo tblinfo[], int numTables)
4429 PQExpBuffer query = createPQExpBuffer();
4432 ConstraintInfo *constrinfo;
4451 for (i = 0; i < numTables; i++)
4453 TableInfo *tbinfo = &tblinfo[i];
4455 /* Only plain tables have indexes */
4456 if (tbinfo->relkind != RELKIND_RELATION || !tbinfo->hasindex)
4459 /* Ignore indexes of tables not to be dumped */
4460 if (!tbinfo->dobj.dump)
4464 write_msg(NULL, "reading indexes for table \"%s\"\n",
4467 /* Make sure we are in proper schema so indexdef is right */
4468 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4471 * The point of the messy-looking outer join is to find a constraint
4472 * that is related by an internal dependency link to the index. If we
4473 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
4474 * assume an index won't have more than one internal dependency.
4476 * As of 9.0 we don't need to look at pg_depend but can check for a
4477 * match to pg_constraint.conindid. The check on conrelid is
4478 * redundant but useful because that column is indexed while conindid
4481 resetPQExpBuffer(query);
4482 if (g_fout->remoteVersion >= 90000)
4484 appendPQExpBuffer(query,
4485 "SELECT t.tableoid, t.oid, "
4486 "t.relname AS indexname, "
4487 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4488 "t.relnatts AS indnkeys, "
4489 "i.indkey, i.indisclustered, "
4490 "c.contype, c.conname, "
4491 "c.condeferrable, c.condeferred, "
4492 "c.tableoid AS contableoid, "
4494 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
4495 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4496 "array_to_string(t.reloptions, ', ') AS options "
4497 "FROM pg_catalog.pg_index i "
4498 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4499 "LEFT JOIN pg_catalog.pg_constraint c "
4500 "ON (i.indrelid = c.conrelid AND "
4501 "i.indexrelid = c.conindid AND "
4502 "c.contype IN ('p','u','x')) "
4503 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4504 "ORDER BY indexname",
4505 tbinfo->dobj.catId.oid);
4507 else if (g_fout->remoteVersion >= 80200)
4509 appendPQExpBuffer(query,
4510 "SELECT t.tableoid, t.oid, "
4511 "t.relname AS indexname, "
4512 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4513 "t.relnatts AS indnkeys, "
4514 "i.indkey, i.indisclustered, "
4515 "c.contype, c.conname, "
4516 "c.condeferrable, c.condeferred, "
4517 "c.tableoid AS contableoid, "
4520 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4521 "array_to_string(t.reloptions, ', ') AS options "
4522 "FROM pg_catalog.pg_index i "
4523 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4524 "LEFT JOIN pg_catalog.pg_depend d "
4525 "ON (d.classid = t.tableoid "
4526 "AND d.objid = t.oid "
4527 "AND d.deptype = 'i') "
4528 "LEFT JOIN pg_catalog.pg_constraint c "
4529 "ON (d.refclassid = c.tableoid "
4530 "AND d.refobjid = c.oid) "
4531 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4532 "ORDER BY indexname",
4533 tbinfo->dobj.catId.oid);
4535 else if (g_fout->remoteVersion >= 80000)
4537 appendPQExpBuffer(query,
4538 "SELECT t.tableoid, t.oid, "
4539 "t.relname AS indexname, "
4540 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4541 "t.relnatts AS indnkeys, "
4542 "i.indkey, i.indisclustered, "
4543 "c.contype, c.conname, "
4544 "c.condeferrable, c.condeferred, "
4545 "c.tableoid AS contableoid, "
4548 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
4550 "FROM pg_catalog.pg_index i "
4551 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4552 "LEFT JOIN pg_catalog.pg_depend d "
4553 "ON (d.classid = t.tableoid "
4554 "AND d.objid = t.oid "
4555 "AND d.deptype = 'i') "
4556 "LEFT JOIN pg_catalog.pg_constraint c "
4557 "ON (d.refclassid = c.tableoid "
4558 "AND d.refobjid = c.oid) "
4559 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4560 "ORDER BY indexname",
4561 tbinfo->dobj.catId.oid);
4563 else if (g_fout->remoteVersion >= 70300)
4565 appendPQExpBuffer(query,
4566 "SELECT t.tableoid, t.oid, "
4567 "t.relname AS indexname, "
4568 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
4569 "t.relnatts AS indnkeys, "
4570 "i.indkey, i.indisclustered, "
4571 "c.contype, c.conname, "
4572 "c.condeferrable, c.condeferred, "
4573 "c.tableoid AS contableoid, "
4576 "NULL AS tablespace, "
4578 "FROM pg_catalog.pg_index i "
4579 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
4580 "LEFT JOIN pg_catalog.pg_depend d "
4581 "ON (d.classid = t.tableoid "
4582 "AND d.objid = t.oid "
4583 "AND d.deptype = 'i') "
4584 "LEFT JOIN pg_catalog.pg_constraint c "
4585 "ON (d.refclassid = c.tableoid "
4586 "AND d.refobjid = c.oid) "
4587 "WHERE i.indrelid = '%u'::pg_catalog.oid "
4588 "ORDER BY indexname",
4589 tbinfo->dobj.catId.oid);
4591 else if (g_fout->remoteVersion >= 70100)
4593 appendPQExpBuffer(query,
4594 "SELECT t.tableoid, t.oid, "
4595 "t.relname AS indexname, "
4596 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4597 "t.relnatts AS indnkeys, "
4598 "i.indkey, false AS indisclustered, "
4599 "CASE WHEN i.indisprimary THEN 'p'::char "
4600 "ELSE '0'::char END AS contype, "
4601 "t.relname AS conname, "
4602 "false AS condeferrable, "
4603 "false AS condeferred, "
4604 "0::oid AS contableoid, "
4607 "NULL AS tablespace, "
4609 "FROM pg_index i, pg_class t "
4610 "WHERE t.oid = i.indexrelid "
4611 "AND i.indrelid = '%u'::oid "
4612 "ORDER BY indexname",
4613 tbinfo->dobj.catId.oid);
4617 appendPQExpBuffer(query,
4619 "(SELECT oid FROM pg_class WHERE relname = 'pg_class') AS tableoid, "
4621 "t.relname AS indexname, "
4622 "pg_get_indexdef(i.indexrelid) AS indexdef, "
4623 "t.relnatts AS indnkeys, "
4624 "i.indkey, false AS indisclustered, "
4625 "CASE WHEN i.indisprimary THEN 'p'::char "
4626 "ELSE '0'::char END AS contype, "
4627 "t.relname AS conname, "
4628 "false AS condeferrable, "
4629 "false AS condeferred, "
4630 "0::oid AS contableoid, "
4633 "NULL AS tablespace, "
4635 "FROM pg_index i, pg_class t "
4636 "WHERE t.oid = i.indexrelid "
4637 "AND i.indrelid = '%u'::oid "
4638 "ORDER BY indexname",
4639 tbinfo->dobj.catId.oid);
4642 res = PQexec(g_conn, query->data);
4643 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4645 ntups = PQntuples(res);
4647 i_tableoid = PQfnumber(res, "tableoid");
4648 i_oid = PQfnumber(res, "oid");
4649 i_indexname = PQfnumber(res, "indexname");
4650 i_indexdef = PQfnumber(res, "indexdef");
4651 i_indnkeys = PQfnumber(res, "indnkeys");
4652 i_indkey = PQfnumber(res, "indkey");
4653 i_indisclustered = PQfnumber(res, "indisclustered");
4654 i_contype = PQfnumber(res, "contype");
4655 i_conname = PQfnumber(res, "conname");
4656 i_condeferrable = PQfnumber(res, "condeferrable");
4657 i_condeferred = PQfnumber(res, "condeferred");
4658 i_contableoid = PQfnumber(res, "contableoid");
4659 i_conoid = PQfnumber(res, "conoid");
4660 i_condef = PQfnumber(res, "condef");
4661 i_tablespace = PQfnumber(res, "tablespace");
4662 i_options = PQfnumber(res, "options");
4664 indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
4665 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4667 for (j = 0; j < ntups; j++)
4671 indxinfo[j].dobj.objType = DO_INDEX;
4672 indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
4673 indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4674 AssignDumpId(&indxinfo[j].dobj);
4675 indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
4676 indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4677 indxinfo[j].indextable = tbinfo;
4678 indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
4679 indxinfo[j].indnkeys = atoi(PQgetvalue(res, j, i_indnkeys));
4680 indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
4681 indxinfo[j].options = pg_strdup(PQgetvalue(res, j, i_options));
4684 * In pre-7.4 releases, indkeys may contain more entries than
4685 * indnkeys says (since indnkeys will be 1 for a functional
4686 * index). We don't actually care about this case since we don't
4687 * examine indkeys except for indexes associated with PRIMARY and
4688 * UNIQUE constraints, which are never functional indexes. But we
4689 * have to allocate enough space to keep parseOidArray from
4692 indxinfo[j].indkeys = (Oid *) pg_malloc(INDEX_MAX_KEYS * sizeof(Oid));
4693 parseOidArray(PQgetvalue(res, j, i_indkey),
4694 indxinfo[j].indkeys, INDEX_MAX_KEYS);
4695 indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
4696 contype = *(PQgetvalue(res, j, i_contype));
4698 if (contype == 'p' || contype == 'u' || contype == 'x')
4701 * If we found a constraint matching the index, create an
4704 * In a pre-7.3 database, we take this path iff the index was
4705 * marked indisprimary.
4707 constrinfo[j].dobj.objType = DO_CONSTRAINT;
4708 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4709 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4710 AssignDumpId(&constrinfo[j].dobj);
4711 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4712 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4713 constrinfo[j].contable = tbinfo;
4714 constrinfo[j].condomain = NULL;
4715 constrinfo[j].contype = contype;
4717 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4719 constrinfo[j].condef = NULL;
4720 constrinfo[j].confrelid = InvalidOid;
4721 constrinfo[j].conindex = indxinfo[j].dobj.dumpId;
4722 constrinfo[j].condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
4723 constrinfo[j].condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
4724 constrinfo[j].conislocal = true;
4725 constrinfo[j].separate = true;
4727 indxinfo[j].indexconstraint = constrinfo[j].dobj.dumpId;
4729 /* If pre-7.3 DB, better make sure table comes first */
4730 addObjectDependency(&constrinfo[j].dobj,
4731 tbinfo->dobj.dumpId);
4735 /* Plain secondary index */
4736 indxinfo[j].indexconstraint = 0;
4743 destroyPQExpBuffer(query);
4749 * Get info about constraints on dumpable tables.
4751 * Currently handles foreign keys only.
4752 * Unique and primary key constraints are handled with indexes,
4753 * while check constraints are processed in getTableAttrs().
4756 getConstraints(TableInfo tblinfo[], int numTables)
4760 ConstraintInfo *constrinfo;
4770 /* pg_constraint was created in 7.3, so nothing to do if older */
4771 if (g_fout->remoteVersion < 70300)
4774 query = createPQExpBuffer();
4776 for (i = 0; i < numTables; i++)
4778 TableInfo *tbinfo = &tblinfo[i];
4780 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
4784 write_msg(NULL, "reading foreign key constraints for table \"%s\"\n",
4788 * select table schema to ensure constraint expr is qualified if
4791 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
4793 resetPQExpBuffer(query);
4794 appendPQExpBuffer(query,
4795 "SELECT tableoid, oid, conname, confrelid, "
4796 "pg_catalog.pg_get_constraintdef(oid) AS condef "
4797 "FROM pg_catalog.pg_constraint "
4798 "WHERE conrelid = '%u'::pg_catalog.oid "
4799 "AND contype = 'f'",
4800 tbinfo->dobj.catId.oid);
4801 res = PQexec(g_conn, query->data);
4802 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4804 ntups = PQntuples(res);
4806 i_contableoid = PQfnumber(res, "tableoid");
4807 i_conoid = PQfnumber(res, "oid");
4808 i_conname = PQfnumber(res, "conname");
4809 i_confrelid = PQfnumber(res, "confrelid");
4810 i_condef = PQfnumber(res, "condef");
4812 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4814 for (j = 0; j < ntups; j++)
4816 constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
4817 constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
4818 constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
4819 AssignDumpId(&constrinfo[j].dobj);
4820 constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
4821 constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4822 constrinfo[j].contable = tbinfo;
4823 constrinfo[j].condomain = NULL;
4824 constrinfo[j].contype = 'f';
4825 constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
4826 constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
4827 constrinfo[j].conindex = 0;
4828 constrinfo[j].condeferrable = false;
4829 constrinfo[j].condeferred = false;
4830 constrinfo[j].conislocal = true;
4831 constrinfo[j].separate = true;
4837 destroyPQExpBuffer(query);
4841 * getDomainConstraints
4843 * Get info about constraints on a domain.
4846 getDomainConstraints(TypeInfo *tyinfo)
4849 ConstraintInfo *constrinfo;
4858 /* pg_constraint was created in 7.3, so nothing to do if older */
4859 if (g_fout->remoteVersion < 70300)
4863 * select appropriate schema to ensure names in constraint are properly
4866 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
4868 query = createPQExpBuffer();
4870 if (g_fout->remoteVersion >= 90100)
4871 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4872 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4874 "FROM pg_catalog.pg_constraint "
4875 "WHERE contypid = '%u'::pg_catalog.oid "
4877 tyinfo->dobj.catId.oid);
4879 else if (g_fout->remoteVersion >= 70400)
4880 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4881 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
4882 "true as convalidated "
4883 "FROM pg_catalog.pg_constraint "
4884 "WHERE contypid = '%u'::pg_catalog.oid "
4886 tyinfo->dobj.catId.oid);
4888 appendPQExpBuffer(query, "SELECT tableoid, oid, conname, "
4889 "'CHECK (' || consrc || ')' AS consrc, "
4890 "true as convalidated "
4891 "FROM pg_catalog.pg_constraint "
4892 "WHERE contypid = '%u'::pg_catalog.oid "
4894 tyinfo->dobj.catId.oid);
4896 res = PQexec(g_conn, query->data);
4897 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
4899 ntups = PQntuples(res);
4901 i_tableoid = PQfnumber(res, "tableoid");
4902 i_oid = PQfnumber(res, "oid");
4903 i_conname = PQfnumber(res, "conname");
4904 i_consrc = PQfnumber(res, "consrc");
4906 constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
4908 tyinfo->nDomChecks = ntups;
4909 tyinfo->domChecks = constrinfo;
4911 for (i = 0; i < ntups; i++)
4913 bool validated = PQgetvalue(res, i, 4)[0] == 't';
4915 constrinfo[i].dobj.objType = DO_CONSTRAINT;
4916 constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
4917 constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4918 AssignDumpId(&constrinfo[i].dobj);
4919 constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
4920 constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
4921 constrinfo[i].contable = NULL;
4922 constrinfo[i].condomain = tyinfo;
4923 constrinfo[i].contype = 'c';
4924 constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
4925 constrinfo[i].confrelid = InvalidOid;
4926 constrinfo[i].conindex = 0;
4927 constrinfo[i].condeferrable = false;
4928 constrinfo[i].condeferred = false;
4929 constrinfo[i].conislocal = true;
4931 constrinfo[i].separate = !validated;
4934 * Make the domain depend on the constraint, ensuring it won't be
4935 * output till any constraint dependencies are OK. If the constraint
4936 * has not been validated, it's going to be dumped after the domain
4937 * anyway, so this doesn't matter.
4940 addObjectDependency(&tyinfo->dobj,
4941 constrinfo[i].dobj.dumpId);
4946 destroyPQExpBuffer(query);
4951 * get basic information about every rule in the system
4953 * numRules is set to the number of rules read in
4956 getRules(int *numRules)
4961 PQExpBuffer query = createPQExpBuffer();
4971 /* Make sure we are in proper schema */
4972 selectSourceSchema("pg_catalog");
4974 if (g_fout->remoteVersion >= 80300)
4976 appendPQExpBuffer(query, "SELECT "
4977 "tableoid, oid, rulename, "
4978 "ev_class AS ruletable, ev_type, is_instead, "
4983 else if (g_fout->remoteVersion >= 70100)
4985 appendPQExpBuffer(query, "SELECT "
4986 "tableoid, oid, rulename, "
4987 "ev_class AS ruletable, ev_type, is_instead, "
4988 "'O'::char AS ev_enabled "
4994 appendPQExpBuffer(query, "SELECT "
4995 "(SELECT oid FROM pg_class WHERE relname = 'pg_rewrite') AS tableoid, "
4997 "ev_class AS ruletable, ev_type, is_instead, "
4998 "'O'::char AS ev_enabled "
5003 res = PQexec(g_conn, query->data);
5004 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5006 ntups = PQntuples(res);
5010 ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
5012 i_tableoid = PQfnumber(res, "tableoid");
5013 i_oid = PQfnumber(res, "oid");
5014 i_rulename = PQfnumber(res, "rulename");
5015 i_ruletable = PQfnumber(res, "ruletable");
5016 i_ev_type = PQfnumber(res, "ev_type");
5017 i_is_instead = PQfnumber(res, "is_instead");
5018 i_ev_enabled = PQfnumber(res, "ev_enabled");
5020 for (i = 0; i < ntups; i++)
5024 ruleinfo[i].dobj.objType = DO_RULE;
5025 ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5026 ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5027 AssignDumpId(&ruleinfo[i].dobj);
5028 ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
5029 ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
5030 ruleinfo[i].ruletable = findTableByOid(ruletableoid);
5031 if (ruleinfo[i].ruletable == NULL)
5033 write_msg(NULL, "failed sanity check, parent table OID %u of pg_rewrite entry OID %u not found\n",
5035 ruleinfo[i].dobj.catId.oid);
5038 ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
5039 ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
5040 ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
5041 ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
5042 ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
5043 if (ruleinfo[i].ruletable)
5046 * If the table is a view, force its ON SELECT rule to be sorted
5047 * before the view itself --- this ensures that any dependencies
5048 * for the rule affect the table's positioning. Other rules are
5049 * forced to appear after their table.
5051 if (ruleinfo[i].ruletable->relkind == RELKIND_VIEW &&
5052 ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
5054 addObjectDependency(&ruleinfo[i].ruletable->dobj,
5055 ruleinfo[i].dobj.dumpId);
5056 /* We'll merge the rule into CREATE VIEW, if possible */
5057 ruleinfo[i].separate = false;
5061 addObjectDependency(&ruleinfo[i].dobj,
5062 ruleinfo[i].ruletable->dobj.dumpId);
5063 ruleinfo[i].separate = true;
5067 ruleinfo[i].separate = true;
5072 destroyPQExpBuffer(query);
5079 * get information about every trigger on a dumpable table
5081 * Note: trigger data is not returned directly to the caller, but it
5082 * does get entered into the DumpableObject tables.
5085 getTriggers(TableInfo tblinfo[], int numTables)
5089 PQExpBuffer query = createPQExpBuffer();
5091 TriggerInfo *tginfo;
5109 for (i = 0; i < numTables; i++)
5111 TableInfo *tbinfo = &tblinfo[i];
5113 if (!tbinfo->hastriggers || !tbinfo->dobj.dump)
5117 write_msg(NULL, "reading triggers for table \"%s\"\n",
5121 * select table schema to ensure regproc name is qualified if needed
5123 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
5125 resetPQExpBuffer(query);
5126 if (g_fout->remoteVersion >= 90000)
5129 * NB: think not to use pretty=true in pg_get_triggerdef. It
5130 * could result in non-forward-compatible dumps of WHEN clauses
5131 * due to under-parenthesization.
5133 appendPQExpBuffer(query,
5135 "tgfoid::pg_catalog.regproc AS tgfname, "
5136 "pg_catalog.pg_get_triggerdef(oid, false) AS tgdef, "
5137 "tgenabled, tableoid, oid "
5138 "FROM pg_catalog.pg_trigger t "
5139 "WHERE tgrelid = '%u'::pg_catalog.oid "
5140 "AND NOT tgisinternal",
5141 tbinfo->dobj.catId.oid);
5143 else if (g_fout->remoteVersion >= 80300)
5146 * We ignore triggers that are tied to a foreign-key constraint
5148 appendPQExpBuffer(query,
5150 "tgfoid::pg_catalog.regproc AS tgfname, "
5151 "tgtype, tgnargs, tgargs, tgenabled, "
5152 "tgisconstraint, tgconstrname, tgdeferrable, "
5153 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5154 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5155 "FROM pg_catalog.pg_trigger t "
5156 "WHERE tgrelid = '%u'::pg_catalog.oid "
5157 "AND tgconstraint = 0",
5158 tbinfo->dobj.catId.oid);
5160 else if (g_fout->remoteVersion >= 70300)
5163 * We ignore triggers that are tied to a foreign-key constraint,
5164 * but in these versions we have to grovel through pg_constraint
5167 appendPQExpBuffer(query,
5169 "tgfoid::pg_catalog.regproc AS tgfname, "
5170 "tgtype, tgnargs, tgargs, tgenabled, "
5171 "tgisconstraint, tgconstrname, tgdeferrable, "
5172 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5173 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
5174 "FROM pg_catalog.pg_trigger t "
5175 "WHERE tgrelid = '%u'::pg_catalog.oid "
5176 "AND (NOT tgisconstraint "
5178 " (SELECT 1 FROM pg_catalog.pg_depend d "
5179 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
5180 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
5181 tbinfo->dobj.catId.oid);
5183 else if (g_fout->remoteVersion >= 70100)
5185 appendPQExpBuffer(query,
5186 "SELECT tgname, tgfoid::regproc AS tgfname, "
5187 "tgtype, tgnargs, tgargs, tgenabled, "
5188 "tgisconstraint, tgconstrname, tgdeferrable, "
5189 "tgconstrrelid, tginitdeferred, tableoid, oid, "
5190 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5191 " AS tgconstrrelname "
5193 "WHERE tgrelid = '%u'::oid",
5194 tbinfo->dobj.catId.oid);
5198 appendPQExpBuffer(query,
5199 "SELECT tgname, tgfoid::regproc AS tgfname, "
5200 "tgtype, tgnargs, tgargs, tgenabled, "
5201 "tgisconstraint, tgconstrname, tgdeferrable, "
5202 "tgconstrrelid, tginitdeferred, "
5203 "(SELECT oid FROM pg_class WHERE relname = 'pg_trigger') AS tableoid, "
5205 "(SELECT relname FROM pg_class WHERE oid = tgconstrrelid) "
5206 " AS tgconstrrelname "
5208 "WHERE tgrelid = '%u'::oid",
5209 tbinfo->dobj.catId.oid);
5211 res = PQexec(g_conn, query->data);
5212 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5214 ntups = PQntuples(res);
5216 i_tableoid = PQfnumber(res, "tableoid");
5217 i_oid = PQfnumber(res, "oid");
5218 i_tgname = PQfnumber(res, "tgname");
5219 i_tgfname = PQfnumber(res, "tgfname");
5220 i_tgtype = PQfnumber(res, "tgtype");
5221 i_tgnargs = PQfnumber(res, "tgnargs");
5222 i_tgargs = PQfnumber(res, "tgargs");
5223 i_tgisconstraint = PQfnumber(res, "tgisconstraint");
5224 i_tgconstrname = PQfnumber(res, "tgconstrname");
5225 i_tgconstrrelid = PQfnumber(res, "tgconstrrelid");
5226 i_tgconstrrelname = PQfnumber(res, "tgconstrrelname");
5227 i_tgenabled = PQfnumber(res, "tgenabled");
5228 i_tgdeferrable = PQfnumber(res, "tgdeferrable");
5229 i_tginitdeferred = PQfnumber(res, "tginitdeferred");
5230 i_tgdef = PQfnumber(res, "tgdef");
5232 tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
5234 for (j = 0; j < ntups; j++)
5236 tginfo[j].dobj.objType = DO_TRIGGER;
5237 tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
5238 tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
5239 AssignDumpId(&tginfo[j].dobj);
5240 tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
5241 tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
5242 tginfo[j].tgtable = tbinfo;
5243 tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
5246 tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
5248 /* remaining fields are not valid if we have tgdef */
5249 tginfo[j].tgfname = NULL;
5250 tginfo[j].tgtype = 0;
5251 tginfo[j].tgnargs = 0;
5252 tginfo[j].tgargs = NULL;
5253 tginfo[j].tgisconstraint = false;
5254 tginfo[j].tgdeferrable = false;
5255 tginfo[j].tginitdeferred = false;
5256 tginfo[j].tgconstrname = NULL;
5257 tginfo[j].tgconstrrelid = InvalidOid;
5258 tginfo[j].tgconstrrelname = NULL;
5262 tginfo[j].tgdef = NULL;
5264 tginfo[j].tgfname = pg_strdup(PQgetvalue(res, j, i_tgfname));
5265 tginfo[j].tgtype = atoi(PQgetvalue(res, j, i_tgtype));
5266 tginfo[j].tgnargs = atoi(PQgetvalue(res, j, i_tgnargs));
5267 tginfo[j].tgargs = pg_strdup(PQgetvalue(res, j, i_tgargs));
5268 tginfo[j].tgisconstraint = *(PQgetvalue(res, j, i_tgisconstraint)) == 't';
5269 tginfo[j].tgdeferrable = *(PQgetvalue(res, j, i_tgdeferrable)) == 't';
5270 tginfo[j].tginitdeferred = *(PQgetvalue(res, j, i_tginitdeferred)) == 't';
5272 if (tginfo[j].tgisconstraint)
5274 tginfo[j].tgconstrname = pg_strdup(PQgetvalue(res, j, i_tgconstrname));
5275 tginfo[j].tgconstrrelid = atooid(PQgetvalue(res, j, i_tgconstrrelid));
5276 if (OidIsValid(tginfo[j].tgconstrrelid))
5278 if (PQgetisnull(res, j, i_tgconstrrelname))
5280 write_msg(NULL, "query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)\n",
5281 tginfo[j].dobj.name, tbinfo->dobj.name,
5282 tginfo[j].tgconstrrelid);
5285 tginfo[j].tgconstrrelname = pg_strdup(PQgetvalue(res, j, i_tgconstrrelname));
5288 tginfo[j].tgconstrrelname = NULL;
5292 tginfo[j].tgconstrname = NULL;
5293 tginfo[j].tgconstrrelid = InvalidOid;
5294 tginfo[j].tgconstrrelname = NULL;
5302 destroyPQExpBuffer(query);
5307 * get basic information about every procedural language in the system
5309 * numProcLangs is set to the number of langs read in
5311 * NB: this must run after getFuncs() because we assume we can do
5315 getProcLangs(int *numProcLangs)
5320 PQExpBuffer query = createPQExpBuffer();
5321 ProcLangInfo *planginfo;
5326 int i_lanplcallfoid;
5332 /* Make sure we are in proper schema */
5333 selectSourceSchema("pg_catalog");
5335 if (g_fout->remoteVersion >= 90000)
5337 /* pg_language has a laninline column */
5338 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5339 "lanname, lanpltrusted, lanplcallfoid, "
5340 "laninline, lanvalidator, lanacl, "
5341 "(%s lanowner) AS lanowner "
5347 else if (g_fout->remoteVersion >= 80300)
5349 /* pg_language has a lanowner column */
5350 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5351 "lanname, lanpltrusted, lanplcallfoid, "
5352 "lanvalidator, lanacl, "
5353 "(%s lanowner) AS lanowner "
5359 else if (g_fout->remoteVersion >= 80100)
5361 /* Languages are owned by the bootstrap superuser, OID 10 */
5362 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5363 "(%s '10') AS lanowner "
5369 else if (g_fout->remoteVersion >= 70400)
5371 /* Languages are owned by the bootstrap superuser, sysid 1 */
5372 appendPQExpBuffer(query, "SELECT tableoid, oid, *, "
5373 "(%s '1') AS lanowner "
5379 else if (g_fout->remoteVersion >= 70100)
5381 /* No clear notion of an owner at all before 7.4 ... */
5382 appendPQExpBuffer(query, "SELECT tableoid, oid, * FROM pg_language "
5388 appendPQExpBuffer(query, "SELECT "
5389 "(SELECT oid FROM pg_class WHERE relname = 'pg_language') AS tableoid, "
5390 "oid, * FROM pg_language "
5395 res = PQexec(g_conn, query->data);
5396 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5398 ntups = PQntuples(res);
5400 *numProcLangs = ntups;
5402 planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
5404 i_tableoid = PQfnumber(res, "tableoid");
5405 i_oid = PQfnumber(res, "oid");
5406 i_lanname = PQfnumber(res, "lanname");
5407 i_lanpltrusted = PQfnumber(res, "lanpltrusted");
5408 i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
5409 /* these may fail and return -1: */
5410 i_laninline = PQfnumber(res, "laninline");
5411 i_lanvalidator = PQfnumber(res, "lanvalidator");
5412 i_lanacl = PQfnumber(res, "lanacl");
5413 i_lanowner = PQfnumber(res, "lanowner");
5415 for (i = 0; i < ntups; i++)
5417 planginfo[i].dobj.objType = DO_PROCLANG;
5418 planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5419 planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5420 AssignDumpId(&planginfo[i].dobj);
5422 planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
5423 planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
5424 planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
5425 if (i_laninline >= 0)
5426 planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
5428 planginfo[i].laninline = InvalidOid;
5429 if (i_lanvalidator >= 0)
5430 planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
5432 planginfo[i].lanvalidator = InvalidOid;
5434 planginfo[i].lanacl = pg_strdup(PQgetvalue(res, i, i_lanacl));
5436 planginfo[i].lanacl = pg_strdup("{=U}");
5437 if (i_lanowner >= 0)
5438 planginfo[i].lanowner = pg_strdup(PQgetvalue(res, i, i_lanowner));
5440 planginfo[i].lanowner = pg_strdup("");
5442 if (g_fout->remoteVersion < 70300)
5445 * We need to make a dependency to ensure the function will be
5446 * dumped first. (In 7.3 and later the regular dependency
5447 * mechanism will handle this for us.)
5449 FuncInfo *funcInfo = findFuncByOid(planginfo[i].lanplcallfoid);
5452 addObjectDependency(&planginfo[i].dobj,
5453 funcInfo->dobj.dumpId);
5459 destroyPQExpBuffer(query);
5466 * get basic information about every cast in the system
5468 * numCasts is set to the number of casts read in
5471 getCasts(int *numCasts)
5476 PQExpBuffer query = createPQExpBuffer();
5486 /* Make sure we are in proper schema */
5487 selectSourceSchema("pg_catalog");
5489 if (g_fout->remoteVersion >= 80400)
5491 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5492 "castsource, casttarget, castfunc, castcontext, "
5494 "FROM pg_cast ORDER BY 3,4");
5496 else if (g_fout->remoteVersion >= 70300)
5498 appendPQExpBuffer(query, "SELECT tableoid, oid, "
5499 "castsource, casttarget, castfunc, castcontext, "
5500 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
5501 "FROM pg_cast ORDER BY 3,4");
5505 appendPQExpBuffer(query, "SELECT 0 AS tableoid, p.oid, "
5506 "t1.oid AS castsource, t2.oid AS casttarget, "
5507 "p.oid AS castfunc, 'e' AS castcontext, "
5508 "'f' AS castmethod "
5509 "FROM pg_type t1, pg_type t2, pg_proc p "
5510 "WHERE p.pronargs = 1 AND "
5511 "p.proargtypes[0] = t1.oid AND "
5512 "p.prorettype = t2.oid AND p.proname = t2.typname "
5516 res = PQexec(g_conn, query->data);
5517 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
5519 ntups = PQntuples(res);
5523 castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
5525 i_tableoid = PQfnumber(res, "tableoid");
5526 i_oid = PQfnumber(res, "oid");
5527 i_castsource = PQfnumber(res, "castsource");
5528 i_casttarget = PQfnumber(res, "casttarget");
5529 i_castfunc = PQfnumber(res, "castfunc");
5530 i_castcontext = PQfnumber(res, "castcontext");
5531 i_castmethod = PQfnumber(res, "castmethod");
5533 for (i = 0; i < ntups; i++)
5535 PQExpBufferData namebuf;
5536 TypeInfo *sTypeInfo;
5537 TypeInfo *tTypeInfo;
5539 castinfo[i].dobj.objType = DO_CAST;
5540 castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5541 castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5542 AssignDumpId(&castinfo[i].dobj);
5543 castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
5544 castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
5545 castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
5546 castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
5547 castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
5550 * Try to name cast as concatenation of typnames. This is only used
5551 * for purposes of sorting. If we fail to find either type, the name
5552 * will be an empty string.
5554 initPQExpBuffer(&namebuf);
5555 sTypeInfo = findTypeByOid(castinfo[i].castsource);
5556 tTypeInfo = findTypeByOid(castinfo[i].casttarget);
5557 if (sTypeInfo && tTypeInfo)
5558 appendPQExpBuffer(&namebuf, "%s %s",
5559 sTypeInfo->dobj.name, tTypeInfo->dobj.name);
5560 castinfo[i].dobj.name = namebuf.data;
5562 if (OidIsValid(castinfo[i].castfunc))
5565 * We need to make a dependency to ensure the function will be
5566 * dumped first. (In 7.3 and later the regular dependency
5567 * mechanism will handle this for us.)
5571 funcInfo = findFuncByOid(castinfo[i].castfunc);
5573 addObjectDependency(&castinfo[i].dobj,
5574 funcInfo->dobj.dumpId);
5580 destroyPQExpBuffer(query);
5587 * for each interesting table, read info about its attributes
5588 * (names, types, default values, CHECK constraints, etc)
5590 * This is implemented in a very inefficient way right now, looping
5591 * through the tblinfo and doing a join per table to find the attrs and their
5592 * types. However, because we want type names and so forth to be named
5593 * relative to the schema of each table, we couldn't do it in just one
5594 * query. (Maybe one query per schema?)
5599 getTableAttrs(TableInfo *tblinfo, int numTables)
5603 PQExpBuffer q = createPQExpBuffer();
5608 int i_attstattarget;
5619 int i_attfdwoptions;
5624 for (i = 0; i < numTables; i++)
5626 TableInfo *tbinfo = &tblinfo[i];
5628 /* Don't bother to collect info for sequences */
5629 if (tbinfo->relkind == RELKIND_SEQUENCE)
5632 /* Don't bother with uninteresting tables, either */
5633 if (!tbinfo->interesting)
5637 * Make sure we are in proper schema for this table; this allows
5638 * correct retrieval of formatted type names and default exprs
5640 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
5642 /* find all the user attributes and their types */
5645 * we must read the attribute names in attribute number order! because
5646 * we will use the attnum to index into the attnames array later. We
5647 * actually ask to order by "attrelid, attnum" because (at least up to
5648 * 7.3) the planner is not smart enough to realize it needn't re-sort
5649 * the output of an indexscan on pg_attribute_relid_attnum_index.
5652 write_msg(NULL, "finding the columns and types of table \"%s\"\n",
5655 resetPQExpBuffer(q);
5657 if (g_fout->remoteVersion >= 90200)
5660 * attfdwoptions is new in 9.2.
5662 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5663 "a.attstattarget, a.attstorage, t.typstorage, "
5664 "a.attnotnull, a.atthasdef, a.attisdropped, "
5665 "a.attlen, a.attalign, a.attislocal, "
5666 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5667 "array_to_string(a.attoptions, ', ') AS attoptions, "
5668 "CASE WHEN a.attcollation <> t.typcollation "
5669 "THEN a.attcollation ELSE 0 END AS attcollation, "
5670 "pg_catalog.array_to_string(ARRAY("
5671 "SELECT pg_catalog.quote_ident(option_name) || "
5672 "' ' || pg_catalog.quote_literal(option_value) "
5673 "FROM pg_catalog.pg_options_to_table(attfdwoptions)"
5674 "), ', ') AS attfdwoptions "
5675 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5676 "ON a.atttypid = t.oid "
5677 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5678 "AND a.attnum > 0::pg_catalog.int2 "
5679 "ORDER BY a.attrelid, a.attnum",
5680 tbinfo->dobj.catId.oid);
5682 else if (g_fout->remoteVersion >= 90100)
5685 * attcollation is new in 9.1. Since we only want to dump COLLATE
5686 * clauses for attributes whose collation is different from their
5687 * type's default, we use a CASE here to suppress uninteresting
5688 * attcollations cheaply.
5690 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5691 "a.attstattarget, a.attstorage, t.typstorage, "
5692 "a.attnotnull, a.atthasdef, a.attisdropped, "
5693 "a.attlen, a.attalign, a.attislocal, "
5694 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5695 "array_to_string(a.attoptions, ', ') AS attoptions, "
5696 "CASE WHEN a.attcollation <> t.typcollation "
5697 "THEN a.attcollation ELSE 0 END AS attcollation, "
5698 "NULL AS attfdwoptions "
5699 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5700 "ON a.atttypid = t.oid "
5701 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5702 "AND a.attnum > 0::pg_catalog.int2 "
5703 "ORDER BY a.attrelid, a.attnum",
5704 tbinfo->dobj.catId.oid);
5706 else if (g_fout->remoteVersion >= 90000)
5708 /* attoptions is new in 9.0 */
5709 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5710 "a.attstattarget, a.attstorage, t.typstorage, "
5711 "a.attnotnull, a.atthasdef, a.attisdropped, "
5712 "a.attlen, a.attalign, a.attislocal, "
5713 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5714 "array_to_string(a.attoptions, ', ') AS attoptions, "
5715 "0 AS attcollation, "
5716 "NULL AS attfdwoptions "
5717 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5718 "ON a.atttypid = t.oid "
5719 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5720 "AND a.attnum > 0::pg_catalog.int2 "
5721 "ORDER BY a.attrelid, a.attnum",
5722 tbinfo->dobj.catId.oid);
5724 else if (g_fout->remoteVersion >= 70300)
5726 /* need left join here to not fail on dropped columns ... */
5727 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5728 "a.attstattarget, a.attstorage, t.typstorage, "
5729 "a.attnotnull, a.atthasdef, a.attisdropped, "
5730 "a.attlen, a.attalign, a.attislocal, "
5731 "pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, "
5732 "'' AS attoptions, 0 AS attcollation, "
5733 "NULL AS attfdwoptions "
5734 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
5735 "ON a.atttypid = t.oid "
5736 "WHERE a.attrelid = '%u'::pg_catalog.oid "
5737 "AND a.attnum > 0::pg_catalog.int2 "
5738 "ORDER BY a.attrelid, a.attnum",
5739 tbinfo->dobj.catId.oid);
5741 else if (g_fout->remoteVersion >= 70100)
5744 * attstattarget doesn't exist in 7.1. It does exist in 7.2, but
5745 * we don't dump it because we can't tell whether it's been
5746 * explicitly set or was just a default.
5748 appendPQExpBuffer(q, "SELECT a.attnum, a.attname, a.atttypmod, "
5749 "-1 AS attstattarget, a.attstorage, "
5750 "t.typstorage, a.attnotnull, a.atthasdef, "
5751 "false AS attisdropped, a.attlen, "
5752 "a.attalign, false AS attislocal, "
5753 "format_type(t.oid,a.atttypmod) AS atttypname, "
5754 "'' AS attoptions, 0 AS attcollation, "
5755 "NULL AS attfdwoptions "
5756 "FROM pg_attribute a LEFT JOIN pg_type t "
5757 "ON a.atttypid = t.oid "
5758 "WHERE a.attrelid = '%u'::oid "
5759 "AND a.attnum > 0::int2 "
5760 "ORDER BY a.attrelid, a.attnum",
5761 tbinfo->dobj.catId.oid);
5765 /* format_type not available before 7.1 */
5766 appendPQExpBuffer(q, "SELECT attnum, attname, atttypmod, "
5767 "-1 AS attstattarget, "
5768 "attstorage, attstorage AS typstorage, "
5769 "attnotnull, atthasdef, false AS attisdropped, "
5770 "attlen, attalign, "
5771 "false AS attislocal, "
5772 "(SELECT typname FROM pg_type WHERE oid = atttypid) AS atttypname, "
5773 "'' AS attoptions, 0 AS attcollation, "
5774 "NULL AS attfdwoptions "
5775 "FROM pg_attribute a "
5776 "WHERE attrelid = '%u'::oid "
5777 "AND attnum > 0::int2 "
5778 "ORDER BY attrelid, attnum",
5779 tbinfo->dobj.catId.oid);
5782 res = PQexec(g_conn, q->data);
5783 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5785 ntups = PQntuples(res);
5787 i_attnum = PQfnumber(res, "attnum");
5788 i_attname = PQfnumber(res, "attname");
5789 i_atttypname = PQfnumber(res, "atttypname");
5790 i_atttypmod = PQfnumber(res, "atttypmod");
5791 i_attstattarget = PQfnumber(res, "attstattarget");
5792 i_attstorage = PQfnumber(res, "attstorage");
5793 i_typstorage = PQfnumber(res, "typstorage");
5794 i_attnotnull = PQfnumber(res, "attnotnull");
5795 i_atthasdef = PQfnumber(res, "atthasdef");
5796 i_attisdropped = PQfnumber(res, "attisdropped");
5797 i_attlen = PQfnumber(res, "attlen");
5798 i_attalign = PQfnumber(res, "attalign");
5799 i_attislocal = PQfnumber(res, "attislocal");
5800 i_attoptions = PQfnumber(res, "attoptions");
5801 i_attcollation = PQfnumber(res, "attcollation");
5802 i_attfdwoptions = PQfnumber(res, "attfdwoptions");
5804 tbinfo->numatts = ntups;
5805 tbinfo->attnames = (char **) pg_malloc(ntups * sizeof(char *));
5806 tbinfo->atttypnames = (char **) pg_malloc(ntups * sizeof(char *));
5807 tbinfo->atttypmod = (int *) pg_malloc(ntups * sizeof(int));
5808 tbinfo->attstattarget = (int *) pg_malloc(ntups * sizeof(int));
5809 tbinfo->attstorage = (char *) pg_malloc(ntups * sizeof(char));
5810 tbinfo->typstorage = (char *) pg_malloc(ntups * sizeof(char));
5811 tbinfo->attisdropped = (bool *) pg_malloc(ntups * sizeof(bool));
5812 tbinfo->attlen = (int *) pg_malloc(ntups * sizeof(int));
5813 tbinfo->attalign = (char *) pg_malloc(ntups * sizeof(char));
5814 tbinfo->attislocal = (bool *) pg_malloc(ntups * sizeof(bool));
5815 tbinfo->notnull = (bool *) pg_malloc(ntups * sizeof(bool));
5816 tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(ntups * sizeof(AttrDefInfo *));
5817 tbinfo->attoptions = (char **) pg_malloc(ntups * sizeof(char *));
5818 tbinfo->attcollation = (Oid *) pg_malloc(ntups * sizeof(Oid));
5819 tbinfo->attfdwoptions = (char **) pg_malloc(ntups * sizeof(char *));
5820 tbinfo->inhAttrs = (bool *) pg_malloc(ntups * sizeof(bool));
5821 tbinfo->inhAttrDef = (bool *) pg_malloc(ntups * sizeof(bool));
5822 tbinfo->inhNotNull = (bool *) pg_malloc(ntups * sizeof(bool));
5823 hasdefaults = false;
5825 for (j = 0; j < ntups; j++)
5827 if (j + 1 != atoi(PQgetvalue(res, j, i_attnum)))
5829 write_msg(NULL, "invalid column numbering in table \"%s\"\n",
5833 tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, j, i_attname));
5834 tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, j, i_atttypname));
5835 tbinfo->atttypmod[j] = atoi(PQgetvalue(res, j, i_atttypmod));
5836 tbinfo->attstattarget[j] = atoi(PQgetvalue(res, j, i_attstattarget));
5837 tbinfo->attstorage[j] = *(PQgetvalue(res, j, i_attstorage));
5838 tbinfo->typstorage[j] = *(PQgetvalue(res, j, i_typstorage));
5839 tbinfo->attisdropped[j] = (PQgetvalue(res, j, i_attisdropped)[0] == 't');
5840 tbinfo->attlen[j] = atoi(PQgetvalue(res, j, i_attlen));
5841 tbinfo->attalign[j] = *(PQgetvalue(res, j, i_attalign));
5842 tbinfo->attislocal[j] = (PQgetvalue(res, j, i_attislocal)[0] == 't');
5843 tbinfo->notnull[j] = (PQgetvalue(res, j, i_attnotnull)[0] == 't');
5844 tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, j, i_attoptions));
5845 tbinfo->attcollation[j] = atooid(PQgetvalue(res, j, i_attcollation));
5846 tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, j, i_attfdwoptions));
5847 tbinfo->attrdefs[j] = NULL; /* fix below */
5848 if (PQgetvalue(res, j, i_atthasdef)[0] == 't')
5850 /* these flags will be set in flagInhAttrs() */
5851 tbinfo->inhAttrs[j] = false;
5852 tbinfo->inhAttrDef[j] = false;
5853 tbinfo->inhNotNull[j] = false;
5859 * Get info about column defaults
5863 AttrDefInfo *attrdefs;
5867 write_msg(NULL, "finding default expressions of table \"%s\"\n",
5870 resetPQExpBuffer(q);
5871 if (g_fout->remoteVersion >= 70300)
5873 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, "
5874 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
5875 "FROM pg_catalog.pg_attrdef "
5876 "WHERE adrelid = '%u'::pg_catalog.oid",
5877 tbinfo->dobj.catId.oid);
5879 else if (g_fout->remoteVersion >= 70200)
5881 /* 7.2 did not have OIDs in pg_attrdef */
5882 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, adnum, "
5883 "pg_get_expr(adbin, adrelid) AS adsrc "
5885 "WHERE adrelid = '%u'::oid",
5886 tbinfo->dobj.catId.oid);
5888 else if (g_fout->remoteVersion >= 70100)
5890 /* no pg_get_expr, so must rely on adsrc */
5891 appendPQExpBuffer(q, "SELECT tableoid, oid, adnum, adsrc "
5893 "WHERE adrelid = '%u'::oid",
5894 tbinfo->dobj.catId.oid);
5898 /* no pg_get_expr, no tableoid either */
5899 appendPQExpBuffer(q, "SELECT "
5900 "(SELECT oid FROM pg_class WHERE relname = 'pg_attrdef') AS tableoid, "
5901 "oid, adnum, adsrc "
5903 "WHERE adrelid = '%u'::oid",
5904 tbinfo->dobj.catId.oid);
5906 res = PQexec(g_conn, q->data);
5907 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
5909 numDefaults = PQntuples(res);
5910 attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
5912 for (j = 0; j < numDefaults; j++)
5916 attrdefs[j].dobj.objType = DO_ATTRDEF;
5917 attrdefs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
5918 attrdefs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
5919 AssignDumpId(&attrdefs[j].dobj);
5920 attrdefs[j].adtable = tbinfo;
5921 attrdefs[j].adnum = adnum = atoi(PQgetvalue(res, j, 2));
5922 attrdefs[j].adef_expr = pg_strdup(PQgetvalue(res, j, 3));
5924 attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
5925 attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
5927 attrdefs[j].dobj.dump = tbinfo->dobj.dump;
5930 * Defaults on a VIEW must always be dumped as separate ALTER
5931 * TABLE commands. Defaults on regular tables are dumped as
5932 * part of the CREATE TABLE if possible. To check if it's
5933 * safe, we mark the default as needing to appear before the
5936 if (tbinfo->relkind == RELKIND_VIEW)
5938 attrdefs[j].separate = true;
5939 /* needed in case pre-7.3 DB: */
5940 addObjectDependency(&attrdefs[j].dobj,
5941 tbinfo->dobj.dumpId);
5945 attrdefs[j].separate = false;
5946 addObjectDependency(&tbinfo->dobj,
5947 attrdefs[j].dobj.dumpId);
5950 if (adnum <= 0 || adnum > ntups)
5952 write_msg(NULL, "invalid adnum value %d for table \"%s\"\n",
5953 adnum, tbinfo->dobj.name);
5956 tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
5962 * Get info about table CHECK constraints
5964 if (tbinfo->ncheck > 0)
5966 ConstraintInfo *constrs;
5970 write_msg(NULL, "finding check constraints for table \"%s\"\n",
5973 resetPQExpBuffer(q);
5974 if (g_fout->remoteVersion >= 90100)
5976 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5977 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5978 "conislocal, convalidated "
5979 "FROM pg_catalog.pg_constraint "
5980 "WHERE conrelid = '%u'::pg_catalog.oid "
5981 " AND contype = 'c' "
5983 tbinfo->dobj.catId.oid);
5985 else if (g_fout->remoteVersion >= 80400)
5987 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5988 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
5989 "conislocal, true AS convalidated "
5990 "FROM pg_catalog.pg_constraint "
5991 "WHERE conrelid = '%u'::pg_catalog.oid "
5992 " AND contype = 'c' "
5994 tbinfo->dobj.catId.oid);
5996 else if (g_fout->remoteVersion >= 70400)
5998 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
5999 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
6000 "true AS conislocal, true AS convalidated "
6001 "FROM pg_catalog.pg_constraint "
6002 "WHERE conrelid = '%u'::pg_catalog.oid "
6003 " AND contype = 'c' "
6005 tbinfo->dobj.catId.oid);
6007 else if (g_fout->remoteVersion >= 70300)
6009 /* no pg_get_constraintdef, must use consrc */
6010 appendPQExpBuffer(q, "SELECT tableoid, oid, conname, "
6011 "'CHECK (' || consrc || ')' AS consrc, "
6012 "true AS conislocal, true AS convalidated "
6013 "FROM pg_catalog.pg_constraint "
6014 "WHERE conrelid = '%u'::pg_catalog.oid "
6015 " AND contype = 'c' "
6017 tbinfo->dobj.catId.oid);
6019 else if (g_fout->remoteVersion >= 70200)
6021 /* 7.2 did not have OIDs in pg_relcheck */
6022 appendPQExpBuffer(q, "SELECT tableoid, 0 AS oid, "
6023 "rcname AS conname, "
6024 "'CHECK (' || rcsrc || ')' AS consrc, "
6025 "true AS conislocal, true AS convalidated "
6027 "WHERE rcrelid = '%u'::oid "
6029 tbinfo->dobj.catId.oid);
6031 else if (g_fout->remoteVersion >= 70100)
6033 appendPQExpBuffer(q, "SELECT tableoid, oid, "
6034 "rcname AS conname, "
6035 "'CHECK (' || rcsrc || ')' AS consrc, "
6036 "true AS conislocal, true AS convalidated "
6038 "WHERE rcrelid = '%u'::oid "
6040 tbinfo->dobj.catId.oid);
6044 /* no tableoid in 7.0 */
6045 appendPQExpBuffer(q, "SELECT "
6046 "(SELECT oid FROM pg_class WHERE relname = 'pg_relcheck') AS tableoid, "
6047 "oid, rcname AS conname, "
6048 "'CHECK (' || rcsrc || ')' AS consrc, "
6049 "true AS conislocal, true AS convalidated "
6051 "WHERE rcrelid = '%u'::oid "
6053 tbinfo->dobj.catId.oid);
6055 res = PQexec(g_conn, q->data);
6056 check_sql_result(res, g_conn, q->data, PGRES_TUPLES_OK);
6058 numConstrs = PQntuples(res);
6059 if (numConstrs != tbinfo->ncheck)
6061 write_msg(NULL, ngettext("expected %d check constraint on table \"%s\" but found %d\n",
6062 "expected %d check constraints on table \"%s\" but found %d\n",
6064 tbinfo->ncheck, tbinfo->dobj.name, numConstrs);
6065 write_msg(NULL, "(The system catalogs might be corrupted.)\n");
6069 constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
6070 tbinfo->checkexprs = constrs;
6072 for (j = 0; j < numConstrs; j++)
6074 bool validated = PQgetvalue(res, j, 5)[0] == 't';
6076 constrs[j].dobj.objType = DO_CONSTRAINT;
6077 constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, 0));
6078 constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, 1));
6079 AssignDumpId(&constrs[j].dobj);
6080 constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, 2));
6081 constrs[j].dobj.namespace = tbinfo->dobj.namespace;
6082 constrs[j].contable = tbinfo;
6083 constrs[j].condomain = NULL;
6084 constrs[j].contype = 'c';
6085 constrs[j].condef = pg_strdup(PQgetvalue(res, j, 3));
6086 constrs[j].confrelid = InvalidOid;
6087 constrs[j].conindex = 0;
6088 constrs[j].condeferrable = false;
6089 constrs[j].condeferred = false;
6090 constrs[j].conislocal = (PQgetvalue(res, j, 4)[0] == 't');
6092 * An unvalidated constraint needs to be dumped separately, so
6093 * that potentially-violating existing data is loaded before
6096 constrs[j].separate = !validated;
6098 constrs[j].dobj.dump = tbinfo->dobj.dump;
6101 * Mark the constraint as needing to appear before the table
6102 * --- this is so that any other dependencies of the
6103 * constraint will be emitted before we try to create the
6104 * table. If the constraint is not validated, it will be
6105 * dumped after data is loaded anyway, so don't do it. (There's
6106 * an automatic dependency in the opposite direction anyway, so
6107 * don't need to add one manually here.)
6110 addObjectDependency(&tbinfo->dobj,
6111 constrs[j].dobj.dumpId);
6114 * If the constraint is inherited, this will be detected later
6115 * (in pre-8.4 databases). We also detect later if the
6116 * constraint must be split out from the table definition.
6123 destroyPQExpBuffer(q);
6129 * read all text search parsers in the system catalogs and return them
6130 * in the TSParserInfo* structure
6132 * numTSParsers is set to the number of parsers read in
6135 getTSParsers(int *numTSParsers)
6140 PQExpBuffer query = createPQExpBuffer();
6141 TSParserInfo *prsinfo;
6152 /* Before 8.3, there is no built-in text search support */
6153 if (g_fout->remoteVersion < 80300)
6160 * find all text search objects, including builtin ones; we filter out
6161 * system-defined objects at dump-out time.
6164 /* Make sure we are in proper schema */
6165 selectSourceSchema("pg_catalog");
6167 appendPQExpBuffer(query, "SELECT tableoid, oid, prsname, prsnamespace, "
6168 "prsstart::oid, prstoken::oid, "
6169 "prsend::oid, prsheadline::oid, prslextype::oid "
6170 "FROM pg_ts_parser");
6172 res = PQexec(g_conn, query->data);
6173 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6175 ntups = PQntuples(res);
6176 *numTSParsers = ntups;
6178 prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
6180 i_tableoid = PQfnumber(res, "tableoid");
6181 i_oid = PQfnumber(res, "oid");
6182 i_prsname = PQfnumber(res, "prsname");
6183 i_prsnamespace = PQfnumber(res, "prsnamespace");
6184 i_prsstart = PQfnumber(res, "prsstart");
6185 i_prstoken = PQfnumber(res, "prstoken");
6186 i_prsend = PQfnumber(res, "prsend");
6187 i_prsheadline = PQfnumber(res, "prsheadline");
6188 i_prslextype = PQfnumber(res, "prslextype");
6190 for (i = 0; i < ntups; i++)
6192 prsinfo[i].dobj.objType = DO_TSPARSER;
6193 prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6194 prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6195 AssignDumpId(&prsinfo[i].dobj);
6196 prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
6197 prsinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_prsnamespace)),
6198 prsinfo[i].dobj.catId.oid);
6199 prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
6200 prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
6201 prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
6202 prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
6203 prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
6205 /* Decide whether we want to dump it */
6206 selectDumpableObject(&(prsinfo[i].dobj));
6211 destroyPQExpBuffer(query);
6217 * getTSDictionaries:
6218 * read all text search dictionaries in the system catalogs and return them
6219 * in the TSDictInfo* structure
6221 * numTSDicts is set to the number of dictionaries read in
6224 getTSDictionaries(int *numTSDicts)
6229 PQExpBuffer query = createPQExpBuffer();
6230 TSDictInfo *dictinfo;
6234 int i_dictnamespace;
6237 int i_dictinitoption;
6239 /* Before 8.3, there is no built-in text search support */
6240 if (g_fout->remoteVersion < 80300)
6246 /* Make sure we are in proper schema */
6247 selectSourceSchema("pg_catalog");
6249 appendPQExpBuffer(query, "SELECT tableoid, oid, dictname, "
6250 "dictnamespace, (%s dictowner) AS rolname, "
6251 "dicttemplate, dictinitoption "
6255 res = PQexec(g_conn, query->data);
6256 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6258 ntups = PQntuples(res);
6259 *numTSDicts = ntups;
6261 dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
6263 i_tableoid = PQfnumber(res, "tableoid");
6264 i_oid = PQfnumber(res, "oid");
6265 i_dictname = PQfnumber(res, "dictname");
6266 i_dictnamespace = PQfnumber(res, "dictnamespace");
6267 i_rolname = PQfnumber(res, "rolname");
6268 i_dictinitoption = PQfnumber(res, "dictinitoption");
6269 i_dicttemplate = PQfnumber(res, "dicttemplate");
6271 for (i = 0; i < ntups; i++)
6273 dictinfo[i].dobj.objType = DO_TSDICT;
6274 dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6275 dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6276 AssignDumpId(&dictinfo[i].dobj);
6277 dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
6278 dictinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_dictnamespace)),
6279 dictinfo[i].dobj.catId.oid);
6280 dictinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6281 dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
6282 if (PQgetisnull(res, i, i_dictinitoption))
6283 dictinfo[i].dictinitoption = NULL;
6285 dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
6287 /* Decide whether we want to dump it */
6288 selectDumpableObject(&(dictinfo[i].dobj));
6293 destroyPQExpBuffer(query);
6300 * read all text search templates in the system catalogs and return them
6301 * in the TSTemplateInfo* structure
6303 * numTSTemplates is set to the number of templates read in
6306 getTSTemplates(int *numTSTemplates)
6311 PQExpBuffer query = createPQExpBuffer();
6312 TSTemplateInfo *tmplinfo;
6316 int i_tmplnamespace;
6320 /* Before 8.3, there is no built-in text search support */
6321 if (g_fout->remoteVersion < 80300)
6323 *numTSTemplates = 0;
6327 /* Make sure we are in proper schema */
6328 selectSourceSchema("pg_catalog");
6330 appendPQExpBuffer(query, "SELECT tableoid, oid, tmplname, "
6331 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
6332 "FROM pg_ts_template");
6334 res = PQexec(g_conn, query->data);
6335 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6337 ntups = PQntuples(res);
6338 *numTSTemplates = ntups;
6340 tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
6342 i_tableoid = PQfnumber(res, "tableoid");
6343 i_oid = PQfnumber(res, "oid");
6344 i_tmplname = PQfnumber(res, "tmplname");
6345 i_tmplnamespace = PQfnumber(res, "tmplnamespace");
6346 i_tmplinit = PQfnumber(res, "tmplinit");
6347 i_tmpllexize = PQfnumber(res, "tmpllexize");
6349 for (i = 0; i < ntups; i++)
6351 tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
6352 tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6353 tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6354 AssignDumpId(&tmplinfo[i].dobj);
6355 tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
6356 tmplinfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_tmplnamespace)),
6357 tmplinfo[i].dobj.catId.oid);
6358 tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
6359 tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
6361 /* Decide whether we want to dump it */
6362 selectDumpableObject(&(tmplinfo[i].dobj));
6367 destroyPQExpBuffer(query);
6373 * getTSConfigurations:
6374 * read all text search configurations in the system catalogs and return
6375 * them in the TSConfigInfo* structure
6377 * numTSConfigs is set to the number of configurations read in
6380 getTSConfigurations(int *numTSConfigs)
6385 PQExpBuffer query = createPQExpBuffer();
6386 TSConfigInfo *cfginfo;
6394 /* Before 8.3, there is no built-in text search support */
6395 if (g_fout->remoteVersion < 80300)
6401 /* Make sure we are in proper schema */
6402 selectSourceSchema("pg_catalog");
6404 appendPQExpBuffer(query, "SELECT tableoid, oid, cfgname, "
6405 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
6406 "FROM pg_ts_config",
6409 res = PQexec(g_conn, query->data);
6410 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6412 ntups = PQntuples(res);
6413 *numTSConfigs = ntups;
6415 cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
6417 i_tableoid = PQfnumber(res, "tableoid");
6418 i_oid = PQfnumber(res, "oid");
6419 i_cfgname = PQfnumber(res, "cfgname");
6420 i_cfgnamespace = PQfnumber(res, "cfgnamespace");
6421 i_rolname = PQfnumber(res, "rolname");
6422 i_cfgparser = PQfnumber(res, "cfgparser");
6424 for (i = 0; i < ntups; i++)
6426 cfginfo[i].dobj.objType = DO_TSCONFIG;
6427 cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6428 cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6429 AssignDumpId(&cfginfo[i].dobj);
6430 cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
6431 cfginfo[i].dobj.namespace = findNamespace(atooid(PQgetvalue(res, i, i_cfgnamespace)),
6432 cfginfo[i].dobj.catId.oid);
6433 cfginfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6434 cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
6436 /* Decide whether we want to dump it */
6437 selectDumpableObject(&(cfginfo[i].dobj));
6442 destroyPQExpBuffer(query);
6448 * getForeignDataWrappers:
6449 * read all foreign-data wrappers in the system catalogs and return
6450 * them in the FdwInfo* structure
6452 * numForeignDataWrappers is set to the number of fdws read in
6455 getForeignDataWrappers(int *numForeignDataWrappers)
6460 PQExpBuffer query = createPQExpBuffer();
6471 /* Before 8.4, there are no foreign-data wrappers */
6472 if (g_fout->remoteVersion < 80400)
6474 *numForeignDataWrappers = 0;
6478 /* Make sure we are in proper schema */
6479 selectSourceSchema("pg_catalog");
6481 if (g_fout->remoteVersion >= 90100)
6483 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6484 "(%s fdwowner) AS rolname, "
6485 "fdwhandler::pg_catalog.regproc, "
6486 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6487 "array_to_string(ARRAY("
6488 "SELECT quote_ident(option_name) || ' ' || "
6489 "quote_literal(option_value) "
6490 "FROM pg_options_to_table(fdwoptions)"
6491 "), ', ') AS fdwoptions "
6492 "FROM pg_foreign_data_wrapper",
6497 appendPQExpBuffer(query, "SELECT tableoid, oid, fdwname, "
6498 "(%s fdwowner) AS rolname, "
6499 "'-' AS fdwhandler, "
6500 "fdwvalidator::pg_catalog.regproc, fdwacl, "
6501 "array_to_string(ARRAY("
6502 "SELECT quote_ident(option_name) || ' ' || "
6503 "quote_literal(option_value) "
6504 "FROM pg_options_to_table(fdwoptions)"
6505 "), ', ') AS fdwoptions "
6506 "FROM pg_foreign_data_wrapper",
6510 res = PQexec(g_conn, query->data);
6511 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6513 ntups = PQntuples(res);
6514 *numForeignDataWrappers = ntups;
6516 fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
6518 i_tableoid = PQfnumber(res, "tableoid");
6519 i_oid = PQfnumber(res, "oid");
6520 i_fdwname = PQfnumber(res, "fdwname");
6521 i_rolname = PQfnumber(res, "rolname");
6522 i_fdwhandler = PQfnumber(res, "fdwhandler");
6523 i_fdwvalidator = PQfnumber(res, "fdwvalidator");
6524 i_fdwacl = PQfnumber(res, "fdwacl");
6525 i_fdwoptions = PQfnumber(res, "fdwoptions");
6527 for (i = 0; i < ntups; i++)
6529 fdwinfo[i].dobj.objType = DO_FDW;
6530 fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6531 fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6532 AssignDumpId(&fdwinfo[i].dobj);
6533 fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
6534 fdwinfo[i].dobj.namespace = NULL;
6535 fdwinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6536 fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
6537 fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
6538 fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
6539 fdwinfo[i].fdwacl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
6541 /* Decide whether we want to dump it */
6542 selectDumpableObject(&(fdwinfo[i].dobj));
6547 destroyPQExpBuffer(query);
6553 * getForeignServers:
6554 * read all foreign servers in the system catalogs and return
6555 * them in the ForeignServerInfo * structure
6557 * numForeignServers is set to the number of servers read in
6560 getForeignServers(int *numForeignServers)
6565 PQExpBuffer query = createPQExpBuffer();
6566 ForeignServerInfo *srvinfo;
6577 /* Before 8.4, there are no foreign servers */
6578 if (g_fout->remoteVersion < 80400)
6580 *numForeignServers = 0;
6584 /* Make sure we are in proper schema */
6585 selectSourceSchema("pg_catalog");
6587 appendPQExpBuffer(query, "SELECT tableoid, oid, srvname, "
6588 "(%s srvowner) AS rolname, "
6589 "srvfdw, srvtype, srvversion, srvacl,"
6590 "array_to_string(ARRAY("
6591 "SELECT quote_ident(option_name) || ' ' || "
6592 "quote_literal(option_value) "
6593 "FROM pg_options_to_table(srvoptions)"
6594 "), ', ') AS srvoptions "
6595 "FROM pg_foreign_server",
6598 res = PQexec(g_conn, query->data);
6599 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6601 ntups = PQntuples(res);
6602 *numForeignServers = ntups;
6604 srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
6606 i_tableoid = PQfnumber(res, "tableoid");
6607 i_oid = PQfnumber(res, "oid");
6608 i_srvname = PQfnumber(res, "srvname");
6609 i_rolname = PQfnumber(res, "rolname");
6610 i_srvfdw = PQfnumber(res, "srvfdw");
6611 i_srvtype = PQfnumber(res, "srvtype");
6612 i_srvversion = PQfnumber(res, "srvversion");
6613 i_srvacl = PQfnumber(res, "srvacl");
6614 i_srvoptions = PQfnumber(res, "srvoptions");
6616 for (i = 0; i < ntups; i++)
6618 srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
6619 srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6620 srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6621 AssignDumpId(&srvinfo[i].dobj);
6622 srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
6623 srvinfo[i].dobj.namespace = NULL;
6624 srvinfo[i].rolname = pg_strdup(PQgetvalue(res, i, i_rolname));
6625 srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
6626 srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
6627 srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
6628 srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
6629 srvinfo[i].srvacl = pg_strdup(PQgetvalue(res, i, i_srvacl));
6631 /* Decide whether we want to dump it */
6632 selectDumpableObject(&(srvinfo[i].dobj));
6637 destroyPQExpBuffer(query);
6644 * read all default ACL information in the system catalogs and return
6645 * them in the DefaultACLInfo structure
6647 * numDefaultACLs is set to the number of ACLs read in
6650 getDefaultACLs(int *numDefaultACLs)
6652 DefaultACLInfo *daclinfo;
6658 int i_defaclnamespace;
6659 int i_defaclobjtype;
6664 if (g_fout->remoteVersion < 90000)
6666 *numDefaultACLs = 0;
6670 query = createPQExpBuffer();
6672 /* Make sure we are in proper schema */
6673 selectSourceSchema("pg_catalog");
6675 appendPQExpBuffer(query, "SELECT oid, tableoid, "
6676 "(%s defaclrole) AS defaclrole, "
6680 "FROM pg_default_acl",
6683 res = PQexec(g_conn, query->data);
6684 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
6686 ntups = PQntuples(res);
6687 *numDefaultACLs = ntups;
6689 daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
6691 i_oid = PQfnumber(res, "oid");
6692 i_tableoid = PQfnumber(res, "tableoid");
6693 i_defaclrole = PQfnumber(res, "defaclrole");
6694 i_defaclnamespace = PQfnumber(res, "defaclnamespace");
6695 i_defaclobjtype = PQfnumber(res, "defaclobjtype");
6696 i_defaclacl = PQfnumber(res, "defaclacl");
6698 for (i = 0; i < ntups; i++)
6700 Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
6702 daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
6703 daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6704 daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6705 AssignDumpId(&daclinfo[i].dobj);
6706 /* cheesy ... is it worth coming up with a better object name? */
6707 daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
6709 if (nspid != InvalidOid)
6710 daclinfo[i].dobj.namespace = findNamespace(nspid,
6711 daclinfo[i].dobj.catId.oid);
6713 daclinfo[i].dobj.namespace = NULL;
6715 daclinfo[i].defaclrole = pg_strdup(PQgetvalue(res, i, i_defaclrole));
6716 daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
6717 daclinfo[i].defaclacl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
6719 /* Decide whether we want to dump it */
6720 selectDumpableDefaultACL(&(daclinfo[i]));
6725 destroyPQExpBuffer(query);
6733 * This routine is used to dump any comments associated with the
6734 * object handed to this routine. The routine takes a constant character
6735 * string for the target part of the comment-creation command, plus
6736 * the namespace and owner of the object (for labeling the ArchiveEntry),
6737 * plus catalog ID and subid which are the lookup key for pg_description,
6738 * plus the dump ID for the object (for setting a dependency).
6739 * If a matching pg_description entry is found, it is dumped.
6741 * Note: although this routine takes a dumpId for dependency purposes,
6742 * that purpose is just to mark the dependency in the emitted dump file
6743 * for possible future use by pg_restore. We do NOT use it for determining
6744 * ordering of the comment in the dump file, because this routine is called
6745 * after dependency sorting occurs. This routine should be called just after
6746 * calling ArchiveEntry() for the specified object.
6749 dumpComment(Archive *fout, const char *target,
6750 const char *namespace, const char *owner,
6751 CatalogId catalogId, int subid, DumpId dumpId)
6753 CommentItem *comments;
6756 /* Comments are schema not data ... except blob comments are data */
6757 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
6768 /* Search for comments associated with catalogId, using table */
6769 ncomments = findComments(fout, catalogId.tableoid, catalogId.oid,
6772 /* Is there one matching the subid? */
6773 while (ncomments > 0)
6775 if (comments->objsubid == subid)
6781 /* If a comment exists, build COMMENT ON statement */
6784 PQExpBuffer query = createPQExpBuffer();
6786 appendPQExpBuffer(query, "COMMENT ON %s IS ", target);
6787 appendStringLiteralAH(query, comments->descr, fout);
6788 appendPQExpBuffer(query, ";\n");
6791 * We mark comments as SECTION_NONE because they really belong in the
6792 * same section as their parent, whether that is pre-data or
6795 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6796 target, namespace, NULL, owner,
6797 false, "COMMENT", SECTION_NONE,
6798 query->data, "", NULL,
6802 destroyPQExpBuffer(query);
6807 * dumpTableComment --
6809 * As above, but dump comments for both the specified table (or view)
6813 dumpTableComment(Archive *fout, TableInfo *tbinfo,
6814 const char *reltypename)
6816 CommentItem *comments;
6821 /* Comments are SCHEMA not data */
6825 /* Search for comments associated with relation, using table */
6826 ncomments = findComments(fout,
6827 tbinfo->dobj.catId.tableoid,
6828 tbinfo->dobj.catId.oid,
6831 /* If comments exist, build COMMENT ON statements */
6835 query = createPQExpBuffer();
6836 target = createPQExpBuffer();
6838 while (ncomments > 0)
6840 const char *descr = comments->descr;
6841 int objsubid = comments->objsubid;
6845 resetPQExpBuffer(target);
6846 appendPQExpBuffer(target, "%s %s", reltypename,
6847 fmtId(tbinfo->dobj.name));
6849 resetPQExpBuffer(query);
6850 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6851 appendStringLiteralAH(query, descr, fout);
6852 appendPQExpBuffer(query, ";\n");
6854 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6856 tbinfo->dobj.namespace->dobj.name,
6857 NULL, tbinfo->rolname,
6858 false, "COMMENT", SECTION_NONE,
6859 query->data, "", NULL,
6860 &(tbinfo->dobj.dumpId), 1,
6863 else if (objsubid > 0 && objsubid <= tbinfo->numatts)
6865 resetPQExpBuffer(target);
6866 appendPQExpBuffer(target, "COLUMN %s.",
6867 fmtId(tbinfo->dobj.name));
6868 appendPQExpBuffer(target, "%s",
6869 fmtId(tbinfo->attnames[objsubid - 1]));
6871 resetPQExpBuffer(query);
6872 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
6873 appendStringLiteralAH(query, descr, fout);
6874 appendPQExpBuffer(query, ";\n");
6876 ArchiveEntry(fout, nilCatalogId, createDumpId(),
6878 tbinfo->dobj.namespace->dobj.name,
6879 NULL, tbinfo->rolname,
6880 false, "COMMENT", SECTION_NONE,
6881 query->data, "", NULL,
6882 &(tbinfo->dobj.dumpId), 1,
6890 destroyPQExpBuffer(query);
6891 destroyPQExpBuffer(target);
6897 * Find the comment(s), if any, associated with the given object. All the
6898 * objsubid values associated with the given classoid/objoid are found with
6902 findComments(Archive *fout, Oid classoid, Oid objoid,
6903 CommentItem **items)
6905 /* static storage for table of comments */
6906 static CommentItem *comments = NULL;
6907 static int ncomments = -1;
6909 CommentItem *middle = NULL;
6914 /* Get comments if we didn't already */
6916 ncomments = collectComments(fout, &comments);
6919 * Pre-7.2, pg_description does not contain classoid, so collectComments
6920 * just stores a zero. If there's a collision on object OID, well, you
6921 * get duplicate comments.
6923 if (fout->remoteVersion < 70200)
6927 * Do binary search to find some item matching the object.
6930 high = &comments[ncomments - 1];
6933 middle = low + (high - low) / 2;
6935 if (classoid < middle->classoid)
6937 else if (classoid > middle->classoid)
6939 else if (objoid < middle->objoid)
6941 else if (objoid > middle->objoid)
6944 break; /* found a match */
6947 if (low > high) /* no matches */
6954 * Now determine how many items match the object. The search loop
6955 * invariant still holds: only items between low and high inclusive could
6959 while (middle > low)
6961 if (classoid != middle[-1].classoid ||
6962 objoid != middle[-1].objoid)
6971 while (middle <= high)
6973 if (classoid != middle->classoid ||
6974 objoid != middle->objoid)
6984 * collectComments --
6986 * Construct a table of all comments available for database objects.
6987 * We used to do per-object queries for the comments, but it's much faster
6988 * to pull them all over at once, and on most databases the memory cost
6991 * The table is sorted by classoid/objid/objsubid for speed in lookup.
6994 collectComments(Archive *fout, CommentItem **items)
7004 CommentItem *comments;
7007 * Note we do NOT change source schema here; preserve the caller's
7011 query = createPQExpBuffer();
7013 if (fout->remoteVersion >= 70300)
7015 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7016 "FROM pg_catalog.pg_description "
7017 "ORDER BY classoid, objoid, objsubid");
7019 else if (fout->remoteVersion >= 70200)
7021 appendPQExpBuffer(query, "SELECT description, classoid, objoid, objsubid "
7022 "FROM pg_description "
7023 "ORDER BY classoid, objoid, objsubid");
7027 /* Note: this will fail to find attribute comments in pre-7.2... */
7028 appendPQExpBuffer(query, "SELECT description, 0 AS classoid, objoid, 0 AS objsubid "
7029 "FROM pg_description "
7033 res = PQexec(g_conn, query->data);
7034 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7036 /* Construct lookup table containing OIDs in numeric form */
7038 i_description = PQfnumber(res, "description");
7039 i_classoid = PQfnumber(res, "classoid");
7040 i_objoid = PQfnumber(res, "objoid");
7041 i_objsubid = PQfnumber(res, "objsubid");
7043 ntups = PQntuples(res);
7045 comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
7047 for (i = 0; i < ntups; i++)
7049 comments[i].descr = PQgetvalue(res, i, i_description);
7050 comments[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
7051 comments[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
7052 comments[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
7055 /* Do NOT free the PGresult since we are keeping pointers into it */
7056 destroyPQExpBuffer(query);
7063 * dumpDumpableObject
7065 * This routine and its subsidiaries are responsible for creating
7066 * ArchiveEntries (TOC objects) for each object to be dumped.
7069 dumpDumpableObject(Archive *fout, DumpableObject *dobj)
7071 switch (dobj->objType)
7074 dumpNamespace(fout, (NamespaceInfo *) dobj);
7077 dumpExtension(fout, (ExtensionInfo *) dobj);
7080 dumpType(fout, (TypeInfo *) dobj);
7083 dumpShellType(fout, (ShellTypeInfo *) dobj);
7086 dumpFunc(fout, (FuncInfo *) dobj);
7089 dumpAgg(fout, (AggInfo *) dobj);
7092 dumpOpr(fout, (OprInfo *) dobj);
7095 dumpOpclass(fout, (OpclassInfo *) dobj);
7098 dumpOpfamily(fout, (OpfamilyInfo *) dobj);
7101 dumpCollation(fout, (CollInfo *) dobj);
7104 dumpConversion(fout, (ConvInfo *) dobj);
7107 dumpTable(fout, (TableInfo *) dobj);
7110 dumpAttrDef(fout, (AttrDefInfo *) dobj);
7113 dumpIndex(fout, (IndxInfo *) dobj);
7116 dumpRule(fout, (RuleInfo *) dobj);
7119 dumpTrigger(fout, (TriggerInfo *) dobj);
7122 dumpConstraint(fout, (ConstraintInfo *) dobj);
7124 case DO_FK_CONSTRAINT:
7125 dumpConstraint(fout, (ConstraintInfo *) dobj);
7128 dumpProcLang(fout, (ProcLangInfo *) dobj);
7131 dumpCast(fout, (CastInfo *) dobj);
7134 dumpTableData(fout, (TableDataInfo *) dobj);
7137 /* table rowtypes and array types are never dumped separately */
7140 dumpTSParser(fout, (TSParserInfo *) dobj);
7143 dumpTSDictionary(fout, (TSDictInfo *) dobj);
7146 dumpTSTemplate(fout, (TSTemplateInfo *) dobj);
7149 dumpTSConfig(fout, (TSConfigInfo *) dobj);
7152 dumpForeignDataWrapper(fout, (FdwInfo *) dobj);
7154 case DO_FOREIGN_SERVER:
7155 dumpForeignServer(fout, (ForeignServerInfo *) dobj);
7157 case DO_DEFAULT_ACL:
7158 dumpDefaultACL(fout, (DefaultACLInfo *) dobj);
7161 dumpBlob(fout, (BlobInfo *) dobj);
7164 ArchiveEntry(fout, dobj->catId, dobj->dumpId,
7165 dobj->name, NULL, NULL, "",
7166 false, "BLOBS", SECTION_DATA,
7168 dobj->dependencies, dobj->nDeps,
7176 * writes out to fout the queries to recreate a user-defined namespace
7179 dumpNamespace(Archive *fout, NamespaceInfo *nspinfo)
7186 /* Skip if not to be dumped */
7187 if (!nspinfo->dobj.dump || dataOnly)
7190 /* don't dump dummy namespace from pre-7.3 source */
7191 if (strlen(nspinfo->dobj.name) == 0)
7194 q = createPQExpBuffer();
7195 delq = createPQExpBuffer();
7196 labelq = createPQExpBuffer();
7198 qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
7200 appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
7202 appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
7204 appendPQExpBuffer(labelq, "SCHEMA %s", qnspname);
7207 binary_upgrade_extension_member(q, &nspinfo->dobj, labelq->data);
7209 ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
7213 false, "SCHEMA", SECTION_PRE_DATA,
7214 q->data, delq->data, NULL,
7215 nspinfo->dobj.dependencies, nspinfo->dobj.nDeps,
7218 /* Dump Schema Comments and Security Labels */
7219 dumpComment(fout, labelq->data,
7220 NULL, nspinfo->rolname,
7221 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7222 dumpSecLabel(fout, labelq->data,
7223 NULL, nspinfo->rolname,
7224 nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
7226 dumpACL(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId, "SCHEMA",
7227 qnspname, NULL, nspinfo->dobj.name, NULL,
7228 nspinfo->rolname, nspinfo->nspacl);
7232 destroyPQExpBuffer(q);
7233 destroyPQExpBuffer(delq);
7234 destroyPQExpBuffer(labelq);
7239 * writes out to fout the queries to recreate an extension
7242 dumpExtension(Archive *fout, ExtensionInfo *extinfo)
7249 /* Skip if not to be dumped */
7250 if (!extinfo->dobj.dump || dataOnly)
7253 q = createPQExpBuffer();
7254 delq = createPQExpBuffer();
7255 labelq = createPQExpBuffer();
7257 qextname = pg_strdup(fmtId(extinfo->dobj.name));
7259 appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
7261 if (!binary_upgrade)
7264 * In a regular dump, we use IF NOT EXISTS so that there isn't a
7265 * problem if the extension already exists in the target database;
7266 * this is essential for installed-by-default extensions such as
7269 * In binary-upgrade mode, that doesn't work well, so instead we skip
7270 * built-in extensions based on their OIDs; see
7271 * selectDumpableExtension.
7273 appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
7274 qextname, fmtId(extinfo->namespace));
7281 appendPQExpBuffer(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
7282 appendPQExpBuffer(q,
7283 "SELECT binary_upgrade.create_empty_extension(");
7284 appendStringLiteralAH(q, extinfo->dobj.name, fout);
7285 appendPQExpBuffer(q, ", ");
7286 appendStringLiteralAH(q, extinfo->namespace, fout);
7287 appendPQExpBuffer(q, ", ");
7288 appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
7289 appendStringLiteralAH(q, extinfo->extversion, fout);
7290 appendPQExpBuffer(q, ", ");
7293 * Note that we're pushing extconfig (an OID array) back into
7294 * pg_extension exactly as-is. This is OK because pg_class OIDs are
7295 * preserved in binary upgrade.
7297 if (strlen(extinfo->extconfig) > 2)
7298 appendStringLiteralAH(q, extinfo->extconfig, fout);
7300 appendPQExpBuffer(q, "NULL");
7301 appendPQExpBuffer(q, ", ");
7302 if (strlen(extinfo->extcondition) > 2)
7303 appendStringLiteralAH(q, extinfo->extcondition, fout);
7305 appendPQExpBuffer(q, "NULL");
7306 appendPQExpBuffer(q, ", ");
7307 appendPQExpBuffer(q, "ARRAY[");
7309 for (i = 0; i < extinfo->dobj.nDeps; i++)
7311 DumpableObject *extobj;
7313 extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
7314 if (extobj && extobj->objType == DO_EXTENSION)
7317 appendPQExpBuffer(q, ",");
7318 appendStringLiteralAH(q, extobj->name, fout);
7321 appendPQExpBuffer(q, "]::pg_catalog.text[]");
7322 appendPQExpBuffer(q, ");\n");
7325 appendPQExpBuffer(labelq, "EXTENSION %s", qextname);
7327 ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
7331 false, "EXTENSION", SECTION_PRE_DATA,
7332 q->data, delq->data, NULL,
7333 extinfo->dobj.dependencies, extinfo->dobj.nDeps,
7336 /* Dump Extension Comments and Security Labels */
7337 dumpComment(fout, labelq->data,
7339 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7340 dumpSecLabel(fout, labelq->data,
7342 extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
7346 destroyPQExpBuffer(q);
7347 destroyPQExpBuffer(delq);
7348 destroyPQExpBuffer(labelq);
7353 * writes out to fout the queries to recreate a user-defined type
7356 dumpType(Archive *fout, TypeInfo *tyinfo)
7358 /* Skip if not to be dumped */
7359 if (!tyinfo->dobj.dump || dataOnly)
7362 /* Dump out in proper style */
7363 if (tyinfo->typtype == TYPTYPE_BASE)
7364 dumpBaseType(fout, tyinfo);
7365 else if (tyinfo->typtype == TYPTYPE_DOMAIN)
7366 dumpDomain(fout, tyinfo);
7367 else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
7368 dumpCompositeType(fout, tyinfo);
7369 else if (tyinfo->typtype == TYPTYPE_ENUM)
7370 dumpEnumType(fout, tyinfo);
7371 else if (tyinfo->typtype == TYPTYPE_RANGE)
7372 dumpRangeType(fout, tyinfo);
7374 write_msg(NULL, "WARNING: typtype of data type \"%s\" appears to be invalid\n",
7380 * writes out to fout the queries to recreate a user-defined enum type
7383 dumpEnumType(Archive *fout, TypeInfo *tyinfo)
7385 PQExpBuffer q = createPQExpBuffer();
7386 PQExpBuffer delq = createPQExpBuffer();
7387 PQExpBuffer labelq = createPQExpBuffer();
7388 PQExpBuffer query = createPQExpBuffer();
7395 /* Set proper schema search path */
7396 selectSourceSchema("pg_catalog");
7398 if (fout->remoteVersion >= 90100)
7399 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7400 "FROM pg_catalog.pg_enum "
7401 "WHERE enumtypid = '%u'"
7402 "ORDER BY enumsortorder",
7403 tyinfo->dobj.catId.oid);
7405 appendPQExpBuffer(query, "SELECT oid, enumlabel "
7406 "FROM pg_catalog.pg_enum "
7407 "WHERE enumtypid = '%u'"
7409 tyinfo->dobj.catId.oid);
7411 res = PQexec(g_conn, query->data);
7412 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7414 num = PQntuples(res);
7417 * DROP must be fully qualified in case same name appears in pg_catalog.
7418 * CASCADE shouldn't be required here as for normal types since the I/O
7419 * functions are generic and do not get dropped.
7421 appendPQExpBuffer(delq, "DROP TYPE %s.",
7422 fmtId(tyinfo->dobj.namespace->dobj.name));
7423 appendPQExpBuffer(delq, "%s;\n",
7424 fmtId(tyinfo->dobj.name));
7427 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7429 appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
7430 fmtId(tyinfo->dobj.name));
7432 if (!binary_upgrade)
7434 /* Labels with server-assigned oids */
7435 for (i = 0; i < num; i++)
7437 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7439 appendPQExpBuffer(q, ",");
7440 appendPQExpBuffer(q, "\n ");
7441 appendStringLiteralAH(q, label, fout);
7445 appendPQExpBuffer(q, "\n);\n");
7449 /* Labels with dump-assigned (preserved) oids */
7450 for (i = 0; i < num; i++)
7452 enum_oid = atooid(PQgetvalue(res, i, PQfnumber(res, "oid")));
7453 label = PQgetvalue(res, i, PQfnumber(res, "enumlabel"));
7456 appendPQExpBuffer(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
7457 appendPQExpBuffer(q,
7458 "SELECT binary_upgrade.set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
7460 appendPQExpBuffer(q, "ALTER TYPE %s.",
7461 fmtId(tyinfo->dobj.namespace->dobj.name));
7462 appendPQExpBuffer(q, "%s ADD VALUE ",
7463 fmtId(tyinfo->dobj.name));
7464 appendStringLiteralAH(q, label, fout);
7465 appendPQExpBuffer(q, ";\n\n");
7469 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7472 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7474 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7476 tyinfo->dobj.namespace->dobj.name,
7478 tyinfo->rolname, false,
7479 "TYPE", SECTION_PRE_DATA,
7480 q->data, delq->data, NULL,
7481 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7484 /* Dump Type Comments and Security Labels */
7485 dumpComment(fout, labelq->data,
7486 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7487 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7488 dumpSecLabel(fout, labelq->data,
7489 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7490 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7493 destroyPQExpBuffer(q);
7494 destroyPQExpBuffer(delq);
7495 destroyPQExpBuffer(labelq);
7496 destroyPQExpBuffer(query);
7501 * writes out to fout the queries to recreate a user-defined range type
7504 dumpRangeType(Archive *fout, TypeInfo *tyinfo)
7506 PQExpBuffer q = createPQExpBuffer();
7507 PQExpBuffer delq = createPQExpBuffer();
7508 PQExpBuffer labelq = createPQExpBuffer();
7509 PQExpBuffer query = createPQExpBuffer();
7515 * select appropriate schema to ensure names in CREATE are properly
7518 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7520 appendPQExpBuffer(query,
7521 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
7522 "opc.opcname AS opcname, "
7523 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
7524 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
7526 "CASE WHEN rngcollation = st.typcollation THEN 0 "
7527 " ELSE rngcollation END AS collation, "
7528 "rngcanonical, rngsubdiff "
7529 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
7530 " pg_catalog.pg_opclass opc "
7531 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
7533 tyinfo->dobj.catId.oid);
7535 res = PQexec(g_conn, query->data);
7536 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7537 if (PQntuples(res) != 1)
7539 write_msg(NULL, "query returned %d pg_range entries for range type \"%s\"\n",
7540 PQntuples(res), tyinfo->dobj.name);
7545 * DROP must be fully qualified in case same name appears in pg_catalog.
7546 * CASCADE shouldn't be required here as for normal types since the I/O
7547 * functions are generic and do not get dropped.
7549 appendPQExpBuffer(delq, "DROP TYPE %s.",
7550 fmtId(tyinfo->dobj.namespace->dobj.name));
7551 appendPQExpBuffer(delq, "%s;\n",
7552 fmtId(tyinfo->dobj.name));
7555 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7557 appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
7558 fmtId(tyinfo->dobj.name));
7560 appendPQExpBuffer(q, "\n subtype = %s",
7561 PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
7563 /* print subtype_opclass only if not default for subtype */
7564 if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
7566 char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
7567 char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
7569 /* always schema-qualify, don't try to be smart */
7570 appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
7572 appendPQExpBuffer(q, "%s", fmtId(opcname));
7575 collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
7576 if (OidIsValid(collationOid))
7578 CollInfo *coll = findCollationByOid(collationOid);
7582 /* always schema-qualify, don't try to be smart */
7583 appendPQExpBuffer(q, ",\n collation = %s.",
7584 fmtId(coll->dobj.namespace->dobj.name));
7585 appendPQExpBuffer(q, "%s",
7586 fmtId(coll->dobj.name));
7590 procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
7591 if (strcmp(procname, "-") != 0)
7592 appendPQExpBuffer(q, ",\n canonical = %s", procname);
7594 procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
7595 if (strcmp(procname, "-") != 0)
7596 appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
7598 appendPQExpBuffer(q, "\n);\n");
7600 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7603 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7605 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
7607 tyinfo->dobj.namespace->dobj.name,
7609 tyinfo->rolname, false,
7610 "TYPE", SECTION_PRE_DATA,
7611 q->data, delq->data, NULL,
7612 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
7615 /* Dump Type Comments and Security Labels */
7616 dumpComment(fout, labelq->data,
7617 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7618 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7619 dumpSecLabel(fout, labelq->data,
7620 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
7621 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
7624 destroyPQExpBuffer(q);
7625 destroyPQExpBuffer(delq);
7626 destroyPQExpBuffer(labelq);
7627 destroyPQExpBuffer(query);
7632 * writes out to fout the queries to recreate a user-defined base type
7635 dumpBaseType(Archive *fout, TypeInfo *tyinfo)
7637 PQExpBuffer q = createPQExpBuffer();
7638 PQExpBuffer delq = createPQExpBuffer();
7639 PQExpBuffer labelq = createPQExpBuffer();
7640 PQExpBuffer query = createPQExpBuffer();
7657 char *typispreferred;
7662 char *typcollatable;
7664 bool typdefault_is_literal = false;
7666 /* Set proper schema search path so regproc references list correctly */
7667 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7669 /* Fetch type-specific details */
7670 if (fout->remoteVersion >= 90100)
7672 appendPQExpBuffer(query, "SELECT typlen, "
7673 "typinput, typoutput, typreceive, typsend, "
7674 "typmodin, typmodout, typanalyze, "
7675 "typreceive::pg_catalog.oid AS typreceiveoid, "
7676 "typsend::pg_catalog.oid AS typsendoid, "
7677 "typmodin::pg_catalog.oid AS typmodinoid, "
7678 "typmodout::pg_catalog.oid AS typmodoutoid, "
7679 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7680 "typcategory, typispreferred, "
7681 "typdelim, typbyval, typalign, typstorage, "
7682 "(typcollation <> 0) AS typcollatable, "
7683 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7684 "FROM pg_catalog.pg_type "
7685 "WHERE oid = '%u'::pg_catalog.oid",
7686 tyinfo->dobj.catId.oid);
7688 else if (fout->remoteVersion >= 80400)
7690 appendPQExpBuffer(query, "SELECT typlen, "
7691 "typinput, typoutput, typreceive, typsend, "
7692 "typmodin, typmodout, typanalyze, "
7693 "typreceive::pg_catalog.oid AS typreceiveoid, "
7694 "typsend::pg_catalog.oid AS typsendoid, "
7695 "typmodin::pg_catalog.oid AS typmodinoid, "
7696 "typmodout::pg_catalog.oid AS typmodoutoid, "
7697 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7698 "typcategory, typispreferred, "
7699 "typdelim, typbyval, typalign, typstorage, "
7700 "false AS typcollatable, "
7701 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
7702 "FROM pg_catalog.pg_type "
7703 "WHERE oid = '%u'::pg_catalog.oid",
7704 tyinfo->dobj.catId.oid);
7706 else if (fout->remoteVersion >= 80300)
7708 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
7709 appendPQExpBuffer(query, "SELECT typlen, "
7710 "typinput, typoutput, typreceive, typsend, "
7711 "typmodin, typmodout, typanalyze, "
7712 "typreceive::pg_catalog.oid AS typreceiveoid, "
7713 "typsend::pg_catalog.oid AS typsendoid, "
7714 "typmodin::pg_catalog.oid AS typmodinoid, "
7715 "typmodout::pg_catalog.oid AS typmodoutoid, "
7716 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7717 "'U' AS typcategory, false AS typispreferred, "
7718 "typdelim, typbyval, typalign, typstorage, "
7719 "false AS typcollatable, "
7720 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7721 "FROM pg_catalog.pg_type "
7722 "WHERE oid = '%u'::pg_catalog.oid",
7723 tyinfo->dobj.catId.oid);
7725 else if (fout->remoteVersion >= 80000)
7727 appendPQExpBuffer(query, "SELECT typlen, "
7728 "typinput, typoutput, typreceive, typsend, "
7729 "'-' AS typmodin, '-' AS typmodout, "
7731 "typreceive::pg_catalog.oid AS typreceiveoid, "
7732 "typsend::pg_catalog.oid AS typsendoid, "
7733 "0 AS typmodinoid, 0 AS typmodoutoid, "
7734 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
7735 "'U' AS typcategory, false AS typispreferred, "
7736 "typdelim, typbyval, typalign, typstorage, "
7737 "false AS typcollatable, "
7738 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7739 "FROM pg_catalog.pg_type "
7740 "WHERE oid = '%u'::pg_catalog.oid",
7741 tyinfo->dobj.catId.oid);
7743 else if (fout->remoteVersion >= 70400)
7745 appendPQExpBuffer(query, "SELECT typlen, "
7746 "typinput, typoutput, typreceive, typsend, "
7747 "'-' AS typmodin, '-' AS typmodout, "
7748 "'-' AS typanalyze, "
7749 "typreceive::pg_catalog.oid AS typreceiveoid, "
7750 "typsend::pg_catalog.oid AS typsendoid, "
7751 "0 AS typmodinoid, 0 AS typmodoutoid, "
7752 "0 AS typanalyzeoid, "
7753 "'U' AS typcategory, false AS typispreferred, "
7754 "typdelim, typbyval, typalign, typstorage, "
7755 "false AS typcollatable, "
7756 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7757 "FROM pg_catalog.pg_type "
7758 "WHERE oid = '%u'::pg_catalog.oid",
7759 tyinfo->dobj.catId.oid);
7761 else if (fout->remoteVersion >= 70300)
7763 appendPQExpBuffer(query, "SELECT typlen, "
7764 "typinput, typoutput, "
7765 "'-' AS typreceive, '-' AS typsend, "
7766 "'-' AS typmodin, '-' AS typmodout, "
7767 "'-' AS typanalyze, "
7768 "0 AS typreceiveoid, 0 AS typsendoid, "
7769 "0 AS typmodinoid, 0 AS typmodoutoid, "
7770 "0 AS typanalyzeoid, "
7771 "'U' AS typcategory, false AS typispreferred, "
7772 "typdelim, typbyval, typalign, typstorage, "
7773 "false AS typcollatable, "
7774 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
7775 "FROM pg_catalog.pg_type "
7776 "WHERE oid = '%u'::pg_catalog.oid",
7777 tyinfo->dobj.catId.oid);
7779 else if (fout->remoteVersion >= 70200)
7782 * Note: although pre-7.3 catalogs contain typreceive and typsend,
7783 * ignore them because they are not right.
7785 appendPQExpBuffer(query, "SELECT typlen, "
7786 "typinput, typoutput, "
7787 "'-' AS typreceive, '-' AS typsend, "
7788 "'-' AS typmodin, '-' AS typmodout, "
7789 "'-' AS typanalyze, "
7790 "0 AS typreceiveoid, 0 AS typsendoid, "
7791 "0 AS typmodinoid, 0 AS typmodoutoid, "
7792 "0 AS typanalyzeoid, "
7793 "'U' AS typcategory, false AS typispreferred, "
7794 "typdelim, typbyval, typalign, typstorage, "
7795 "false AS typcollatable, "
7796 "NULL AS typdefaultbin, typdefault "
7798 "WHERE oid = '%u'::oid",
7799 tyinfo->dobj.catId.oid);
7801 else if (fout->remoteVersion >= 70100)
7804 * Ignore pre-7.2 typdefault; the field exists but has an unusable
7807 appendPQExpBuffer(query, "SELECT typlen, "
7808 "typinput, typoutput, "
7809 "'-' AS typreceive, '-' AS typsend, "
7810 "'-' AS typmodin, '-' AS typmodout, "
7811 "'-' AS typanalyze, "
7812 "0 AS typreceiveoid, 0 AS typsendoid, "
7813 "0 AS typmodinoid, 0 AS typmodoutoid, "
7814 "0 AS typanalyzeoid, "
7815 "'U' AS typcategory, false AS typispreferred, "
7816 "typdelim, typbyval, typalign, typstorage, "
7817 "false AS typcollatable, "
7818 "NULL AS typdefaultbin, NULL AS typdefault "
7820 "WHERE oid = '%u'::oid",
7821 tyinfo->dobj.catId.oid);
7825 appendPQExpBuffer(query, "SELECT typlen, "
7826 "typinput, typoutput, "
7827 "'-' AS typreceive, '-' AS typsend, "
7828 "'-' AS typmodin, '-' AS typmodout, "
7829 "'-' AS typanalyze, "
7830 "0 AS typreceiveoid, 0 AS typsendoid, "
7831 "0 AS typmodinoid, 0 AS typmodoutoid, "
7832 "0 AS typanalyzeoid, "
7833 "'U' AS typcategory, false AS typispreferred, "
7834 "typdelim, typbyval, typalign, "
7835 "'p'::char AS typstorage, "
7836 "false AS typcollatable, "
7837 "NULL AS typdefaultbin, NULL AS typdefault "
7839 "WHERE oid = '%u'::oid",
7840 tyinfo->dobj.catId.oid);
7843 res = PQexec(g_conn, query->data);
7844 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
7846 /* Expecting a single result only */
7847 ntups = PQntuples(res);
7850 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
7851 "query returned %d rows instead of one: %s\n",
7853 ntups, query->data);
7857 typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
7858 typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
7859 typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
7860 typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
7861 typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
7862 typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
7863 typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
7864 typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
7865 typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
7866 typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
7867 typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
7868 typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
7869 typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
7870 typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
7871 typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
7872 typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
7873 typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
7874 typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
7875 typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
7876 typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
7877 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
7878 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
7879 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
7881 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
7882 typdefault_is_literal = true; /* it needs quotes */
7888 * DROP must be fully qualified in case same name appears in pg_catalog.
7889 * The reason we include CASCADE is that the circular dependency between
7890 * the type and its I/O functions makes it impossible to drop the type any
7893 appendPQExpBuffer(delq, "DROP TYPE %s.",
7894 fmtId(tyinfo->dobj.namespace->dobj.name));
7895 appendPQExpBuffer(delq, "%s CASCADE;\n",
7896 fmtId(tyinfo->dobj.name));
7898 /* We might already have a shell type, but setting pg_type_oid is harmless */
7900 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
7902 appendPQExpBuffer(q,
7903 "CREATE TYPE %s (\n"
7904 " INTERNALLENGTH = %s",
7905 fmtId(tyinfo->dobj.name),
7906 (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
7908 if (fout->remoteVersion >= 70300)
7910 /* regproc result is correctly quoted as of 7.3 */
7911 appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
7912 appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
7913 if (OidIsValid(typreceiveoid))
7914 appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
7915 if (OidIsValid(typsendoid))
7916 appendPQExpBuffer(q, ",\n SEND = %s", typsend);
7917 if (OidIsValid(typmodinoid))
7918 appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
7919 if (OidIsValid(typmodoutoid))
7920 appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
7921 if (OidIsValid(typanalyzeoid))
7922 appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
7926 /* regproc delivers an unquoted name before 7.3 */
7927 /* cannot combine these because fmtId uses static result area */
7928 appendPQExpBuffer(q, ",\n INPUT = %s", fmtId(typinput));
7929 appendPQExpBuffer(q, ",\n OUTPUT = %s", fmtId(typoutput));
7930 /* receive/send/typmodin/typmodout/analyze need not be printed */
7933 if (strcmp(typcollatable, "t") == 0)
7934 appendPQExpBuffer(q, ",\n COLLATABLE = true");
7936 if (typdefault != NULL)
7938 appendPQExpBuffer(q, ",\n DEFAULT = ");
7939 if (typdefault_is_literal)
7940 appendStringLiteralAH(q, typdefault, fout);
7942 appendPQExpBufferStr(q, typdefault);
7945 if (OidIsValid(tyinfo->typelem))
7949 /* reselect schema in case changed by function dump */
7950 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
7951 elemType = getFormattedTypeName(tyinfo->typelem, zeroAsOpaque);
7952 appendPQExpBuffer(q, ",\n ELEMENT = %s", elemType);
7956 if (strcmp(typcategory, "U") != 0)
7958 appendPQExpBuffer(q, ",\n CATEGORY = ");
7959 appendStringLiteralAH(q, typcategory, fout);
7962 if (strcmp(typispreferred, "t") == 0)
7963 appendPQExpBuffer(q, ",\n PREFERRED = true");
7965 if (typdelim && strcmp(typdelim, ",") != 0)
7967 appendPQExpBuffer(q, ",\n DELIMITER = ");
7968 appendStringLiteralAH(q, typdelim, fout);
7971 if (strcmp(typalign, "c") == 0)
7972 appendPQExpBuffer(q, ",\n ALIGNMENT = char");
7973 else if (strcmp(typalign, "s") == 0)
7974 appendPQExpBuffer(q, ",\n ALIGNMENT = int2");
7975 else if (strcmp(typalign, "i") == 0)
7976 appendPQExpBuffer(q, ",\n ALIGNMENT = int4");
7977 else if (strcmp(typalign, "d") == 0)
7978 appendPQExpBuffer(q, ",\n ALIGNMENT = double");
7980 if (strcmp(typstorage, "p") == 0)
7981 appendPQExpBuffer(q, ",\n STORAGE = plain");
7982 else if (strcmp(typstorage, "e") == 0)
7983 appendPQExpBuffer(q, ",\n STORAGE = external");
7984 else if (strcmp(typstorage, "x") == 0)
7985 appendPQExpBuffer(q, ",\n STORAGE = extended");
7986 else if (strcmp(typstorage, "m") == 0)
7987 appendPQExpBuffer(q, ",\n STORAGE = main");
7989 if (strcmp(typbyval, "t") == 0)
7990 appendPQExpBuffer(q, ",\n PASSEDBYVALUE");
7992 appendPQExpBuffer(q, "\n);\n");
7994 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
7997 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
7999 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8001 tyinfo->dobj.namespace->dobj.name,
8003 tyinfo->rolname, false,
8004 "TYPE", SECTION_PRE_DATA,
8005 q->data, delq->data, NULL,
8006 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8009 /* Dump Type Comments and Security Labels */
8010 dumpComment(fout, labelq->data,
8011 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8012 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8013 dumpSecLabel(fout, labelq->data,
8014 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8015 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8018 destroyPQExpBuffer(q);
8019 destroyPQExpBuffer(delq);
8020 destroyPQExpBuffer(labelq);
8021 destroyPQExpBuffer(query);
8026 * writes out to fout the queries to recreate a user-defined domain
8029 dumpDomain(Archive *fout, TypeInfo *tyinfo)
8031 PQExpBuffer q = createPQExpBuffer();
8032 PQExpBuffer delq = createPQExpBuffer();
8033 PQExpBuffer labelq = createPQExpBuffer();
8034 PQExpBuffer query = createPQExpBuffer();
8042 bool typdefault_is_literal = false;
8044 /* Set proper schema search path so type references list correctly */
8045 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
8047 /* Fetch domain specific details */
8048 if (g_fout->remoteVersion >= 90100)
8050 /* typcollation is new in 9.1 */
8051 appendPQExpBuffer(query, "SELECT t.typnotnull, "
8052 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
8053 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8055 "CASE WHEN t.typcollation <> u.typcollation "
8056 "THEN t.typcollation ELSE 0 END AS typcollation "
8057 "FROM pg_catalog.pg_type t "
8058 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
8059 "WHERE t.oid = '%u'::pg_catalog.oid",
8060 tyinfo->dobj.catId.oid);
8064 /* We assume here that remoteVersion must be at least 70300 */
8065 appendPQExpBuffer(query, "SELECT typnotnull, "
8066 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
8067 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
8068 "typdefault, 0 AS typcollation "
8069 "FROM pg_catalog.pg_type "
8070 "WHERE oid = '%u'::pg_catalog.oid",
8071 tyinfo->dobj.catId.oid);
8074 res = PQexec(g_conn, query->data);
8075 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8077 /* Expecting a single result only */
8078 ntups = PQntuples(res);
8081 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
8082 "query returned %d rows instead of one: %s\n",
8084 ntups, query->data);
8088 typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
8089 typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
8090 if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
8091 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
8092 else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
8094 typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
8095 typdefault_is_literal = true; /* it needs quotes */
8099 typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
8102 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
8104 appendPQExpBuffer(q,
8105 "CREATE DOMAIN %s AS %s",
8106 fmtId(tyinfo->dobj.name),
8109 /* Print collation only if different from base type's collation */
8110 if (OidIsValid(typcollation))
8114 coll = findCollationByOid(typcollation);
8117 /* always schema-qualify, don't try to be smart */
8118 appendPQExpBuffer(q, " COLLATE %s.",
8119 fmtId(coll->dobj.namespace->dobj.name));
8120 appendPQExpBuffer(q, "%s",
8121 fmtId(coll->dobj.name));
8125 if (typnotnull[0] == 't')
8126 appendPQExpBuffer(q, " NOT NULL");
8128 if (typdefault != NULL)
8130 appendPQExpBuffer(q, " DEFAULT ");
8131 if (typdefault_is_literal)
8132 appendStringLiteralAH(q, typdefault, fout);
8134 appendPQExpBufferStr(q, typdefault);
8140 * Add any CHECK constraints for the domain
8142 for (i = 0; i < tyinfo->nDomChecks; i++)
8144 ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
8146 if (!domcheck->separate)
8147 appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
8148 fmtId(domcheck->dobj.name), domcheck->condef);
8151 appendPQExpBuffer(q, ";\n");
8154 * DROP must be fully qualified in case same name appears in pg_catalog
8156 appendPQExpBuffer(delq, "DROP DOMAIN %s.",
8157 fmtId(tyinfo->dobj.namespace->dobj.name));
8158 appendPQExpBuffer(delq, "%s;\n",
8159 fmtId(tyinfo->dobj.name));
8161 appendPQExpBuffer(labelq, "DOMAIN %s", fmtId(tyinfo->dobj.name));
8164 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8166 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8168 tyinfo->dobj.namespace->dobj.name,
8170 tyinfo->rolname, false,
8171 "DOMAIN", SECTION_PRE_DATA,
8172 q->data, delq->data, NULL,
8173 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8176 /* Dump Domain Comments and Security Labels */
8177 dumpComment(fout, labelq->data,
8178 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8179 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8180 dumpSecLabel(fout, labelq->data,
8181 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8182 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8184 destroyPQExpBuffer(q);
8185 destroyPQExpBuffer(delq);
8186 destroyPQExpBuffer(labelq);
8187 destroyPQExpBuffer(query);
8192 * writes out to fout the queries to recreate a user-defined stand-alone
8196 dumpCompositeType(Archive *fout, TypeInfo *tyinfo)
8198 PQExpBuffer q = createPQExpBuffer();
8199 PQExpBuffer dropped = createPQExpBuffer();
8200 PQExpBuffer delq = createPQExpBuffer();
8201 PQExpBuffer labelq = createPQExpBuffer();
8202 PQExpBuffer query = createPQExpBuffer();
8215 /* Set proper schema search path so type references list correctly */
8216 selectSourceSchema(tyinfo->dobj.namespace->dobj.name);
8218 /* Fetch type specific details */
8219 if (fout->remoteVersion >= 90100)
8222 * attcollation is new in 9.1. Since we only want to dump COLLATE
8223 * clauses for attributes whose collation is different from their
8224 * type's default, we use a CASE here to suppress uninteresting
8225 * attcollations cheaply. atttypid will be 0 for dropped columns;
8226 * collation does not matter for those.
8228 appendPQExpBuffer(query, "SELECT a.attname, "
8229 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8230 "a.attlen, a.attalign, a.attisdropped, "
8231 "CASE WHEN a.attcollation <> at.typcollation "
8232 "THEN a.attcollation ELSE 0 END AS attcollation, "
8234 "FROM pg_catalog.pg_type ct "
8235 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
8236 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
8237 "WHERE ct.oid = '%u'::pg_catalog.oid "
8238 "ORDER BY a.attnum ",
8239 tyinfo->dobj.catId.oid);
8244 * We assume here that remoteVersion must be at least 70300. Since
8245 * ALTER TYPE could not drop columns until 9.1, attisdropped should
8248 appendPQExpBuffer(query, "SELECT a.attname, "
8249 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
8250 "a.attlen, a.attalign, a.attisdropped, "
8251 "0 AS attcollation, "
8253 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
8254 "WHERE ct.oid = '%u'::pg_catalog.oid "
8255 "AND a.attrelid = ct.typrelid "
8256 "ORDER BY a.attnum ",
8257 tyinfo->dobj.catId.oid);
8260 res = PQexec(g_conn, query->data);
8261 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8263 ntups = PQntuples(res);
8265 i_attname = PQfnumber(res, "attname");
8266 i_atttypdefn = PQfnumber(res, "atttypdefn");
8267 i_attlen = PQfnumber(res, "attlen");
8268 i_attalign = PQfnumber(res, "attalign");
8269 i_attisdropped = PQfnumber(res, "attisdropped");
8270 i_attcollation = PQfnumber(res, "attcollation");
8271 i_typrelid = PQfnumber(res, "typrelid");
8275 Oid typrelid = atooid(PQgetvalue(res, 0, i_typrelid));
8277 binary_upgrade_set_type_oids_by_type_oid(q, tyinfo->dobj.catId.oid);
8278 binary_upgrade_set_pg_class_oids(q, typrelid, false);
8281 appendPQExpBuffer(q, "CREATE TYPE %s AS (",
8282 fmtId(tyinfo->dobj.name));
8285 for (i = 0; i < ntups; i++)
8294 attname = PQgetvalue(res, i, i_attname);
8295 atttypdefn = PQgetvalue(res, i, i_atttypdefn);
8296 attlen = PQgetvalue(res, i, i_attlen);
8297 attalign = PQgetvalue(res, i, i_attalign);
8298 attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
8299 attcollation = atooid(PQgetvalue(res, i, i_attcollation));
8301 if (attisdropped && !binary_upgrade)
8304 /* Format properly if not first attr */
8305 if (actual_atts++ > 0)
8306 appendPQExpBuffer(q, ",");
8307 appendPQExpBuffer(q, "\n\t");
8311 appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
8313 /* Add collation if not default for the column type */
8314 if (OidIsValid(attcollation))
8318 coll = findCollationByOid(attcollation);
8321 /* always schema-qualify, don't try to be smart */
8322 appendPQExpBuffer(q, " COLLATE %s.",
8323 fmtId(coll->dobj.namespace->dobj.name));
8324 appendPQExpBuffer(q, "%s",
8325 fmtId(coll->dobj.name));
8332 * This is a dropped attribute and we're in binary_upgrade mode.
8333 * Insert a placeholder for it in the CREATE TYPE command, and set
8334 * length and alignment with direct UPDATE to the catalogs
8335 * afterwards. See similar code in dumpTableSchema().
8337 appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
8339 /* stash separately for insertion after the CREATE TYPE */
8340 appendPQExpBuffer(dropped,
8341 "\n-- For binary upgrade, recreate dropped column.\n");
8342 appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
8344 "attalign = '%s', attbyval = false\n"
8345 "WHERE attname = ", attlen, attalign);
8346 appendStringLiteralAH(dropped, attname, fout);
8347 appendPQExpBuffer(dropped, "\n AND attrelid = ");
8348 appendStringLiteralAH(dropped, fmtId(tyinfo->dobj.name), fout);
8349 appendPQExpBuffer(dropped, "::pg_catalog.regclass;\n");
8351 appendPQExpBuffer(dropped, "ALTER TYPE %s ",
8352 fmtId(tyinfo->dobj.name));
8353 appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
8357 appendPQExpBuffer(q, "\n);\n");
8358 appendPQExpBufferStr(q, dropped->data);
8361 * DROP must be fully qualified in case same name appears in pg_catalog
8363 appendPQExpBuffer(delq, "DROP TYPE %s.",
8364 fmtId(tyinfo->dobj.namespace->dobj.name));
8365 appendPQExpBuffer(delq, "%s;\n",
8366 fmtId(tyinfo->dobj.name));
8368 appendPQExpBuffer(labelq, "TYPE %s", fmtId(tyinfo->dobj.name));
8371 binary_upgrade_extension_member(q, &tyinfo->dobj, labelq->data);
8373 ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
8375 tyinfo->dobj.namespace->dobj.name,
8377 tyinfo->rolname, false,
8378 "TYPE", SECTION_PRE_DATA,
8379 q->data, delq->data, NULL,
8380 tyinfo->dobj.dependencies, tyinfo->dobj.nDeps,
8384 /* Dump Type Comments and Security Labels */
8385 dumpComment(fout, labelq->data,
8386 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8387 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8388 dumpSecLabel(fout, labelq->data,
8389 tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
8390 tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
8393 destroyPQExpBuffer(q);
8394 destroyPQExpBuffer(dropped);
8395 destroyPQExpBuffer(delq);
8396 destroyPQExpBuffer(labelq);
8397 destroyPQExpBuffer(query);
8399 /* Dump any per-column comments */
8400 dumpCompositeTypeColComments(fout, tyinfo);
8404 * dumpCompositeTypeColComments
8405 * writes out to fout the queries to recreate comments on the columns of
8406 * a user-defined stand-alone composite type
8409 dumpCompositeTypeColComments(Archive *fout, TypeInfo *tyinfo)
8411 CommentItem *comments;
8422 query = createPQExpBuffer();
8424 /* We assume here that remoteVersion must be at least 70300 */
8425 appendPQExpBuffer(query,
8426 "SELECT c.tableoid, a.attname, a.attnum "
8427 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
8428 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
8429 " AND NOT a.attisdropped "
8430 "ORDER BY a.attnum ",
8433 /* Fetch column attnames */
8434 res = PQexec(g_conn, query->data);
8435 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
8437 ntups = PQntuples(res);
8441 destroyPQExpBuffer(query);
8445 pgClassOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "tableoid")));
8447 /* Search for comments associated with type's pg_class OID */
8448 ncomments = findComments(fout,
8453 /* If no comments exist, we're done */
8457 destroyPQExpBuffer(query);
8461 /* Build COMMENT ON statements */
8462 target = createPQExpBuffer();
8464 i_attnum = PQfnumber(res, "attnum");
8465 i_attname = PQfnumber(res, "attname");
8466 while (ncomments > 0)
8468 const char *attname;
8471 for (i = 0; i < ntups; i++)
8473 if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid)
8475 attname = PQgetvalue(res, i, i_attname);
8479 if (attname) /* just in case we don't find it */
8481 const char *descr = comments->descr;
8483 resetPQExpBuffer(target);
8484 appendPQExpBuffer(target, "COLUMN %s.",
8485 fmtId(tyinfo->dobj.name));
8486 appendPQExpBuffer(target, "%s",
8489 resetPQExpBuffer(query);
8490 appendPQExpBuffer(query, "COMMENT ON %s IS ", target->data);
8491 appendStringLiteralAH(query, descr, fout);
8492 appendPQExpBuffer(query, ";\n");
8494 ArchiveEntry(fout, nilCatalogId, createDumpId(),
8496 tyinfo->dobj.namespace->dobj.name,
8497 NULL, tyinfo->rolname,
8498 false, "COMMENT", SECTION_NONE,
8499 query->data, "", NULL,
8500 &(tyinfo->dobj.dumpId), 1,
8509 destroyPQExpBuffer(query);
8510 destroyPQExpBuffer(target);
8515 * writes out to fout the queries to create a shell type
8517 * We dump a shell definition in advance of the I/O functions for the type.
8520 dumpShellType(Archive *fout, ShellTypeInfo *stinfo)
8524 /* Skip if not to be dumped */
8525 if (!stinfo->dobj.dump || dataOnly)
8528 q = createPQExpBuffer();
8531 * Note the lack of a DROP command for the shell type; any required DROP
8532 * is driven off the base type entry, instead. This interacts with
8533 * _printTocEntry()'s use of the presence of a DROP command to decide
8534 * whether an entry needs an ALTER OWNER command. We don't want to alter
8535 * the shell type's owner immediately on creation; that should happen only
8536 * after it's filled in, otherwise the backend complains.
8540 binary_upgrade_set_type_oids_by_type_oid(q,
8541 stinfo->baseType->dobj.catId.oid);
8543 appendPQExpBuffer(q, "CREATE TYPE %s;\n",
8544 fmtId(stinfo->dobj.name));
8546 ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
8548 stinfo->dobj.namespace->dobj.name,
8550 stinfo->baseType->rolname, false,
8551 "SHELL TYPE", SECTION_PRE_DATA,
8553 stinfo->dobj.dependencies, stinfo->dobj.nDeps,
8556 destroyPQExpBuffer(q);
8560 * Determine whether we want to dump definitions for procedural languages.
8561 * Since the languages themselves don't have schemas, we can't rely on
8562 * the normal schema-based selection mechanism. We choose to dump them
8563 * whenever neither --schema nor --table was given. (Before 8.1, we used
8564 * the dump flag of the PL's call handler function, but in 8.1 this will
8565 * probably always be false since call handlers are created in pg_catalog.)
8567 * For some backwards compatibility with the older behavior, we forcibly
8568 * dump a PL if its handler function (and validator if any) are in a
8569 * dumpable namespace. That case is not checked here.
8571 * Also, if the PL belongs to an extension, we do not use this heuristic.
8572 * That case isn't checked here either.
8575 shouldDumpProcLangs(void)
8577 if (!include_everything)
8579 /* And they're schema not data */
8587 * writes out to fout the queries to recreate a user-defined
8588 * procedural language
8591 dumpProcLang(Archive *fout, ProcLangInfo *plang)
8600 FuncInfo *inlineInfo = NULL;
8601 FuncInfo *validatorInfo = NULL;
8603 /* Skip if not to be dumped */
8604 if (!plang->dobj.dump || dataOnly)
8608 * Try to find the support function(s). It is not an error if we don't
8609 * find them --- if the functions are in the pg_catalog schema, as is
8610 * standard in 8.1 and up, then we won't have loaded them. (In this case
8611 * we will emit a parameterless CREATE LANGUAGE command, which will
8612 * require PL template knowledge in the backend to reload.)
8615 funcInfo = findFuncByOid(plang->lanplcallfoid);
8616 if (funcInfo != NULL && !funcInfo->dobj.dump)
8617 funcInfo = NULL; /* treat not-dumped same as not-found */
8619 if (OidIsValid(plang->laninline))
8621 inlineInfo = findFuncByOid(plang->laninline);
8622 if (inlineInfo != NULL && !inlineInfo->dobj.dump)
8626 if (OidIsValid(plang->lanvalidator))
8628 validatorInfo = findFuncByOid(plang->lanvalidator);
8629 if (validatorInfo != NULL && !validatorInfo->dobj.dump)
8630 validatorInfo = NULL;
8634 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
8635 * with parameters. Otherwise, dump only if shouldDumpProcLangs() says to
8638 * However, for a language that belongs to an extension, we must not use
8639 * the shouldDumpProcLangs heuristic, but just dump the language iff we're
8640 * told to (via dobj.dump). Generally the support functions will belong
8641 * to the same extension and so have the same dump flags ... if they
8642 * don't, this might not work terribly nicely.
8644 useParams = (funcInfo != NULL &&
8645 (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
8646 (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
8648 if (!plang->dobj.ext_member)
8650 if (!useParams && !shouldDumpProcLangs())
8654 defqry = createPQExpBuffer();
8655 delqry = createPQExpBuffer();
8656 labelq = createPQExpBuffer();
8658 qlanname = pg_strdup(fmtId(plang->dobj.name));
8661 * If dumping a HANDLER clause, treat the language as being in the handler
8662 * function's schema; this avoids cluttering the HANDLER clause. Otherwise
8663 * it doesn't really have a schema.
8666 lanschema = funcInfo->dobj.namespace->dobj.name;
8670 appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
8675 appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
8676 plang->lanpltrusted ? "TRUSTED " : "",
8678 appendPQExpBuffer(defqry, " HANDLER %s",
8679 fmtId(funcInfo->dobj.name));
8680 if (OidIsValid(plang->laninline))
8682 appendPQExpBuffer(defqry, " INLINE ");
8683 /* Cope with possibility that inline is in different schema */
8684 if (inlineInfo->dobj.namespace != funcInfo->dobj.namespace)
8685 appendPQExpBuffer(defqry, "%s.",
8686 fmtId(inlineInfo->dobj.namespace->dobj.name));
8687 appendPQExpBuffer(defqry, "%s",
8688 fmtId(inlineInfo->dobj.name));
8690 if (OidIsValid(plang->lanvalidator))
8692 appendPQExpBuffer(defqry, " VALIDATOR ");
8693 /* Cope with possibility that validator is in different schema */
8694 if (validatorInfo->dobj.namespace != funcInfo->dobj.namespace)
8695 appendPQExpBuffer(defqry, "%s.",
8696 fmtId(validatorInfo->dobj.namespace->dobj.name));
8697 appendPQExpBuffer(defqry, "%s",
8698 fmtId(validatorInfo->dobj.name));
8704 * If not dumping parameters, then use CREATE OR REPLACE so that the
8705 * command will not fail if the language is preinstalled in the target
8706 * database. We restrict the use of REPLACE to this case so as to
8707 * eliminate the risk of replacing a language with incompatible
8708 * parameter settings: this command will only succeed at all if there
8709 * is a pg_pltemplate entry, and if there is one, the existing entry
8710 * must match it too.
8712 appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
8715 appendPQExpBuffer(defqry, ";\n");
8717 appendPQExpBuffer(labelq, "LANGUAGE %s", qlanname);
8720 binary_upgrade_extension_member(defqry, &plang->dobj, labelq->data);
8722 ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
8724 lanschema, NULL, plang->lanowner,
8725 false, "PROCEDURAL LANGUAGE", SECTION_PRE_DATA,
8726 defqry->data, delqry->data, NULL,
8727 plang->dobj.dependencies, plang->dobj.nDeps,
8730 /* Dump Proc Lang Comments and Security Labels */
8731 dumpComment(fout, labelq->data,
8733 plang->dobj.catId, 0, plang->dobj.dumpId);
8734 dumpSecLabel(fout, labelq->data,
8736 plang->dobj.catId, 0, plang->dobj.dumpId);
8738 if (plang->lanpltrusted)
8739 dumpACL(fout, plang->dobj.catId, plang->dobj.dumpId, "LANGUAGE",
8740 qlanname, NULL, plang->dobj.name,
8742 plang->lanowner, plang->lanacl);
8746 destroyPQExpBuffer(defqry);
8747 destroyPQExpBuffer(delqry);
8748 destroyPQExpBuffer(labelq);
8752 * format_function_arguments: generate function name and argument list
8754 * This is used when we can rely on pg_get_function_arguments to format
8755 * the argument list.
8758 format_function_arguments(FuncInfo *finfo, char *funcargs)
8762 initPQExpBuffer(&fn);
8763 appendPQExpBuffer(&fn, "%s(%s)", fmtId(finfo->dobj.name), funcargs);
8768 * format_function_arguments_old: generate function name and argument list
8770 * The argument type names are qualified if needed. The function name
8771 * is never qualified.
8773 * This is used only with pre-8.4 servers, so we aren't expecting to see
8774 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
8776 * Any or all of allargtypes, argmodes, argnames may be NULL.
8779 format_function_arguments_old(FuncInfo *finfo, int nallargs,
8787 initPQExpBuffer(&fn);
8788 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8789 for (j = 0; j < nallargs; j++)
8793 const char *argmode;
8794 const char *argname;
8796 typid = allargtypes ? atooid(allargtypes[j]) : finfo->argtypes[j];
8797 typname = getFormattedTypeName(typid, zeroAsOpaque);
8801 switch (argmodes[j][0])
8806 case PROARGMODE_OUT:
8809 case PROARGMODE_INOUT:
8813 write_msg(NULL, "WARNING: bogus value in proargmodes array\n");
8821 argname = argnames ? argnames[j] : (char *) NULL;
8822 if (argname && argname[0] == '\0')
8825 appendPQExpBuffer(&fn, "%s%s%s%s%s",
8826 (j > 0) ? ", " : "",
8828 argname ? fmtId(argname) : "",
8833 appendPQExpBuffer(&fn, ")");
8838 * format_function_signature: generate function name and argument list
8840 * This is like format_function_arguments_old except that only a minimal
8841 * list of input argument types is generated; this is sufficient to
8842 * reference the function, but not to define it.
8844 * If honor_quotes is false then the function name is never quoted.
8845 * This is appropriate for use in TOC tags, but not in SQL commands.
8848 format_function_signature(FuncInfo *finfo, bool honor_quotes)
8853 initPQExpBuffer(&fn);
8855 appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
8857 appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
8858 for (j = 0; j < finfo->nargs; j++)
8862 typname = getFormattedTypeName(finfo->argtypes[j], zeroAsOpaque);
8864 appendPQExpBuffer(&fn, "%s%s",
8865 (j > 0) ? ", " : "",
8869 appendPQExpBuffer(&fn, ")");
8876 * dump out one function
8879 dumpFunc(Archive *fout, FuncInfo *finfo)
8887 char *funcsig; /* identity signature */
8888 char *funcfullsig; /* full signature */
8897 char *proallargtypes;
8910 char **allargtypes = NULL;
8911 char **argmodes = NULL;
8912 char **argnames = NULL;
8913 char **configitems = NULL;
8914 int nconfigitems = 0;
8917 /* Skip if not to be dumped */
8918 if (!finfo->dobj.dump || dataOnly)
8921 query = createPQExpBuffer();
8922 q = createPQExpBuffer();
8923 delqry = createPQExpBuffer();
8924 labelq = createPQExpBuffer();
8925 asPart = createPQExpBuffer();
8927 /* Set proper schema search path so type references list correctly */
8928 selectSourceSchema(finfo->dobj.namespace->dobj.name);
8930 /* Fetch function-specific details */
8931 if (g_fout->remoteVersion >= 80400)
8934 * In 8.4 and up we rely on pg_get_function_arguments and
8935 * pg_get_function_result instead of examining proallargtypes etc.
8937 appendPQExpBuffer(query,
8938 "SELECT proretset, prosrc, probin, "
8939 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
8940 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
8941 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
8942 "proiswindow, provolatile, proisstrict, prosecdef, "
8943 "proconfig, procost, prorows, "
8944 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8945 "FROM pg_catalog.pg_proc "
8946 "WHERE oid = '%u'::pg_catalog.oid",
8947 finfo->dobj.catId.oid);
8949 else if (g_fout->remoteVersion >= 80300)
8951 appendPQExpBuffer(query,
8952 "SELECT proretset, prosrc, probin, "
8953 "proallargtypes, proargmodes, proargnames, "
8954 "false AS proiswindow, "
8955 "provolatile, proisstrict, prosecdef, "
8956 "proconfig, procost, prorows, "
8957 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8958 "FROM pg_catalog.pg_proc "
8959 "WHERE oid = '%u'::pg_catalog.oid",
8960 finfo->dobj.catId.oid);
8962 else if (g_fout->remoteVersion >= 80100)
8964 appendPQExpBuffer(query,
8965 "SELECT proretset, prosrc, probin, "
8966 "proallargtypes, proargmodes, proargnames, "
8967 "false AS proiswindow, "
8968 "provolatile, proisstrict, prosecdef, "
8969 "null AS proconfig, 0 AS procost, 0 AS prorows, "
8970 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8971 "FROM pg_catalog.pg_proc "
8972 "WHERE oid = '%u'::pg_catalog.oid",
8973 finfo->dobj.catId.oid);
8975 else if (g_fout->remoteVersion >= 80000)
8977 appendPQExpBuffer(query,
8978 "SELECT proretset, prosrc, probin, "
8979 "null AS proallargtypes, "
8980 "null AS proargmodes, "
8982 "false AS proiswindow, "
8983 "provolatile, proisstrict, prosecdef, "
8984 "null AS proconfig, 0 AS procost, 0 AS prorows, "
8985 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
8986 "FROM pg_catalog.pg_proc "
8987 "WHERE oid = '%u'::pg_catalog.oid",
8988 finfo->dobj.catId.oid);
8990 else if (g_fout->remoteVersion >= 70300)
8992 appendPQExpBuffer(query,
8993 "SELECT proretset, prosrc, probin, "
8994 "null AS proallargtypes, "
8995 "null AS proargmodes, "
8996 "null AS proargnames, "
8997 "false AS proiswindow, "
8998 "provolatile, proisstrict, prosecdef, "
8999 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9000 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
9001 "FROM pg_catalog.pg_proc "
9002 "WHERE oid = '%u'::pg_catalog.oid",
9003 finfo->dobj.catId.oid);
9005 else if (g_fout->remoteVersion >= 70100)
9007 appendPQExpBuffer(query,
9008 "SELECT proretset, prosrc, probin, "
9009 "null AS proallargtypes, "
9010 "null AS proargmodes, "
9011 "null AS proargnames, "
9012 "false AS proiswindow, "
9013 "case when proiscachable then 'i' else 'v' end AS provolatile, "
9015 "false AS prosecdef, "
9016 "null AS proconfig, 0 AS procost, 0 AS prorows, "
9017 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9019 "WHERE oid = '%u'::oid",
9020 finfo->dobj.catId.oid);
9024 appendPQExpBuffer(query,
9025 "SELECT proretset, prosrc, probin, "
9026 "null AS proallargtypes, "
9027 "null AS proargmodes, "
9028 "null AS proargnames, "
9029 "false AS proiswindow, "
9030 "CASE WHEN proiscachable THEN 'i' ELSE 'v' END AS provolatile, "
9031 "false AS proisstrict, "
9032 "false AS prosecdef, "
9033 "NULL AS proconfig, 0 AS procost, 0 AS prorows, "
9034 "(SELECT lanname FROM pg_language WHERE oid = prolang) AS lanname "
9036 "WHERE oid = '%u'::oid",
9037 finfo->dobj.catId.oid);
9040 res = PQexec(g_conn, query->data);
9041 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9043 /* Expecting a single result only */
9044 ntups = PQntuples(res);
9047 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9048 "query returned %d rows instead of one: %s\n",
9050 ntups, query->data);
9054 proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
9055 prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
9056 probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
9057 if (g_fout->remoteVersion >= 80400)
9059 funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
9060 funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
9061 funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
9062 proallargtypes = proargmodes = proargnames = NULL;
9066 proallargtypes = PQgetvalue(res, 0, PQfnumber(res, "proallargtypes"));
9067 proargmodes = PQgetvalue(res, 0, PQfnumber(res, "proargmodes"));
9068 proargnames = PQgetvalue(res, 0, PQfnumber(res, "proargnames"));
9069 funcargs = funciargs = funcresult = NULL;
9071 proiswindow = PQgetvalue(res, 0, PQfnumber(res, "proiswindow"));
9072 provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
9073 proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
9074 prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
9075 proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
9076 procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
9077 prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
9078 lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
9081 * See backend/commands/functioncmds.c for details of how the 'AS' clause
9082 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
9083 * versions would set it to "-". There are no known cases in which prosrc
9084 * is unused, so the tests below for "-" are probably useless.
9086 if (probin[0] != '\0' && strcmp(probin, "-") != 0)
9088 appendPQExpBuffer(asPart, "AS ");
9089 appendStringLiteralAH(asPart, probin, fout);
9090 if (strcmp(prosrc, "-") != 0)
9092 appendPQExpBuffer(asPart, ", ");
9095 * where we have bin, use dollar quoting if allowed and src
9096 * contains quote or backslash; else use regular quoting.
9098 if (disable_dollar_quoting ||
9099 (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
9100 appendStringLiteralAH(asPart, prosrc, fout);
9102 appendStringLiteralDQ(asPart, prosrc, NULL);
9107 if (strcmp(prosrc, "-") != 0)
9109 appendPQExpBuffer(asPart, "AS ");
9110 /* with no bin, dollar quote src unconditionally if allowed */
9111 if (disable_dollar_quoting)
9112 appendStringLiteralAH(asPart, prosrc, fout);
9114 appendStringLiteralDQ(asPart, prosrc, NULL);
9118 nallargs = finfo->nargs; /* unless we learn different from allargs */
9120 if (proallargtypes && *proallargtypes)
9124 if (!parsePGArray(proallargtypes, &allargtypes, &nitems) ||
9125 nitems < finfo->nargs)
9127 write_msg(NULL, "WARNING: could not parse proallargtypes array\n");
9136 if (proargmodes && *proargmodes)
9140 if (!parsePGArray(proargmodes, &argmodes, &nitems) ||
9143 write_msg(NULL, "WARNING: could not parse proargmodes array\n");
9150 if (proargnames && *proargnames)
9154 if (!parsePGArray(proargnames, &argnames, &nitems) ||
9157 write_msg(NULL, "WARNING: could not parse proargnames array\n");
9164 if (proconfig && *proconfig)
9166 if (!parsePGArray(proconfig, &configitems, &nconfigitems))
9168 write_msg(NULL, "WARNING: could not parse proconfig array\n");
9178 /* 8.4 or later; we rely on server-side code for most of the work */
9179 funcfullsig = format_function_arguments(finfo, funcargs);
9180 funcsig = format_function_arguments(finfo, funciargs);
9184 /* pre-8.4, do it ourselves */
9185 funcsig = format_function_arguments_old(finfo, nallargs, allargtypes,
9186 argmodes, argnames);
9187 funcfullsig = funcsig;
9190 funcsig_tag = format_function_signature(finfo, false);
9193 * DROP must be fully qualified in case same name appears in pg_catalog
9195 appendPQExpBuffer(delqry, "DROP FUNCTION %s.%s;\n",
9196 fmtId(finfo->dobj.namespace->dobj.name),
9199 appendPQExpBuffer(q, "CREATE FUNCTION %s ", funcfullsig);
9201 appendPQExpBuffer(q, "RETURNS %s", funcresult);
9204 rettypename = getFormattedTypeName(finfo->prorettype, zeroAsOpaque);
9205 appendPQExpBuffer(q, "RETURNS %s%s",
9206 (proretset[0] == 't') ? "SETOF " : "",
9211 appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
9213 if (proiswindow[0] == 't')
9214 appendPQExpBuffer(q, " WINDOW");
9216 if (provolatile[0] != PROVOLATILE_VOLATILE)
9218 if (provolatile[0] == PROVOLATILE_IMMUTABLE)
9219 appendPQExpBuffer(q, " IMMUTABLE");
9220 else if (provolatile[0] == PROVOLATILE_STABLE)
9221 appendPQExpBuffer(q, " STABLE");
9222 else if (provolatile[0] != PROVOLATILE_VOLATILE)
9224 write_msg(NULL, "unrecognized provolatile value for function \"%s\"\n",
9230 if (proisstrict[0] == 't')
9231 appendPQExpBuffer(q, " STRICT");
9233 if (prosecdef[0] == 't')
9234 appendPQExpBuffer(q, " SECURITY DEFINER");
9237 * COST and ROWS are emitted only if present and not default, so as not to
9238 * break backwards-compatibility of the dump without need. Keep this code
9239 * in sync with the defaults in functioncmds.c.
9241 if (strcmp(procost, "0") != 0)
9243 if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
9245 /* default cost is 1 */
9246 if (strcmp(procost, "1") != 0)
9247 appendPQExpBuffer(q, " COST %s", procost);
9251 /* default cost is 100 */
9252 if (strcmp(procost, "100") != 0)
9253 appendPQExpBuffer(q, " COST %s", procost);
9256 if (proretset[0] == 't' &&
9257 strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
9258 appendPQExpBuffer(q, " ROWS %s", prorows);
9260 for (i = 0; i < nconfigitems; i++)
9262 /* we feel free to scribble on configitems[] here */
9263 char *configitem = configitems[i];
9266 pos = strchr(configitem, '=');
9270 appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
9273 * Some GUC variable names are 'LIST' type and hence must not be
9276 if (pg_strcasecmp(configitem, "DateStyle") == 0
9277 || pg_strcasecmp(configitem, "search_path") == 0)
9278 appendPQExpBuffer(q, "%s", pos);
9280 appendStringLiteralAH(q, pos, fout);
9283 appendPQExpBuffer(q, "\n %s;\n", asPart->data);
9285 appendPQExpBuffer(labelq, "FUNCTION %s", funcsig);
9288 binary_upgrade_extension_member(q, &finfo->dobj, labelq->data);
9290 ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
9292 finfo->dobj.namespace->dobj.name,
9294 finfo->rolname, false,
9295 "FUNCTION", SECTION_PRE_DATA,
9296 q->data, delqry->data, NULL,
9297 finfo->dobj.dependencies, finfo->dobj.nDeps,
9300 /* Dump Function Comments and Security Labels */
9301 dumpComment(fout, labelq->data,
9302 finfo->dobj.namespace->dobj.name, finfo->rolname,
9303 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9304 dumpSecLabel(fout, labelq->data,
9305 finfo->dobj.namespace->dobj.name, finfo->rolname,
9306 finfo->dobj.catId, 0, finfo->dobj.dumpId);
9308 dumpACL(fout, finfo->dobj.catId, finfo->dobj.dumpId, "FUNCTION",
9309 funcsig, NULL, funcsig_tag,
9310 finfo->dobj.namespace->dobj.name,
9311 finfo->rolname, finfo->proacl);
9315 destroyPQExpBuffer(query);
9316 destroyPQExpBuffer(q);
9317 destroyPQExpBuffer(delqry);
9318 destroyPQExpBuffer(labelq);
9319 destroyPQExpBuffer(asPart);
9334 * Dump a user-defined cast
9337 dumpCast(Archive *fout, CastInfo *cast)
9342 FuncInfo *funcInfo = NULL;
9344 /* Skip if not to be dumped */
9345 if (!cast->dobj.dump || dataOnly)
9348 /* Cannot dump if we don't have the cast function's info */
9349 if (OidIsValid(cast->castfunc))
9351 funcInfo = findFuncByOid(cast->castfunc);
9352 if (funcInfo == NULL)
9357 * As per discussion we dump casts if one or more of the underlying
9358 * objects (the conversion function and the two data types) are not
9359 * builtin AND if all of the non-builtin objects are included in the dump.
9360 * Builtin meaning, the namespace name does not start with "pg_".
9362 * However, for a cast that belongs to an extension, we must not use this
9363 * heuristic, but just dump the cast iff we're told to (via dobj.dump).
9365 if (!cast->dobj.ext_member)
9367 TypeInfo *sourceInfo = findTypeByOid(cast->castsource);
9368 TypeInfo *targetInfo = findTypeByOid(cast->casttarget);
9370 if (sourceInfo == NULL || targetInfo == NULL)
9374 * Skip this cast if all objects are from pg_
9376 if ((funcInfo == NULL ||
9377 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) == 0) &&
9378 strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) == 0 &&
9379 strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) == 0)
9383 * Skip cast if function isn't from pg_ and is not to be dumped.
9386 strncmp(funcInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9387 !funcInfo->dobj.dump)
9391 * Same for the source type
9393 if (strncmp(sourceInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9394 !sourceInfo->dobj.dump)
9398 * and the target type.
9400 if (strncmp(targetInfo->dobj.namespace->dobj.name, "pg_", 3) != 0 &&
9401 !targetInfo->dobj.dump)
9405 /* Make sure we are in proper schema (needed for getFormattedTypeName) */
9406 selectSourceSchema("pg_catalog");
9408 defqry = createPQExpBuffer();
9409 delqry = createPQExpBuffer();
9410 labelq = createPQExpBuffer();
9412 appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
9413 getFormattedTypeName(cast->castsource, zeroAsNone),
9414 getFormattedTypeName(cast->casttarget, zeroAsNone));
9416 appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
9417 getFormattedTypeName(cast->castsource, zeroAsNone),
9418 getFormattedTypeName(cast->casttarget, zeroAsNone));
9420 switch (cast->castmethod)
9422 case COERCION_METHOD_BINARY:
9423 appendPQExpBuffer(defqry, "WITHOUT FUNCTION");
9425 case COERCION_METHOD_INOUT:
9426 appendPQExpBuffer(defqry, "WITH INOUT");
9428 case COERCION_METHOD_FUNCTION:
9431 * Always qualify the function name, in case it is not in
9432 * pg_catalog schema (format_function_signature won't qualify it).
9434 appendPQExpBuffer(defqry, "WITH FUNCTION %s.",
9435 fmtId(funcInfo->dobj.namespace->dobj.name));
9436 appendPQExpBuffer(defqry, "%s",
9437 format_function_signature(funcInfo, true));
9440 write_msg(NULL, "WARNING: bogus value in pg_cast.castmethod field\n");
9443 if (cast->castcontext == 'a')
9444 appendPQExpBuffer(defqry, " AS ASSIGNMENT");
9445 else if (cast->castcontext == 'i')
9446 appendPQExpBuffer(defqry, " AS IMPLICIT");
9447 appendPQExpBuffer(defqry, ";\n");
9449 appendPQExpBuffer(labelq, "CAST (%s AS %s)",
9450 getFormattedTypeName(cast->castsource, zeroAsNone),
9451 getFormattedTypeName(cast->casttarget, zeroAsNone));
9454 binary_upgrade_extension_member(defqry, &cast->dobj, labelq->data);
9456 ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
9458 "pg_catalog", NULL, "",
9459 false, "CAST", SECTION_PRE_DATA,
9460 defqry->data, delqry->data, NULL,
9461 cast->dobj.dependencies, cast->dobj.nDeps,
9464 /* Dump Cast Comments */
9465 dumpComment(fout, labelq->data,
9467 cast->dobj.catId, 0, cast->dobj.dumpId);
9469 destroyPQExpBuffer(defqry);
9470 destroyPQExpBuffer(delqry);
9471 destroyPQExpBuffer(labelq);
9476 * write out a single operator definition
9479 dumpOpr(Archive *fout, OprInfo *oprinfo)
9486 PQExpBuffer details;
9511 /* Skip if not to be dumped */
9512 if (!oprinfo->dobj.dump || dataOnly)
9516 * some operators are invalid because they were the result of user
9517 * defining operators before commutators exist
9519 if (!OidIsValid(oprinfo->oprcode))
9522 query = createPQExpBuffer();
9523 q = createPQExpBuffer();
9524 delq = createPQExpBuffer();
9525 labelq = createPQExpBuffer();
9526 oprid = createPQExpBuffer();
9527 details = createPQExpBuffer();
9529 /* Make sure we are in proper schema so regoperator works correctly */
9530 selectSourceSchema(oprinfo->dobj.namespace->dobj.name);
9532 if (g_fout->remoteVersion >= 80300)
9534 appendPQExpBuffer(query, "SELECT oprkind, "
9535 "oprcode::pg_catalog.regprocedure, "
9536 "oprleft::pg_catalog.regtype, "
9537 "oprright::pg_catalog.regtype, "
9538 "oprcom::pg_catalog.regoperator, "
9539 "oprnegate::pg_catalog.regoperator, "
9540 "oprrest::pg_catalog.regprocedure, "
9541 "oprjoin::pg_catalog.regprocedure, "
9542 "oprcanmerge, oprcanhash "
9543 "FROM pg_catalog.pg_operator "
9544 "WHERE oid = '%u'::pg_catalog.oid",
9545 oprinfo->dobj.catId.oid);
9547 else if (g_fout->remoteVersion >= 70300)
9549 appendPQExpBuffer(query, "SELECT oprkind, "
9550 "oprcode::pg_catalog.regprocedure, "
9551 "oprleft::pg_catalog.regtype, "
9552 "oprright::pg_catalog.regtype, "
9553 "oprcom::pg_catalog.regoperator, "
9554 "oprnegate::pg_catalog.regoperator, "
9555 "oprrest::pg_catalog.regprocedure, "
9556 "oprjoin::pg_catalog.regprocedure, "
9557 "(oprlsortop != 0) AS oprcanmerge, "
9559 "FROM pg_catalog.pg_operator "
9560 "WHERE oid = '%u'::pg_catalog.oid",
9561 oprinfo->dobj.catId.oid);
9563 else if (g_fout->remoteVersion >= 70100)
9565 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9566 "CASE WHEN oprleft = 0 THEN '-' "
9567 "ELSE format_type(oprleft, NULL) END AS oprleft, "
9568 "CASE WHEN oprright = 0 THEN '-' "
9569 "ELSE format_type(oprright, NULL) END AS oprright, "
9570 "oprcom, oprnegate, oprrest, oprjoin, "
9571 "(oprlsortop != 0) AS oprcanmerge, "
9574 "WHERE oid = '%u'::oid",
9575 oprinfo->dobj.catId.oid);
9579 appendPQExpBuffer(query, "SELECT oprkind, oprcode, "
9580 "CASE WHEN oprleft = 0 THEN '-'::name "
9581 "ELSE (SELECT typname FROM pg_type WHERE oid = oprleft) END AS oprleft, "
9582 "CASE WHEN oprright = 0 THEN '-'::name "
9583 "ELSE (SELECT typname FROM pg_type WHERE oid = oprright) END AS oprright, "
9584 "oprcom, oprnegate, oprrest, oprjoin, "
9585 "(oprlsortop != 0) AS oprcanmerge, "
9588 "WHERE oid = '%u'::oid",
9589 oprinfo->dobj.catId.oid);
9592 res = PQexec(g_conn, query->data);
9593 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9595 /* Expecting a single result only */
9596 ntups = PQntuples(res);
9599 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9600 "query returned %d rows instead of one: %s\n",
9602 ntups, query->data);
9606 i_oprkind = PQfnumber(res, "oprkind");
9607 i_oprcode = PQfnumber(res, "oprcode");
9608 i_oprleft = PQfnumber(res, "oprleft");
9609 i_oprright = PQfnumber(res, "oprright");
9610 i_oprcom = PQfnumber(res, "oprcom");
9611 i_oprnegate = PQfnumber(res, "oprnegate");
9612 i_oprrest = PQfnumber(res, "oprrest");
9613 i_oprjoin = PQfnumber(res, "oprjoin");
9614 i_oprcanmerge = PQfnumber(res, "oprcanmerge");
9615 i_oprcanhash = PQfnumber(res, "oprcanhash");
9617 oprkind = PQgetvalue(res, 0, i_oprkind);
9618 oprcode = PQgetvalue(res, 0, i_oprcode);
9619 oprleft = PQgetvalue(res, 0, i_oprleft);
9620 oprright = PQgetvalue(res, 0, i_oprright);
9621 oprcom = PQgetvalue(res, 0, i_oprcom);
9622 oprnegate = PQgetvalue(res, 0, i_oprnegate);
9623 oprrest = PQgetvalue(res, 0, i_oprrest);
9624 oprjoin = PQgetvalue(res, 0, i_oprjoin);
9625 oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
9626 oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
9628 appendPQExpBuffer(details, " PROCEDURE = %s",
9629 convertRegProcReference(oprcode));
9631 appendPQExpBuffer(oprid, "%s (",
9632 oprinfo->dobj.name);
9635 * right unary means there's a left arg and left unary means there's a
9638 if (strcmp(oprkind, "r") == 0 ||
9639 strcmp(oprkind, "b") == 0)
9641 if (g_fout->remoteVersion >= 70100)
9644 name = fmtId(oprleft);
9645 appendPQExpBuffer(details, ",\n LEFTARG = %s", name);
9646 appendPQExpBuffer(oprid, "%s", name);
9649 appendPQExpBuffer(oprid, "NONE");
9651 if (strcmp(oprkind, "l") == 0 ||
9652 strcmp(oprkind, "b") == 0)
9654 if (g_fout->remoteVersion >= 70100)
9657 name = fmtId(oprright);
9658 appendPQExpBuffer(details, ",\n RIGHTARG = %s", name);
9659 appendPQExpBuffer(oprid, ", %s)", name);
9662 appendPQExpBuffer(oprid, ", NONE)");
9664 name = convertOperatorReference(oprcom);
9666 appendPQExpBuffer(details, ",\n COMMUTATOR = %s", name);
9668 name = convertOperatorReference(oprnegate);
9670 appendPQExpBuffer(details, ",\n NEGATOR = %s", name);
9672 if (strcmp(oprcanmerge, "t") == 0)
9673 appendPQExpBuffer(details, ",\n MERGES");
9675 if (strcmp(oprcanhash, "t") == 0)
9676 appendPQExpBuffer(details, ",\n HASHES");
9678 name = convertRegProcReference(oprrest);
9680 appendPQExpBuffer(details, ",\n RESTRICT = %s", name);
9682 name = convertRegProcReference(oprjoin);
9684 appendPQExpBuffer(details, ",\n JOIN = %s", name);
9687 * DROP must be fully qualified in case same name appears in pg_catalog
9689 appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
9690 fmtId(oprinfo->dobj.namespace->dobj.name),
9693 appendPQExpBuffer(q, "CREATE OPERATOR %s (\n%s\n);\n",
9694 oprinfo->dobj.name, details->data);
9696 appendPQExpBuffer(labelq, "OPERATOR %s", oprid->data);
9699 binary_upgrade_extension_member(q, &oprinfo->dobj, labelq->data);
9701 ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
9703 oprinfo->dobj.namespace->dobj.name,
9706 false, "OPERATOR", SECTION_PRE_DATA,
9707 q->data, delq->data, NULL,
9708 oprinfo->dobj.dependencies, oprinfo->dobj.nDeps,
9711 /* Dump Operator Comments */
9712 dumpComment(fout, labelq->data,
9713 oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
9714 oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
9718 destroyPQExpBuffer(query);
9719 destroyPQExpBuffer(q);
9720 destroyPQExpBuffer(delq);
9721 destroyPQExpBuffer(labelq);
9722 destroyPQExpBuffer(oprid);
9723 destroyPQExpBuffer(details);
9727 * Convert a function reference obtained from pg_operator
9729 * Returns what to print, or NULL if function references is InvalidOid
9731 * In 7.3 the input is a REGPROCEDURE display; we have to strip the
9732 * argument-types part. In prior versions, the input is a REGPROC display.
9735 convertRegProcReference(const char *proc)
9737 /* In all cases "-" means a null reference */
9738 if (strcmp(proc, "-") == 0)
9741 if (g_fout->remoteVersion >= 70300)
9747 name = pg_strdup(proc);
9748 /* find non-double-quoted left paren */
9750 for (paren = name; *paren; paren++)
9752 if (*paren == '(' && !inquote)
9763 /* REGPROC before 7.3 does not quote its result */
9768 * Convert an operator cross-reference obtained from pg_operator
9770 * Returns what to print, or NULL to print nothing
9772 * In 7.3 and up the input is a REGOPERATOR display; we have to strip the
9773 * argument-types part, and add OPERATOR() decoration if the name is
9774 * schema-qualified. In older versions, the input is just a numeric OID,
9775 * which we search our operator list for.
9778 convertOperatorReference(const char *opr)
9782 /* In all cases "0" means a null reference */
9783 if (strcmp(opr, "0") == 0)
9786 if (g_fout->remoteVersion >= 70300)
9794 name = pg_strdup(opr);
9795 /* find non-double-quoted left paren, and check for non-quoted dot */
9798 for (ptr = name; *ptr; ptr++)
9802 else if (*ptr == '.' && !inquote)
9804 else if (*ptr == '(' && !inquote)
9810 /* If not schema-qualified, don't need to add OPERATOR() */
9813 oname = pg_malloc(strlen(name) + 11);
9814 sprintf(oname, "OPERATOR(%s)", name);
9819 oprInfo = findOprByOid(atooid(opr));
9820 if (oprInfo == NULL)
9822 write_msg(NULL, "WARNING: could not find operator with OID %s\n",
9826 return oprInfo->dobj.name;
9830 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
9832 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
9833 * argument lists of these functions are predetermined. Note that the
9834 * caller should ensure we are in the proper schema, because the results
9835 * are search path dependent!
9838 convertTSFunction(Oid funcOid)
9845 snprintf(query, sizeof(query),
9846 "SELECT '%u'::pg_catalog.regproc", funcOid);
9847 res = PQexec(g_conn, query);
9848 check_sql_result(res, g_conn, query, PGRES_TUPLES_OK);
9850 ntups = PQntuples(res);
9853 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9854 "query returned %d rows instead of one: %s\n",
9860 result = pg_strdup(PQgetvalue(res, 0, 0));
9870 * write out a single operator class definition
9873 dumpOpclass(Archive *fout, OpclassInfo *opcinfo)
9885 int i_opcfamilyname;
9892 int i_sortfamilynsp;
9895 int i_amproclefttype;
9896 int i_amprocrighttype;
9901 char *opcfamilyname;
9908 char *sortfamilynsp;
9911 char *amproclefttype;
9912 char *amprocrighttype;
9916 /* Skip if not to be dumped */
9917 if (!opcinfo->dobj.dump || dataOnly)
9921 * XXX currently we do not implement dumping of operator classes from
9922 * pre-7.3 databases. This could be done but it seems not worth the
9925 if (g_fout->remoteVersion < 70300)
9928 query = createPQExpBuffer();
9929 q = createPQExpBuffer();
9930 delq = createPQExpBuffer();
9931 labelq = createPQExpBuffer();
9933 /* Make sure we are in proper schema so regoperator works correctly */
9934 selectSourceSchema(opcinfo->dobj.namespace->dobj.name);
9936 /* Get additional fields from the pg_opclass row */
9937 if (g_fout->remoteVersion >= 80300)
9939 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9940 "opckeytype::pg_catalog.regtype, "
9941 "opcdefault, opcfamily, "
9942 "opfname AS opcfamilyname, "
9943 "nspname AS opcfamilynsp, "
9944 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
9945 "FROM pg_catalog.pg_opclass c "
9946 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
9947 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
9948 "WHERE c.oid = '%u'::pg_catalog.oid",
9949 opcinfo->dobj.catId.oid);
9953 appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
9954 "opckeytype::pg_catalog.regtype, "
9955 "opcdefault, NULL AS opcfamily, "
9956 "NULL AS opcfamilyname, "
9957 "NULL AS opcfamilynsp, "
9958 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
9959 "FROM pg_catalog.pg_opclass "
9960 "WHERE oid = '%u'::pg_catalog.oid",
9961 opcinfo->dobj.catId.oid);
9964 res = PQexec(g_conn, query->data);
9965 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
9967 /* Expecting a single result only */
9968 ntups = PQntuples(res);
9971 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
9972 "query returned %d rows instead of one: %s\n",
9974 ntups, query->data);
9978 i_opcintype = PQfnumber(res, "opcintype");
9979 i_opckeytype = PQfnumber(res, "opckeytype");
9980 i_opcdefault = PQfnumber(res, "opcdefault");
9981 i_opcfamily = PQfnumber(res, "opcfamily");
9982 i_opcfamilyname = PQfnumber(res, "opcfamilyname");
9983 i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
9984 i_amname = PQfnumber(res, "amname");
9986 opcintype = PQgetvalue(res, 0, i_opcintype);
9987 opckeytype = PQgetvalue(res, 0, i_opckeytype);
9988 opcdefault = PQgetvalue(res, 0, i_opcdefault);
9989 /* opcfamily will still be needed after we PQclear res */
9990 opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
9991 opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
9992 opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
9993 /* amname will still be needed after we PQclear res */
9994 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
9997 * DROP must be fully qualified in case same name appears in pg_catalog
9999 appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
10000 fmtId(opcinfo->dobj.namespace->dobj.name));
10001 appendPQExpBuffer(delq, ".%s",
10002 fmtId(opcinfo->dobj.name));
10003 appendPQExpBuffer(delq, " USING %s;\n",
10006 /* Build the fixed portion of the CREATE command */
10007 appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
10008 fmtId(opcinfo->dobj.name));
10009 if (strcmp(opcdefault, "t") == 0)
10010 appendPQExpBuffer(q, "DEFAULT ");
10011 appendPQExpBuffer(q, "FOR TYPE %s USING %s",
10014 if (strlen(opcfamilyname) > 0 &&
10015 (strcmp(opcfamilyname, opcinfo->dobj.name) != 0 ||
10016 strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0))
10018 appendPQExpBuffer(q, " FAMILY ");
10019 if (strcmp(opcfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10020 appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
10021 appendPQExpBuffer(q, "%s", fmtId(opcfamilyname));
10023 appendPQExpBuffer(q, " AS\n ");
10027 if (strcmp(opckeytype, "-") != 0)
10029 appendPQExpBuffer(q, "STORAGE %s",
10037 * Now fetch and print the OPERATOR entries (pg_amop rows).
10039 * Print only those opfamily members that are tied to the opclass by
10040 * pg_depend entries.
10042 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10043 * older server's opclass in which it is used. This is to avoid
10044 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10045 * older server and then reload into that old version. This can go away
10046 * once 8.3 is so old as to not be of interest to anyone.
10048 resetPQExpBuffer(query);
10050 if (g_fout->remoteVersion >= 90100)
10052 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10053 "amopopr::pg_catalog.regoperator, "
10054 "opfname AS sortfamily, "
10055 "nspname AS sortfamilynsp "
10056 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10057 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10058 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10059 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10060 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10061 "AND refobjid = '%u'::pg_catalog.oid "
10062 "AND amopfamily = '%s'::pg_catalog.oid "
10063 "ORDER BY amopstrategy",
10064 opcinfo->dobj.catId.oid,
10067 else if (g_fout->remoteVersion >= 80400)
10069 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10070 "amopopr::pg_catalog.regoperator, "
10071 "NULL AS sortfamily, "
10072 "NULL AS sortfamilynsp "
10073 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10074 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10075 "AND refobjid = '%u'::pg_catalog.oid "
10076 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10077 "AND objid = ao.oid "
10078 "ORDER BY amopstrategy",
10079 opcinfo->dobj.catId.oid);
10081 else if (g_fout->remoteVersion >= 80300)
10083 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10084 "amopopr::pg_catalog.regoperator, "
10085 "NULL AS sortfamily, "
10086 "NULL AS sortfamilynsp "
10087 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10088 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10089 "AND refobjid = '%u'::pg_catalog.oid "
10090 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10091 "AND objid = ao.oid "
10092 "ORDER BY amopstrategy",
10093 opcinfo->dobj.catId.oid);
10098 * Here, we print all entries since there are no opfamilies and hence
10099 * no loose operators to worry about.
10101 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10102 "amopopr::pg_catalog.regoperator, "
10103 "NULL AS sortfamily, "
10104 "NULL AS sortfamilynsp "
10105 "FROM pg_catalog.pg_amop "
10106 "WHERE amopclaid = '%u'::pg_catalog.oid "
10107 "ORDER BY amopstrategy",
10108 opcinfo->dobj.catId.oid);
10111 res = PQexec(g_conn, query->data);
10112 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10114 ntups = PQntuples(res);
10116 i_amopstrategy = PQfnumber(res, "amopstrategy");
10117 i_amopreqcheck = PQfnumber(res, "amopreqcheck");
10118 i_amopopr = PQfnumber(res, "amopopr");
10119 i_sortfamily = PQfnumber(res, "sortfamily");
10120 i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
10122 for (i = 0; i < ntups; i++)
10124 amopstrategy = PQgetvalue(res, i, i_amopstrategy);
10125 amopreqcheck = PQgetvalue(res, i, i_amopreqcheck);
10126 amopopr = PQgetvalue(res, i, i_amopopr);
10127 sortfamily = PQgetvalue(res, i, i_sortfamily);
10128 sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
10131 appendPQExpBuffer(q, " ,\n ");
10133 appendPQExpBuffer(q, "OPERATOR %s %s",
10134 amopstrategy, amopopr);
10136 if (strlen(sortfamily) > 0)
10138 appendPQExpBuffer(q, " FOR ORDER BY ");
10139 if (strcmp(sortfamilynsp, opcinfo->dobj.namespace->dobj.name) != 0)
10140 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10141 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10144 if (strcmp(amopreqcheck, "t") == 0)
10145 appendPQExpBuffer(q, " RECHECK");
10153 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10155 * Print only those opfamily members that are tied to the opclass by
10156 * pg_depend entries.
10158 * We print the amproclefttype/amprocrighttype even though in most cases
10159 * the backend could deduce the right values, because of the corner case
10160 * of a btree sort support function for a cross-type comparison. That's
10161 * only allowed in 9.2 and later, but for simplicity print them in all
10162 * versions that have the columns.
10164 resetPQExpBuffer(query);
10166 if (g_fout->remoteVersion >= 80300)
10168 appendPQExpBuffer(query, "SELECT amprocnum, "
10169 "amproc::pg_catalog.regprocedure, "
10170 "amproclefttype::pg_catalog.regtype, "
10171 "amprocrighttype::pg_catalog.regtype "
10172 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10173 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10174 "AND refobjid = '%u'::pg_catalog.oid "
10175 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10176 "AND objid = ap.oid "
10177 "ORDER BY amprocnum",
10178 opcinfo->dobj.catId.oid);
10182 appendPQExpBuffer(query, "SELECT amprocnum, "
10183 "amproc::pg_catalog.regprocedure, "
10184 "'' AS amproclefttype, "
10185 "'' AS amprocrighttype "
10186 "FROM pg_catalog.pg_amproc "
10187 "WHERE amopclaid = '%u'::pg_catalog.oid "
10188 "ORDER BY amprocnum",
10189 opcinfo->dobj.catId.oid);
10192 res = PQexec(g_conn, query->data);
10193 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10195 ntups = PQntuples(res);
10197 i_amprocnum = PQfnumber(res, "amprocnum");
10198 i_amproc = PQfnumber(res, "amproc");
10199 i_amproclefttype = PQfnumber(res, "amproclefttype");
10200 i_amprocrighttype = PQfnumber(res, "amprocrighttype");
10202 for (i = 0; i < ntups; i++)
10204 amprocnum = PQgetvalue(res, i, i_amprocnum);
10205 amproc = PQgetvalue(res, i, i_amproc);
10206 amproclefttype = PQgetvalue(res, i, i_amproclefttype);
10207 amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
10210 appendPQExpBuffer(q, " ,\n ");
10212 appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
10214 if (*amproclefttype && *amprocrighttype)
10215 appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
10217 appendPQExpBuffer(q, " %s", amproc);
10224 appendPQExpBuffer(q, ";\n");
10226 appendPQExpBuffer(labelq, "OPERATOR CLASS %s",
10227 fmtId(opcinfo->dobj.name));
10228 appendPQExpBuffer(labelq, " USING %s",
10231 if (binary_upgrade)
10232 binary_upgrade_extension_member(q, &opcinfo->dobj, labelq->data);
10234 ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
10235 opcinfo->dobj.name,
10236 opcinfo->dobj.namespace->dobj.name,
10239 false, "OPERATOR CLASS", SECTION_PRE_DATA,
10240 q->data, delq->data, NULL,
10241 opcinfo->dobj.dependencies, opcinfo->dobj.nDeps,
10244 /* Dump Operator Class Comments */
10245 dumpComment(fout, labelq->data,
10246 NULL, opcinfo->rolname,
10247 opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
10250 destroyPQExpBuffer(query);
10251 destroyPQExpBuffer(q);
10252 destroyPQExpBuffer(delq);
10253 destroyPQExpBuffer(labelq);
10258 * write out a single operator family definition
10260 * Note: this also dumps any "loose" operator members that aren't bound to a
10261 * specific opclass within the opfamily.
10264 dumpOpfamily(Archive *fout, OpfamilyInfo *opfinfo)
10269 PQExpBuffer labelq;
10272 PGresult *res_procs;
10275 int i_amopstrategy;
10276 int i_amopreqcheck;
10279 int i_sortfamilynsp;
10282 int i_amproclefttype;
10283 int i_amprocrighttype;
10285 char *amopstrategy;
10286 char *amopreqcheck;
10289 char *sortfamilynsp;
10292 char *amproclefttype;
10293 char *amprocrighttype;
10297 /* Skip if not to be dumped */
10298 if (!opfinfo->dobj.dump || dataOnly)
10302 * We want to dump the opfamily only if (1) it contains "loose" operators
10303 * or functions, or (2) it contains an opclass with a different name or
10304 * owner. Otherwise it's sufficient to let it be created during creation
10305 * of the contained opclass, and not dumping it improves portability of
10306 * the dump. Since we have to fetch the loose operators/funcs anyway, do
10310 query = createPQExpBuffer();
10311 q = createPQExpBuffer();
10312 delq = createPQExpBuffer();
10313 labelq = createPQExpBuffer();
10315 /* Make sure we are in proper schema so regoperator works correctly */
10316 selectSourceSchema(opfinfo->dobj.namespace->dobj.name);
10319 * Fetch only those opfamily members that are tied directly to the
10320 * opfamily by pg_depend entries.
10322 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
10323 * older server's opclass in which it is used. This is to avoid
10324 * hard-to-detect breakage if a newer pg_dump is used to dump from an
10325 * older server and then reload into that old version. This can go away
10326 * once 8.3 is so old as to not be of interest to anyone.
10328 if (g_fout->remoteVersion >= 90100)
10330 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10331 "amopopr::pg_catalog.regoperator, "
10332 "opfname AS sortfamily, "
10333 "nspname AS sortfamilynsp "
10334 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
10335 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
10336 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
10337 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
10338 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10339 "AND refobjid = '%u'::pg_catalog.oid "
10340 "AND amopfamily = '%u'::pg_catalog.oid "
10341 "ORDER BY amopstrategy",
10342 opfinfo->dobj.catId.oid,
10343 opfinfo->dobj.catId.oid);
10345 else if (g_fout->remoteVersion >= 80400)
10347 appendPQExpBuffer(query, "SELECT amopstrategy, false AS amopreqcheck, "
10348 "amopopr::pg_catalog.regoperator, "
10349 "NULL AS sortfamily, "
10350 "NULL AS sortfamilynsp "
10351 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10352 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10353 "AND refobjid = '%u'::pg_catalog.oid "
10354 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10355 "AND objid = ao.oid "
10356 "ORDER BY amopstrategy",
10357 opfinfo->dobj.catId.oid);
10361 appendPQExpBuffer(query, "SELECT amopstrategy, amopreqcheck, "
10362 "amopopr::pg_catalog.regoperator, "
10363 "NULL AS sortfamily, "
10364 "NULL AS sortfamilynsp "
10365 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
10366 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10367 "AND refobjid = '%u'::pg_catalog.oid "
10368 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
10369 "AND objid = ao.oid "
10370 "ORDER BY amopstrategy",
10371 opfinfo->dobj.catId.oid);
10374 res_ops = PQexec(g_conn, query->data);
10375 check_sql_result(res_ops, g_conn, query->data, PGRES_TUPLES_OK);
10377 resetPQExpBuffer(query);
10379 appendPQExpBuffer(query, "SELECT amprocnum, "
10380 "amproc::pg_catalog.regprocedure, "
10381 "amproclefttype::pg_catalog.regtype, "
10382 "amprocrighttype::pg_catalog.regtype "
10383 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
10384 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10385 "AND refobjid = '%u'::pg_catalog.oid "
10386 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
10387 "AND objid = ap.oid "
10388 "ORDER BY amprocnum",
10389 opfinfo->dobj.catId.oid);
10391 res_procs = PQexec(g_conn, query->data);
10392 check_sql_result(res_procs, g_conn, query->data, PGRES_TUPLES_OK);
10394 if (PQntuples(res_ops) == 0 && PQntuples(res_procs) == 0)
10396 /* No loose members, so check contained opclasses */
10397 resetPQExpBuffer(query);
10399 appendPQExpBuffer(query, "SELECT 1 "
10400 "FROM pg_catalog.pg_opclass c, pg_catalog.pg_opfamily f, pg_catalog.pg_depend "
10401 "WHERE f.oid = '%u'::pg_catalog.oid "
10402 "AND refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
10403 "AND refobjid = f.oid "
10404 "AND classid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
10405 "AND objid = c.oid "
10406 "AND (opcname != opfname OR opcnamespace != opfnamespace OR opcowner != opfowner) "
10408 opfinfo->dobj.catId.oid);
10410 res = PQexec(g_conn, query->data);
10411 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10413 if (PQntuples(res) == 0)
10415 /* no need to dump it, so bail out */
10418 PQclear(res_procs);
10419 destroyPQExpBuffer(query);
10420 destroyPQExpBuffer(q);
10421 destroyPQExpBuffer(delq);
10422 destroyPQExpBuffer(labelq);
10429 /* Get additional fields from the pg_opfamily row */
10430 resetPQExpBuffer(query);
10432 appendPQExpBuffer(query, "SELECT "
10433 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
10434 "FROM pg_catalog.pg_opfamily "
10435 "WHERE oid = '%u'::pg_catalog.oid",
10436 opfinfo->dobj.catId.oid);
10438 res = PQexec(g_conn, query->data);
10439 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10441 /* Expecting a single result only */
10442 ntups = PQntuples(res);
10445 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10446 "query returned %d rows instead of one: %s\n",
10448 ntups, query->data);
10452 i_amname = PQfnumber(res, "amname");
10454 /* amname will still be needed after we PQclear res */
10455 amname = pg_strdup(PQgetvalue(res, 0, i_amname));
10458 * DROP must be fully qualified in case same name appears in pg_catalog
10460 appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
10461 fmtId(opfinfo->dobj.namespace->dobj.name));
10462 appendPQExpBuffer(delq, ".%s",
10463 fmtId(opfinfo->dobj.name));
10464 appendPQExpBuffer(delq, " USING %s;\n",
10467 /* Build the fixed portion of the CREATE command */
10468 appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
10469 fmtId(opfinfo->dobj.name));
10470 appendPQExpBuffer(q, " USING %s;\n",
10475 /* Do we need an ALTER to add loose members? */
10476 if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
10478 appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
10479 fmtId(opfinfo->dobj.name));
10480 appendPQExpBuffer(q, " USING %s ADD\n ",
10486 * Now fetch and print the OPERATOR entries (pg_amop rows).
10488 ntups = PQntuples(res_ops);
10490 i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
10491 i_amopreqcheck = PQfnumber(res_ops, "amopreqcheck");
10492 i_amopopr = PQfnumber(res_ops, "amopopr");
10493 i_sortfamily = PQfnumber(res_ops, "sortfamily");
10494 i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
10496 for (i = 0; i < ntups; i++)
10498 amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
10499 amopreqcheck = PQgetvalue(res_ops, i, i_amopreqcheck);
10500 amopopr = PQgetvalue(res_ops, i, i_amopopr);
10501 sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
10502 sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
10505 appendPQExpBuffer(q, " ,\n ");
10507 appendPQExpBuffer(q, "OPERATOR %s %s",
10508 amopstrategy, amopopr);
10510 if (strlen(sortfamily) > 0)
10512 appendPQExpBuffer(q, " FOR ORDER BY ");
10513 if (strcmp(sortfamilynsp, opfinfo->dobj.namespace->dobj.name) != 0)
10514 appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
10515 appendPQExpBuffer(q, "%s", fmtId(sortfamily));
10518 if (strcmp(amopreqcheck, "t") == 0)
10519 appendPQExpBuffer(q, " RECHECK");
10525 * Now fetch and print the FUNCTION entries (pg_amproc rows).
10527 ntups = PQntuples(res_procs);
10529 i_amprocnum = PQfnumber(res_procs, "amprocnum");
10530 i_amproc = PQfnumber(res_procs, "amproc");
10531 i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
10532 i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
10534 for (i = 0; i < ntups; i++)
10536 amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
10537 amproc = PQgetvalue(res_procs, i, i_amproc);
10538 amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
10539 amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
10542 appendPQExpBuffer(q, " ,\n ");
10544 appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
10545 amprocnum, amproclefttype, amprocrighttype,
10551 appendPQExpBuffer(q, ";\n");
10554 appendPQExpBuffer(labelq, "OPERATOR FAMILY %s",
10555 fmtId(opfinfo->dobj.name));
10556 appendPQExpBuffer(labelq, " USING %s",
10559 if (binary_upgrade)
10560 binary_upgrade_extension_member(q, &opfinfo->dobj, labelq->data);
10562 ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
10563 opfinfo->dobj.name,
10564 opfinfo->dobj.namespace->dobj.name,
10567 false, "OPERATOR FAMILY", SECTION_PRE_DATA,
10568 q->data, delq->data, NULL,
10569 opfinfo->dobj.dependencies, opfinfo->dobj.nDeps,
10572 /* Dump Operator Family Comments */
10573 dumpComment(fout, labelq->data,
10574 NULL, opfinfo->rolname,
10575 opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
10579 PQclear(res_procs);
10580 destroyPQExpBuffer(query);
10581 destroyPQExpBuffer(q);
10582 destroyPQExpBuffer(delq);
10583 destroyPQExpBuffer(labelq);
10588 * write out a single collation definition
10591 dumpCollation(Archive *fout, CollInfo *collinfo)
10596 PQExpBuffer labelq;
10601 const char *collcollate;
10602 const char *collctype;
10604 /* Skip if not to be dumped */
10605 if (!collinfo->dobj.dump || dataOnly)
10608 query = createPQExpBuffer();
10609 q = createPQExpBuffer();
10610 delq = createPQExpBuffer();
10611 labelq = createPQExpBuffer();
10613 /* Make sure we are in proper schema */
10614 selectSourceSchema(collinfo->dobj.namespace->dobj.name);
10616 /* Get conversion-specific details */
10617 appendPQExpBuffer(query, "SELECT "
10620 "FROM pg_catalog.pg_collation c "
10621 "WHERE c.oid = '%u'::pg_catalog.oid",
10622 collinfo->dobj.catId.oid);
10624 res = PQexec(g_conn, query->data);
10625 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10627 /* Expecting a single result only */
10628 ntups = PQntuples(res);
10631 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10632 "query returned %d rows instead of one: %s\n",
10634 ntups, query->data);
10638 i_collcollate = PQfnumber(res, "collcollate");
10639 i_collctype = PQfnumber(res, "collctype");
10641 collcollate = PQgetvalue(res, 0, i_collcollate);
10642 collctype = PQgetvalue(res, 0, i_collctype);
10645 * DROP must be fully qualified in case same name appears in pg_catalog
10647 appendPQExpBuffer(delq, "DROP COLLATION %s",
10648 fmtId(collinfo->dobj.namespace->dobj.name));
10649 appendPQExpBuffer(delq, ".%s;\n",
10650 fmtId(collinfo->dobj.name));
10652 appendPQExpBuffer(q, "CREATE COLLATION %s (lc_collate = ",
10653 fmtId(collinfo->dobj.name));
10654 appendStringLiteralAH(q, collcollate, fout);
10655 appendPQExpBuffer(q, ", lc_ctype = ");
10656 appendStringLiteralAH(q, collctype, fout);
10657 appendPQExpBuffer(q, ");\n");
10659 appendPQExpBuffer(labelq, "COLLATION %s", fmtId(collinfo->dobj.name));
10661 if (binary_upgrade)
10662 binary_upgrade_extension_member(q, &collinfo->dobj, labelq->data);
10664 ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
10665 collinfo->dobj.name,
10666 collinfo->dobj.namespace->dobj.name,
10669 false, "COLLATION", SECTION_PRE_DATA,
10670 q->data, delq->data, NULL,
10671 collinfo->dobj.dependencies, collinfo->dobj.nDeps,
10674 /* Dump Collation Comments */
10675 dumpComment(fout, labelq->data,
10676 collinfo->dobj.namespace->dobj.name, collinfo->rolname,
10677 collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
10681 destroyPQExpBuffer(query);
10682 destroyPQExpBuffer(q);
10683 destroyPQExpBuffer(delq);
10684 destroyPQExpBuffer(labelq);
10689 * write out a single conversion definition
10692 dumpConversion(Archive *fout, ConvInfo *convinfo)
10697 PQExpBuffer labelq;
10700 int i_conforencoding;
10701 int i_contoencoding;
10704 const char *conforencoding;
10705 const char *contoencoding;
10706 const char *conproc;
10709 /* Skip if not to be dumped */
10710 if (!convinfo->dobj.dump || dataOnly)
10713 query = createPQExpBuffer();
10714 q = createPQExpBuffer();
10715 delq = createPQExpBuffer();
10716 labelq = createPQExpBuffer();
10718 /* Make sure we are in proper schema */
10719 selectSourceSchema(convinfo->dobj.namespace->dobj.name);
10721 /* Get conversion-specific details */
10722 appendPQExpBuffer(query, "SELECT "
10723 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
10724 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
10725 "conproc, condefault "
10726 "FROM pg_catalog.pg_conversion c "
10727 "WHERE c.oid = '%u'::pg_catalog.oid",
10728 convinfo->dobj.catId.oid);
10730 res = PQexec(g_conn, query->data);
10731 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10733 /* Expecting a single result only */
10734 ntups = PQntuples(res);
10737 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10738 "query returned %d rows instead of one: %s\n",
10740 ntups, query->data);
10744 i_conforencoding = PQfnumber(res, "conforencoding");
10745 i_contoencoding = PQfnumber(res, "contoencoding");
10746 i_conproc = PQfnumber(res, "conproc");
10747 i_condefault = PQfnumber(res, "condefault");
10749 conforencoding = PQgetvalue(res, 0, i_conforencoding);
10750 contoencoding = PQgetvalue(res, 0, i_contoencoding);
10751 conproc = PQgetvalue(res, 0, i_conproc);
10752 condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
10755 * DROP must be fully qualified in case same name appears in pg_catalog
10757 appendPQExpBuffer(delq, "DROP CONVERSION %s",
10758 fmtId(convinfo->dobj.namespace->dobj.name));
10759 appendPQExpBuffer(delq, ".%s;\n",
10760 fmtId(convinfo->dobj.name));
10762 appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
10763 (condefault) ? "DEFAULT " : "",
10764 fmtId(convinfo->dobj.name));
10765 appendStringLiteralAH(q, conforencoding, fout);
10766 appendPQExpBuffer(q, " TO ");
10767 appendStringLiteralAH(q, contoencoding, fout);
10768 /* regproc is automatically quoted in 7.3 and above */
10769 appendPQExpBuffer(q, " FROM %s;\n", conproc);
10771 appendPQExpBuffer(labelq, "CONVERSION %s", fmtId(convinfo->dobj.name));
10773 if (binary_upgrade)
10774 binary_upgrade_extension_member(q, &convinfo->dobj, labelq->data);
10776 ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
10777 convinfo->dobj.name,
10778 convinfo->dobj.namespace->dobj.name,
10781 false, "CONVERSION", SECTION_PRE_DATA,
10782 q->data, delq->data, NULL,
10783 convinfo->dobj.dependencies, convinfo->dobj.nDeps,
10786 /* Dump Conversion Comments */
10787 dumpComment(fout, labelq->data,
10788 convinfo->dobj.namespace->dobj.name, convinfo->rolname,
10789 convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
10793 destroyPQExpBuffer(query);
10794 destroyPQExpBuffer(q);
10795 destroyPQExpBuffer(delq);
10796 destroyPQExpBuffer(labelq);
10800 * format_aggregate_signature: generate aggregate name and argument list
10802 * The argument type names are qualified if needed. The aggregate name
10803 * is never qualified.
10806 format_aggregate_signature(AggInfo *agginfo, Archive *fout, bool honor_quotes)
10808 PQExpBufferData buf;
10811 initPQExpBuffer(&buf);
10813 appendPQExpBuffer(&buf, "%s",
10814 fmtId(agginfo->aggfn.dobj.name));
10816 appendPQExpBuffer(&buf, "%s", agginfo->aggfn.dobj.name);
10818 if (agginfo->aggfn.nargs == 0)
10819 appendPQExpBuffer(&buf, "(*)");
10822 appendPQExpBuffer(&buf, "(");
10823 for (j = 0; j < agginfo->aggfn.nargs; j++)
10827 typname = getFormattedTypeName(agginfo->aggfn.argtypes[j], zeroAsOpaque);
10829 appendPQExpBuffer(&buf, "%s%s",
10830 (j > 0) ? ", " : "",
10834 appendPQExpBuffer(&buf, ")");
10841 * write out a single aggregate definition
10844 dumpAgg(Archive *fout, AggInfo *agginfo)
10849 PQExpBuffer labelq;
10850 PQExpBuffer details;
10858 int i_aggtranstype;
10861 const char *aggtransfn;
10862 const char *aggfinalfn;
10863 const char *aggsortop;
10864 const char *aggtranstype;
10865 const char *agginitval;
10868 /* Skip if not to be dumped */
10869 if (!agginfo->aggfn.dobj.dump || dataOnly)
10872 query = createPQExpBuffer();
10873 q = createPQExpBuffer();
10874 delq = createPQExpBuffer();
10875 labelq = createPQExpBuffer();
10876 details = createPQExpBuffer();
10878 /* Make sure we are in proper schema */
10879 selectSourceSchema(agginfo->aggfn.dobj.namespace->dobj.name);
10881 /* Get aggregate-specific details */
10882 if (g_fout->remoteVersion >= 80100)
10884 appendPQExpBuffer(query, "SELECT aggtransfn, "
10885 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10886 "aggsortop::pg_catalog.regoperator, "
10888 "'t'::boolean AS convertok "
10889 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10890 "WHERE a.aggfnoid = p.oid "
10891 "AND p.oid = '%u'::pg_catalog.oid",
10892 agginfo->aggfn.dobj.catId.oid);
10894 else if (g_fout->remoteVersion >= 70300)
10896 appendPQExpBuffer(query, "SELECT aggtransfn, "
10897 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
10900 "'t'::boolean AS convertok "
10901 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
10902 "WHERE a.aggfnoid = p.oid "
10903 "AND p.oid = '%u'::pg_catalog.oid",
10904 agginfo->aggfn.dobj.catId.oid);
10906 else if (g_fout->remoteVersion >= 70100)
10908 appendPQExpBuffer(query, "SELECT aggtransfn, aggfinalfn, "
10909 "format_type(aggtranstype, NULL) AS aggtranstype, "
10912 "'t'::boolean AS convertok "
10913 "FROM pg_aggregate "
10914 "WHERE oid = '%u'::oid",
10915 agginfo->aggfn.dobj.catId.oid);
10919 appendPQExpBuffer(query, "SELECT aggtransfn1 AS aggtransfn, "
10921 "(SELECT typname FROM pg_type WHERE oid = aggtranstype1) AS aggtranstype, "
10923 "agginitval1 AS agginitval, "
10924 "(aggtransfn2 = 0 and aggtranstype2 = 0 and agginitval2 is null) AS convertok "
10925 "FROM pg_aggregate "
10926 "WHERE oid = '%u'::oid",
10927 agginfo->aggfn.dobj.catId.oid);
10930 res = PQexec(g_conn, query->data);
10931 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
10933 /* Expecting a single result only */
10934 ntups = PQntuples(res);
10937 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
10938 "query returned %d rows instead of one: %s\n",
10940 ntups, query->data);
10944 i_aggtransfn = PQfnumber(res, "aggtransfn");
10945 i_aggfinalfn = PQfnumber(res, "aggfinalfn");
10946 i_aggsortop = PQfnumber(res, "aggsortop");
10947 i_aggtranstype = PQfnumber(res, "aggtranstype");
10948 i_agginitval = PQfnumber(res, "agginitval");
10949 i_convertok = PQfnumber(res, "convertok");
10951 aggtransfn = PQgetvalue(res, 0, i_aggtransfn);
10952 aggfinalfn = PQgetvalue(res, 0, i_aggfinalfn);
10953 aggsortop = PQgetvalue(res, 0, i_aggsortop);
10954 aggtranstype = PQgetvalue(res, 0, i_aggtranstype);
10955 agginitval = PQgetvalue(res, 0, i_agginitval);
10956 convertok = (PQgetvalue(res, 0, i_convertok)[0] == 't');
10958 aggsig = format_aggregate_signature(agginfo, fout, true);
10959 aggsig_tag = format_aggregate_signature(agginfo, fout, false);
10963 write_msg(NULL, "WARNING: aggregate function %s could not be dumped correctly for this database version; ignored\n",
10968 if (g_fout->remoteVersion >= 70300)
10970 /* If using 7.3's regproc or regtype, data is already quoted */
10971 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10975 else if (g_fout->remoteVersion >= 70100)
10977 /* format_type quotes, regproc does not */
10978 appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
10984 /* need quotes all around */
10985 appendPQExpBuffer(details, " SFUNC = %s,\n",
10986 fmtId(aggtransfn));
10987 appendPQExpBuffer(details, " STYPE = %s",
10988 fmtId(aggtranstype));
10991 if (!PQgetisnull(res, 0, i_agginitval))
10993 appendPQExpBuffer(details, ",\n INITCOND = ");
10994 appendStringLiteralAH(details, agginitval, fout);
10997 if (strcmp(aggfinalfn, "-") != 0)
10999 appendPQExpBuffer(details, ",\n FINALFUNC = %s",
11003 aggsortop = convertOperatorReference(aggsortop);
11006 appendPQExpBuffer(details, ",\n SORTOP = %s",
11011 * DROP must be fully qualified in case same name appears in pg_catalog
11013 appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
11014 fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
11017 appendPQExpBuffer(q, "CREATE AGGREGATE %s (\n%s\n);\n",
11018 aggsig, details->data);
11020 appendPQExpBuffer(labelq, "AGGREGATE %s", aggsig);
11022 if (binary_upgrade)
11023 binary_upgrade_extension_member(q, &agginfo->aggfn.dobj, labelq->data);
11025 ArchiveEntry(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11027 agginfo->aggfn.dobj.namespace->dobj.name,
11029 agginfo->aggfn.rolname,
11030 false, "AGGREGATE", SECTION_PRE_DATA,
11031 q->data, delq->data, NULL,
11032 agginfo->aggfn.dobj.dependencies, agginfo->aggfn.dobj.nDeps,
11035 /* Dump Aggregate Comments */
11036 dumpComment(fout, labelq->data,
11037 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11038 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11039 dumpSecLabel(fout, labelq->data,
11040 agginfo->aggfn.dobj.namespace->dobj.name, agginfo->aggfn.rolname,
11041 agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
11044 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
11045 * command look like a function's GRANT; in particular this affects the
11046 * syntax for zero-argument aggregates.
11051 aggsig = format_function_signature(&agginfo->aggfn, true);
11052 aggsig_tag = format_function_signature(&agginfo->aggfn, false);
11054 dumpACL(fout, agginfo->aggfn.dobj.catId, agginfo->aggfn.dobj.dumpId,
11056 aggsig, NULL, aggsig_tag,
11057 agginfo->aggfn.dobj.namespace->dobj.name,
11058 agginfo->aggfn.rolname, agginfo->aggfn.proacl);
11065 destroyPQExpBuffer(query);
11066 destroyPQExpBuffer(q);
11067 destroyPQExpBuffer(delq);
11068 destroyPQExpBuffer(labelq);
11069 destroyPQExpBuffer(details);
11074 * write out a single text search parser
11077 dumpTSParser(Archive *fout, TSParserInfo *prsinfo)
11081 PQExpBuffer labelq;
11083 /* Skip if not to be dumped */
11084 if (!prsinfo->dobj.dump || dataOnly)
11087 q = createPQExpBuffer();
11088 delq = createPQExpBuffer();
11089 labelq = createPQExpBuffer();
11091 /* Make sure we are in proper schema */
11092 selectSourceSchema(prsinfo->dobj.namespace->dobj.name);
11094 appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
11095 fmtId(prsinfo->dobj.name));
11097 appendPQExpBuffer(q, " START = %s,\n",
11098 convertTSFunction(prsinfo->prsstart));
11099 appendPQExpBuffer(q, " GETTOKEN = %s,\n",
11100 convertTSFunction(prsinfo->prstoken));
11101 appendPQExpBuffer(q, " END = %s,\n",
11102 convertTSFunction(prsinfo->prsend));
11103 if (prsinfo->prsheadline != InvalidOid)
11104 appendPQExpBuffer(q, " HEADLINE = %s,\n",
11105 convertTSFunction(prsinfo->prsheadline));
11106 appendPQExpBuffer(q, " LEXTYPES = %s );\n",
11107 convertTSFunction(prsinfo->prslextype));
11110 * DROP must be fully qualified in case same name appears in pg_catalog
11112 appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s",
11113 fmtId(prsinfo->dobj.namespace->dobj.name));
11114 appendPQExpBuffer(delq, ".%s;\n",
11115 fmtId(prsinfo->dobj.name));
11117 appendPQExpBuffer(labelq, "TEXT SEARCH PARSER %s",
11118 fmtId(prsinfo->dobj.name));
11120 if (binary_upgrade)
11121 binary_upgrade_extension_member(q, &prsinfo->dobj, labelq->data);
11123 ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
11124 prsinfo->dobj.name,
11125 prsinfo->dobj.namespace->dobj.name,
11128 false, "TEXT SEARCH PARSER", SECTION_PRE_DATA,
11129 q->data, delq->data, NULL,
11130 prsinfo->dobj.dependencies, prsinfo->dobj.nDeps,
11133 /* Dump Parser Comments */
11134 dumpComment(fout, labelq->data,
11136 prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
11138 destroyPQExpBuffer(q);
11139 destroyPQExpBuffer(delq);
11140 destroyPQExpBuffer(labelq);
11145 * write out a single text search dictionary
11148 dumpTSDictionary(Archive *fout, TSDictInfo *dictinfo)
11152 PQExpBuffer labelq;
11159 /* Skip if not to be dumped */
11160 if (!dictinfo->dobj.dump || dataOnly)
11163 q = createPQExpBuffer();
11164 delq = createPQExpBuffer();
11165 labelq = createPQExpBuffer();
11166 query = createPQExpBuffer();
11168 /* Fetch name and namespace of the dictionary's template */
11169 selectSourceSchema("pg_catalog");
11170 appendPQExpBuffer(query, "SELECT nspname, tmplname "
11171 "FROM pg_ts_template p, pg_namespace n "
11172 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
11173 dictinfo->dicttemplate);
11174 res = PQexec(g_conn, query->data);
11175 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11176 ntups = PQntuples(res);
11179 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11180 "query returned %d rows instead of one: %s\n",
11182 ntups, query->data);
11185 nspname = PQgetvalue(res, 0, 0);
11186 tmplname = PQgetvalue(res, 0, 1);
11188 /* Make sure we are in proper schema */
11189 selectSourceSchema(dictinfo->dobj.namespace->dobj.name);
11191 appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
11192 fmtId(dictinfo->dobj.name));
11194 appendPQExpBuffer(q, " TEMPLATE = ");
11195 if (strcmp(nspname, dictinfo->dobj.namespace->dobj.name) != 0)
11196 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11197 appendPQExpBuffer(q, "%s", fmtId(tmplname));
11201 /* the dictinitoption can be dumped straight into the command */
11202 if (dictinfo->dictinitoption)
11203 appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
11205 appendPQExpBuffer(q, " );\n");
11208 * DROP must be fully qualified in case same name appears in pg_catalog
11210 appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s",
11211 fmtId(dictinfo->dobj.namespace->dobj.name));
11212 appendPQExpBuffer(delq, ".%s;\n",
11213 fmtId(dictinfo->dobj.name));
11215 appendPQExpBuffer(labelq, "TEXT SEARCH DICTIONARY %s",
11216 fmtId(dictinfo->dobj.name));
11218 if (binary_upgrade)
11219 binary_upgrade_extension_member(q, &dictinfo->dobj, labelq->data);
11221 ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
11222 dictinfo->dobj.name,
11223 dictinfo->dobj.namespace->dobj.name,
11226 false, "TEXT SEARCH DICTIONARY", SECTION_PRE_DATA,
11227 q->data, delq->data, NULL,
11228 dictinfo->dobj.dependencies, dictinfo->dobj.nDeps,
11231 /* Dump Dictionary Comments */
11232 dumpComment(fout, labelq->data,
11233 NULL, dictinfo->rolname,
11234 dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
11236 destroyPQExpBuffer(q);
11237 destroyPQExpBuffer(delq);
11238 destroyPQExpBuffer(labelq);
11239 destroyPQExpBuffer(query);
11244 * write out a single text search template
11247 dumpTSTemplate(Archive *fout, TSTemplateInfo *tmplinfo)
11251 PQExpBuffer labelq;
11253 /* Skip if not to be dumped */
11254 if (!tmplinfo->dobj.dump || dataOnly)
11257 q = createPQExpBuffer();
11258 delq = createPQExpBuffer();
11259 labelq = createPQExpBuffer();
11261 /* Make sure we are in proper schema */
11262 selectSourceSchema(tmplinfo->dobj.namespace->dobj.name);
11264 appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
11265 fmtId(tmplinfo->dobj.name));
11267 if (tmplinfo->tmplinit != InvalidOid)
11268 appendPQExpBuffer(q, " INIT = %s,\n",
11269 convertTSFunction(tmplinfo->tmplinit));
11270 appendPQExpBuffer(q, " LEXIZE = %s );\n",
11271 convertTSFunction(tmplinfo->tmpllexize));
11274 * DROP must be fully qualified in case same name appears in pg_catalog
11276 appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s",
11277 fmtId(tmplinfo->dobj.namespace->dobj.name));
11278 appendPQExpBuffer(delq, ".%s;\n",
11279 fmtId(tmplinfo->dobj.name));
11281 appendPQExpBuffer(labelq, "TEXT SEARCH TEMPLATE %s",
11282 fmtId(tmplinfo->dobj.name));
11284 if (binary_upgrade)
11285 binary_upgrade_extension_member(q, &tmplinfo->dobj, labelq->data);
11287 ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
11288 tmplinfo->dobj.name,
11289 tmplinfo->dobj.namespace->dobj.name,
11292 false, "TEXT SEARCH TEMPLATE", SECTION_PRE_DATA,
11293 q->data, delq->data, NULL,
11294 tmplinfo->dobj.dependencies, tmplinfo->dobj.nDeps,
11297 /* Dump Template Comments */
11298 dumpComment(fout, labelq->data,
11300 tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
11302 destroyPQExpBuffer(q);
11303 destroyPQExpBuffer(delq);
11304 destroyPQExpBuffer(labelq);
11309 * write out a single text search configuration
11312 dumpTSConfig(Archive *fout, TSConfigInfo *cfginfo)
11316 PQExpBuffer labelq;
11326 /* Skip if not to be dumped */
11327 if (!cfginfo->dobj.dump || dataOnly)
11330 q = createPQExpBuffer();
11331 delq = createPQExpBuffer();
11332 labelq = createPQExpBuffer();
11333 query = createPQExpBuffer();
11335 /* Fetch name and namespace of the config's parser */
11336 selectSourceSchema("pg_catalog");
11337 appendPQExpBuffer(query, "SELECT nspname, prsname "
11338 "FROM pg_ts_parser p, pg_namespace n "
11339 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
11340 cfginfo->cfgparser);
11341 res = PQexec(g_conn, query->data);
11342 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11343 ntups = PQntuples(res);
11346 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11347 "query returned %d rows instead of one: %s\n",
11349 ntups, query->data);
11352 nspname = PQgetvalue(res, 0, 0);
11353 prsname = PQgetvalue(res, 0, 1);
11355 /* Make sure we are in proper schema */
11356 selectSourceSchema(cfginfo->dobj.namespace->dobj.name);
11358 appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
11359 fmtId(cfginfo->dobj.name));
11361 appendPQExpBuffer(q, " PARSER = ");
11362 if (strcmp(nspname, cfginfo->dobj.namespace->dobj.name) != 0)
11363 appendPQExpBuffer(q, "%s.", fmtId(nspname));
11364 appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
11368 resetPQExpBuffer(query);
11369 appendPQExpBuffer(query,
11371 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t \n"
11372 " WHERE t.tokid = m.maptokentype ) AS tokenname, \n"
11373 " m.mapdict::pg_catalog.regdictionary AS dictname \n"
11374 "FROM pg_catalog.pg_ts_config_map AS m \n"
11375 "WHERE m.mapcfg = '%u' \n"
11376 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
11377 cfginfo->cfgparser, cfginfo->dobj.catId.oid);
11379 res = PQexec(g_conn, query->data);
11380 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11381 ntups = PQntuples(res);
11383 i_tokenname = PQfnumber(res, "tokenname");
11384 i_dictname = PQfnumber(res, "dictname");
11386 for (i = 0; i < ntups; i++)
11388 char *tokenname = PQgetvalue(res, i, i_tokenname);
11389 char *dictname = PQgetvalue(res, i, i_dictname);
11392 strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
11394 /* starting a new token type, so start a new command */
11396 appendPQExpBuffer(q, ";\n");
11397 appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
11398 fmtId(cfginfo->dobj.name));
11399 /* tokenname needs quoting, dictname does NOT */
11400 appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
11401 fmtId(tokenname), dictname);
11404 appendPQExpBuffer(q, ", %s", dictname);
11408 appendPQExpBuffer(q, ";\n");
11413 * DROP must be fully qualified in case same name appears in pg_catalog
11415 appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s",
11416 fmtId(cfginfo->dobj.namespace->dobj.name));
11417 appendPQExpBuffer(delq, ".%s;\n",
11418 fmtId(cfginfo->dobj.name));
11420 appendPQExpBuffer(labelq, "TEXT SEARCH CONFIGURATION %s",
11421 fmtId(cfginfo->dobj.name));
11423 if (binary_upgrade)
11424 binary_upgrade_extension_member(q, &cfginfo->dobj, labelq->data);
11426 ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
11427 cfginfo->dobj.name,
11428 cfginfo->dobj.namespace->dobj.name,
11431 false, "TEXT SEARCH CONFIGURATION", SECTION_PRE_DATA,
11432 q->data, delq->data, NULL,
11433 cfginfo->dobj.dependencies, cfginfo->dobj.nDeps,
11436 /* Dump Configuration Comments */
11437 dumpComment(fout, labelq->data,
11438 NULL, cfginfo->rolname,
11439 cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
11441 destroyPQExpBuffer(q);
11442 destroyPQExpBuffer(delq);
11443 destroyPQExpBuffer(labelq);
11444 destroyPQExpBuffer(query);
11448 * dumpForeignDataWrapper
11449 * write out a single foreign-data wrapper definition
11452 dumpForeignDataWrapper(Archive *fout, FdwInfo *fdwinfo)
11456 PQExpBuffer labelq;
11459 /* Skip if not to be dumped */
11460 if (!fdwinfo->dobj.dump || dataOnly)
11464 * FDWs that belong to an extension are dumped based on their "dump"
11465 * field. Otherwise omit them if we are only dumping some specific object.
11467 if (!fdwinfo->dobj.ext_member)
11468 if (!include_everything)
11471 q = createPQExpBuffer();
11472 delq = createPQExpBuffer();
11473 labelq = createPQExpBuffer();
11475 qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
11477 appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
11480 if (strcmp(fdwinfo->fdwhandler, "-") != 0)
11481 appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
11483 if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
11484 appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
11486 if (strlen(fdwinfo->fdwoptions) > 0)
11487 appendPQExpBuffer(q, " OPTIONS (%s)", fdwinfo->fdwoptions);
11489 appendPQExpBuffer(q, ";\n");
11491 appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
11494 appendPQExpBuffer(labelq, "FOREIGN DATA WRAPPER %s",
11497 if (binary_upgrade)
11498 binary_upgrade_extension_member(q, &fdwinfo->dobj, labelq->data);
11500 ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11501 fdwinfo->dobj.name,
11505 false, "FOREIGN DATA WRAPPER", SECTION_PRE_DATA,
11506 q->data, delq->data, NULL,
11507 fdwinfo->dobj.dependencies, fdwinfo->dobj.nDeps,
11510 /* Handle the ACL */
11511 dumpACL(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
11512 "FOREIGN DATA WRAPPER",
11513 qfdwname, NULL, fdwinfo->dobj.name,
11514 NULL, fdwinfo->rolname,
11517 /* Dump Foreign Data Wrapper Comments */
11518 dumpComment(fout, labelq->data,
11519 NULL, fdwinfo->rolname,
11520 fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
11524 destroyPQExpBuffer(q);
11525 destroyPQExpBuffer(delq);
11526 destroyPQExpBuffer(labelq);
11530 * dumpForeignServer
11531 * write out a foreign server definition
11534 dumpForeignServer(Archive *fout, ForeignServerInfo *srvinfo)
11538 PQExpBuffer labelq;
11545 /* Skip if not to be dumped */
11546 if (!srvinfo->dobj.dump || dataOnly || !include_everything)
11549 q = createPQExpBuffer();
11550 delq = createPQExpBuffer();
11551 labelq = createPQExpBuffer();
11552 query = createPQExpBuffer();
11554 qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
11556 /* look up the foreign-data wrapper */
11557 selectSourceSchema("pg_catalog");
11558 appendPQExpBuffer(query, "SELECT fdwname "
11559 "FROM pg_foreign_data_wrapper w "
11560 "WHERE w.oid = '%u'",
11562 res = PQexec(g_conn, query->data);
11563 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11564 ntups = PQntuples(res);
11567 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
11568 "query returned %d rows instead of one: %s\n",
11570 ntups, query->data);
11573 fdwname = PQgetvalue(res, 0, 0);
11575 appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
11576 if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
11578 appendPQExpBuffer(q, " TYPE ");
11579 appendStringLiteralAH(q, srvinfo->srvtype, fout);
11581 if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
11583 appendPQExpBuffer(q, " VERSION ");
11584 appendStringLiteralAH(q, srvinfo->srvversion, fout);
11587 appendPQExpBuffer(q, " FOREIGN DATA WRAPPER ");
11588 appendPQExpBuffer(q, "%s", fmtId(fdwname));
11590 if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
11591 appendPQExpBuffer(q, " OPTIONS (%s)", srvinfo->srvoptions);
11593 appendPQExpBuffer(q, ";\n");
11595 appendPQExpBuffer(delq, "DROP SERVER %s;\n",
11598 appendPQExpBuffer(labelq, "SERVER %s", qsrvname);
11600 if (binary_upgrade)
11601 binary_upgrade_extension_member(q, &srvinfo->dobj, labelq->data);
11603 ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11604 srvinfo->dobj.name,
11608 false, "SERVER", SECTION_PRE_DATA,
11609 q->data, delq->data, NULL,
11610 srvinfo->dobj.dependencies, srvinfo->dobj.nDeps,
11613 /* Handle the ACL */
11614 dumpACL(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
11616 qsrvname, NULL, srvinfo->dobj.name,
11617 NULL, srvinfo->rolname,
11620 /* Dump user mappings */
11621 dumpUserMappings(fout,
11622 srvinfo->dobj.name, NULL,
11624 srvinfo->dobj.catId, srvinfo->dobj.dumpId);
11626 /* Dump Foreign Server Comments */
11627 dumpComment(fout, labelq->data,
11628 NULL, srvinfo->rolname,
11629 srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
11633 destroyPQExpBuffer(q);
11634 destroyPQExpBuffer(delq);
11635 destroyPQExpBuffer(labelq);
11641 * This routine is used to dump any user mappings associated with the
11642 * server handed to this routine. Should be called after ArchiveEntry()
11646 dumpUserMappings(Archive *fout,
11647 const char *servername, const char *namespace,
11649 CatalogId catalogId, DumpId dumpId)
11661 q = createPQExpBuffer();
11662 tag = createPQExpBuffer();
11663 delq = createPQExpBuffer();
11664 query = createPQExpBuffer();
11667 * We read from the publicly accessible view pg_user_mappings, so as not
11668 * to fail if run by a non-superuser. Note that the view will show
11669 * umoptions as null if the user hasn't got privileges for the associated
11670 * server; this means that pg_dump will dump such a mapping, but with no
11671 * OPTIONS clause. A possible alternative is to skip such mappings
11672 * altogether, but it's not clear that that's an improvement.
11674 selectSourceSchema("pg_catalog");
11676 appendPQExpBuffer(query,
11678 "array_to_string(ARRAY("
11679 "SELECT quote_ident(option_name) || ' ' || "
11680 "quote_literal(option_value) "
11681 "FROM pg_options_to_table(umoptions)"
11682 "), ', ') AS umoptions "
11683 "FROM pg_user_mappings "
11684 "WHERE srvid = '%u'",
11687 res = PQexec(g_conn, query->data);
11688 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
11690 ntups = PQntuples(res);
11691 i_usename = PQfnumber(res, "usename");
11692 i_umoptions = PQfnumber(res, "umoptions");
11694 for (i = 0; i < ntups; i++)
11699 usename = PQgetvalue(res, i, i_usename);
11700 umoptions = PQgetvalue(res, i, i_umoptions);
11702 resetPQExpBuffer(q);
11703 appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
11704 appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
11706 if (umoptions && strlen(umoptions) > 0)
11707 appendPQExpBuffer(q, " OPTIONS (%s)", umoptions);
11709 appendPQExpBuffer(q, ";\n");
11711 resetPQExpBuffer(delq);
11712 appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
11713 appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
11715 resetPQExpBuffer(tag);
11716 appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
11717 usename, servername);
11719 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11724 "USER MAPPING", SECTION_PRE_DATA,
11725 q->data, delq->data, NULL,
11732 destroyPQExpBuffer(query);
11733 destroyPQExpBuffer(delq);
11734 destroyPQExpBuffer(q);
11738 * Write out default privileges information
11741 dumpDefaultACL(Archive *fout, DefaultACLInfo *daclinfo)
11747 /* Skip if not to be dumped */
11748 if (!daclinfo->dobj.dump || dataOnly || aclsSkip)
11751 q = createPQExpBuffer();
11752 tag = createPQExpBuffer();
11754 switch (daclinfo->defaclobjtype)
11756 case DEFACLOBJ_RELATION:
11759 case DEFACLOBJ_SEQUENCE:
11760 type = "SEQUENCES";
11762 case DEFACLOBJ_FUNCTION:
11763 type = "FUNCTIONS";
11766 /* shouldn't get here */
11767 write_msg(NULL, "unknown object type (%d) in default privileges\n",
11768 (int) daclinfo->defaclobjtype);
11770 type = ""; /* keep compiler quiet */
11773 appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
11775 /* build the actual command(s) for this tuple */
11776 if (!buildDefaultACLCommands(type,
11777 daclinfo->dobj.namespace != NULL ?
11778 daclinfo->dobj.namespace->dobj.name : NULL,
11779 daclinfo->defaclacl,
11780 daclinfo->defaclrole,
11781 fout->remoteVersion,
11784 write_msg(NULL, "could not parse default ACL list (%s)\n",
11785 daclinfo->defaclacl);
11789 ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
11791 daclinfo->dobj.namespace ? daclinfo->dobj.namespace->dobj.name : NULL,
11793 daclinfo->defaclrole,
11794 false, "DEFAULT ACL", SECTION_NONE,
11796 daclinfo->dobj.dependencies, daclinfo->dobj.nDeps,
11799 destroyPQExpBuffer(tag);
11800 destroyPQExpBuffer(q);
11804 * Write out grant/revoke information
11806 * 'objCatId' is the catalog ID of the underlying object.
11807 * 'objDumpId' is the dump ID of the underlying object.
11808 * 'type' must be one of
11809 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
11810 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
11811 * 'name' is the formatted name of the object. Must be quoted etc. already.
11812 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
11813 * 'tag' is the tag for the archive entry (typ. unquoted name of object).
11814 * 'nspname' is the namespace the object is in (NULL if none).
11815 * 'owner' is the owner, NULL if there is no owner (for languages).
11816 * 'acls' is the string read out of the fooacl system catalog field;
11817 * it will be parsed here.
11821 dumpACL(Archive *fout, CatalogId objCatId, DumpId objDumpId,
11822 const char *type, const char *name, const char *subname,
11823 const char *tag, const char *nspname, const char *owner,
11828 /* Do nothing if ACL dump is not enabled */
11832 /* --data-only skips ACLs *except* BLOB ACLs */
11833 if (dataOnly && strcmp(type, "LARGE OBJECT") != 0)
11836 sql = createPQExpBuffer();
11838 if (!buildACLCommands(name, subname, type, acls, owner,
11839 "", fout->remoteVersion, sql))
11841 write_msg(NULL, "could not parse ACL list (%s) for object \"%s\" (%s)\n",
11847 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11850 owner ? owner : "",
11851 false, "ACL", SECTION_NONE,
11852 sql->data, "", NULL,
11856 destroyPQExpBuffer(sql);
11862 * This routine is used to dump any security labels associated with the
11863 * object handed to this routine. The routine takes a constant character
11864 * string for the target part of the security-label command, plus
11865 * the namespace and owner of the object (for labeling the ArchiveEntry),
11866 * plus catalog ID and subid which are the lookup key for pg_seclabel,
11867 * plus the dump ID for the object (for setting a dependency).
11868 * If a matching pg_seclabel entry is found, it is dumped.
11870 * Note: although this routine takes a dumpId for dependency purposes,
11871 * that purpose is just to mark the dependency in the emitted dump file
11872 * for possible future use by pg_restore. We do NOT use it for determining
11873 * ordering of the label in the dump file, because this routine is called
11874 * after dependency sorting occurs. This routine should be called just after
11875 * calling ArchiveEntry() for the specified object.
11878 dumpSecLabel(Archive *fout, const char *target,
11879 const char *namespace, const char *owner,
11880 CatalogId catalogId, int subid, DumpId dumpId)
11882 SecLabelItem *labels;
11887 /* do nothing, if --no-security-labels is supplied */
11888 if (no_security_labels)
11891 /* Comments are schema not data ... except blob comments are data */
11892 if (strncmp(target, "LARGE OBJECT ", 13) != 0)
11903 /* Search for security labels associated with catalogId, using table */
11904 nlabels = findSecLabels(fout, catalogId.tableoid, catalogId.oid, &labels);
11906 query = createPQExpBuffer();
11908 for (i = 0; i < nlabels; i++)
11911 * Ignore label entries for which the subid doesn't match.
11913 if (labels[i].objsubid != subid)
11916 appendPQExpBuffer(query,
11917 "SECURITY LABEL FOR %s ON %s IS ",
11918 fmtId(labels[i].provider), target);
11919 appendStringLiteralAH(query, labels[i].label, fout);
11920 appendPQExpBuffer(query, ";\n");
11923 if (query->len > 0)
11925 ArchiveEntry(fout, nilCatalogId, createDumpId(),
11926 target, namespace, NULL, owner,
11927 false, "SECURITY LABEL", SECTION_NONE,
11928 query->data, "", NULL,
11932 destroyPQExpBuffer(query);
11936 * dumpTableSecLabel
11938 * As above, but dump security label for both the specified table (or view)
11942 dumpTableSecLabel(Archive *fout, TableInfo *tbinfo, const char *reltypename)
11944 SecLabelItem *labels;
11948 PQExpBuffer target;
11950 /* do nothing, if --no-security-labels is supplied */
11951 if (no_security_labels)
11954 /* SecLabel are SCHEMA not data */
11958 /* Search for comments associated with relation, using table */
11959 nlabels = findSecLabels(fout,
11960 tbinfo->dobj.catId.tableoid,
11961 tbinfo->dobj.catId.oid,
11964 /* If security labels exist, build SECURITY LABEL statements */
11968 query = createPQExpBuffer();
11969 target = createPQExpBuffer();
11971 for (i = 0; i < nlabels; i++)
11973 const char *colname;
11974 const char *provider = labels[i].provider;
11975 const char *label = labels[i].label;
11976 int objsubid = labels[i].objsubid;
11978 resetPQExpBuffer(target);
11981 appendPQExpBuffer(target, "%s %s", reltypename,
11982 fmtId(tbinfo->dobj.name));
11986 colname = getAttrName(objsubid, tbinfo);
11987 /* first fmtId result must be consumed before calling it again */
11988 appendPQExpBuffer(target, "COLUMN %s", fmtId(tbinfo->dobj.name));
11989 appendPQExpBuffer(target, ".%s", fmtId(colname));
11991 appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
11992 fmtId(provider), target->data);
11993 appendStringLiteralAH(query, label, fout);
11994 appendPQExpBuffer(query, ";\n");
11996 if (query->len > 0)
11998 resetPQExpBuffer(target);
11999 appendPQExpBuffer(target, "%s %s", reltypename,
12000 fmtId(tbinfo->dobj.name));
12001 ArchiveEntry(fout, nilCatalogId, createDumpId(),
12003 tbinfo->dobj.namespace->dobj.name,
12004 NULL, tbinfo->rolname,
12005 false, "SECURITY LABEL", SECTION_NONE,
12006 query->data, "", NULL,
12007 &(tbinfo->dobj.dumpId), 1,
12010 destroyPQExpBuffer(query);
12011 destroyPQExpBuffer(target);
12017 * Find the security label(s), if any, associated with the given object.
12018 * All the objsubid values associated with the given classoid/objoid are
12019 * found with one search.
12022 findSecLabels(Archive *fout, Oid classoid, Oid objoid, SecLabelItem **items)
12024 /* static storage for table of security labels */
12025 static SecLabelItem *labels = NULL;
12026 static int nlabels = -1;
12028 SecLabelItem *middle = NULL;
12030 SecLabelItem *high;
12033 /* Get security labels if we didn't already */
12035 nlabels = collectSecLabels(fout, &labels);
12037 if (nlabels <= 0) /* no labels, so no match is possible */
12044 * Do binary search to find some item matching the object.
12047 high = &labels[nlabels - 1];
12048 while (low <= high)
12050 middle = low + (high - low) / 2;
12052 if (classoid < middle->classoid)
12054 else if (classoid > middle->classoid)
12056 else if (objoid < middle->objoid)
12058 else if (objoid > middle->objoid)
12061 break; /* found a match */
12064 if (low > high) /* no matches */
12071 * Now determine how many items match the object. The search loop
12072 * invariant still holds: only items between low and high inclusive could
12076 while (middle > low)
12078 if (classoid != middle[-1].classoid ||
12079 objoid != middle[-1].objoid)
12088 while (middle <= high)
12090 if (classoid != middle->classoid ||
12091 objoid != middle->objoid)
12103 * Construct a table of all security labels available for database objects.
12104 * It's much faster to pull them all at once.
12106 * The table is sorted by classoid/objid/objsubid for speed in lookup.
12109 collectSecLabels(Archive *fout, SecLabelItem **items)
12120 SecLabelItem *labels;
12122 query = createPQExpBuffer();
12124 appendPQExpBuffer(query,
12125 "SELECT label, provider, classoid, objoid, objsubid "
12126 "FROM pg_catalog.pg_seclabel "
12127 "ORDER BY classoid, objoid, objsubid");
12129 res = PQexec(g_conn, query->data);
12130 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12132 /* Construct lookup table containing OIDs in numeric form */
12133 i_label = PQfnumber(res, "label");
12134 i_provider = PQfnumber(res, "provider");
12135 i_classoid = PQfnumber(res, "classoid");
12136 i_objoid = PQfnumber(res, "objoid");
12137 i_objsubid = PQfnumber(res, "objsubid");
12139 ntups = PQntuples(res);
12141 labels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
12143 for (i = 0; i < ntups; i++)
12145 labels[i].label = PQgetvalue(res, i, i_label);
12146 labels[i].provider = PQgetvalue(res, i, i_provider);
12147 labels[i].classoid = atooid(PQgetvalue(res, i, i_classoid));
12148 labels[i].objoid = atooid(PQgetvalue(res, i, i_objoid));
12149 labels[i].objsubid = atoi(PQgetvalue(res, i, i_objsubid));
12152 /* Do NOT free the PGresult since we are keeping pointers into it */
12153 destroyPQExpBuffer(query);
12161 * write out to fout the declarations (not data) of a user-defined table
12164 dumpTable(Archive *fout, TableInfo *tbinfo)
12166 if (tbinfo->dobj.dump)
12170 if (tbinfo->relkind == RELKIND_SEQUENCE)
12171 dumpSequence(fout, tbinfo);
12172 else if (!dataOnly)
12173 dumpTableSchema(fout, tbinfo);
12175 /* Handle the ACL here */
12176 namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
12177 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12178 (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" :
12180 namecopy, NULL, tbinfo->dobj.name,
12181 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12185 * Handle column ACLs, if any. Note: we pull these with a separate
12186 * query rather than trying to fetch them during getTableAttrs, so
12187 * that we won't miss ACLs on system columns.
12189 if (g_fout->remoteVersion >= 80400)
12191 PQExpBuffer query = createPQExpBuffer();
12195 appendPQExpBuffer(query,
12196 "SELECT attname, attacl FROM pg_catalog.pg_attribute "
12197 "WHERE attrelid = '%u' AND NOT attisdropped AND attacl IS NOT NULL "
12199 tbinfo->dobj.catId.oid);
12200 res = PQexec(g_conn, query->data);
12201 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12203 for (i = 0; i < PQntuples(res); i++)
12205 char *attname = PQgetvalue(res, i, 0);
12206 char *attacl = PQgetvalue(res, i, 1);
12210 attnamecopy = pg_strdup(fmtId(attname));
12211 acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2);
12212 sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
12213 /* Column's GRANT type is always TABLE */
12214 dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
12215 namecopy, attnamecopy, acltag,
12216 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
12222 destroyPQExpBuffer(query);
12231 * write the declaration (not data) of one user-defined table or view
12234 dumpTableSchema(Archive *fout, TableInfo *tbinfo)
12236 PQExpBuffer query = createPQExpBuffer();
12237 PQExpBuffer q = createPQExpBuffer();
12238 PQExpBuffer delq = createPQExpBuffer();
12239 PQExpBuffer labelq = createPQExpBuffer();
12242 TableInfo **parents;
12243 int actual_atts; /* number of attrs in this CREATE statment */
12244 const char *reltypename;
12251 /* Make sure we are in proper schema */
12252 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
12254 if (binary_upgrade)
12255 binary_upgrade_set_type_oids_by_rel_oid(q,
12256 tbinfo->dobj.catId.oid);
12258 /* Is it a table or a view? */
12259 if (tbinfo->relkind == RELKIND_VIEW)
12263 reltypename = "VIEW";
12265 /* Fetch the view definition */
12266 if (g_fout->remoteVersion >= 70300)
12268 /* Beginning in 7.3, viewname is not unique; rely on OID */
12269 appendPQExpBuffer(query,
12270 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
12271 tbinfo->dobj.catId.oid);
12275 appendPQExpBuffer(query, "SELECT definition AS viewdef "
12276 "FROM pg_views WHERE viewname = ");
12277 appendStringLiteralAH(query, tbinfo->dobj.name, fout);
12278 appendPQExpBuffer(query, ";");
12281 res = PQexec(g_conn, query->data);
12282 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12284 if (PQntuples(res) != 1)
12286 if (PQntuples(res) < 1)
12287 write_msg(NULL, "query to obtain definition of view \"%s\" returned no data\n",
12288 tbinfo->dobj.name);
12290 write_msg(NULL, "query to obtain definition of view \"%s\" returned more than one definition\n",
12291 tbinfo->dobj.name);
12295 viewdef = PQgetvalue(res, 0, 0);
12297 if (strlen(viewdef) == 0)
12299 write_msg(NULL, "definition of view \"%s\" appears to be empty (length zero)\n",
12300 tbinfo->dobj.name);
12305 * DROP must be fully qualified in case same name appears in
12308 appendPQExpBuffer(delq, "DROP VIEW %s.",
12309 fmtId(tbinfo->dobj.namespace->dobj.name));
12310 appendPQExpBuffer(delq, "%s;\n",
12311 fmtId(tbinfo->dobj.name));
12313 if (binary_upgrade)
12314 binary_upgrade_set_pg_class_oids(q, tbinfo->dobj.catId.oid, false);
12316 appendPQExpBuffer(q, "CREATE VIEW %s AS\n %s\n",
12317 fmtId(tbinfo->dobj.name), viewdef);
12319 appendPQExpBuffer(labelq, "VIEW %s",
12320 fmtId(tbinfo->dobj.name));
12326 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12331 reltypename = "FOREIGN TABLE";
12333 /* retrieve name of foreign server and generic options */
12334 appendPQExpBuffer(query,
12335 "SELECT fs.srvname, "
12336 "pg_catalog.array_to_string(ARRAY("
12337 "SELECT pg_catalog.quote_ident(option_name) || "
12338 "' ' || pg_catalog.quote_literal(option_value) "
12339 "FROM pg_catalog.pg_options_to_table(ftoptions)"
12340 "), ', ') AS ftoptions "
12341 "FROM pg_catalog.pg_foreign_table ft "
12342 "JOIN pg_catalog.pg_foreign_server fs "
12343 "ON (fs.oid = ft.ftserver) "
12344 "WHERE ft.ftrelid = '%u'",
12345 tbinfo->dobj.catId.oid);
12346 res = PQexec(g_conn, query->data);
12347 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
12348 if (PQntuples(res) != 1)
12350 write_msg(NULL, ngettext("query returned %d foreign server entry for foreign table \"%s\"\n",
12351 "query returned %d foreign server entries for foreign table \"%s\"\n",
12353 PQntuples(res), tbinfo->dobj.name);
12356 i_srvname = PQfnumber(res, "srvname");
12357 i_ftoptions = PQfnumber(res, "ftoptions");
12358 srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
12359 ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
12364 reltypename = "TABLE";
12368 numParents = tbinfo->numParents;
12369 parents = tbinfo->parents;
12372 * DROP must be fully qualified in case same name appears in
12375 appendPQExpBuffer(delq, "DROP %s %s.", reltypename,
12376 fmtId(tbinfo->dobj.namespace->dobj.name));
12377 appendPQExpBuffer(delq, "%s;\n",
12378 fmtId(tbinfo->dobj.name));
12380 appendPQExpBuffer(labelq, "%s %s", reltypename,
12381 fmtId(tbinfo->dobj.name));
12383 if (binary_upgrade)
12384 binary_upgrade_set_pg_class_oids(q, tbinfo->dobj.catId.oid, false);
12386 appendPQExpBuffer(q, "CREATE %s%s %s",
12387 tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
12390 fmtId(tbinfo->dobj.name));
12393 * In case of a binary upgrade, we dump the table normally and attach
12394 * it to the type afterward.
12396 if (tbinfo->reloftype && !binary_upgrade)
12397 appendPQExpBuffer(q, " OF %s", tbinfo->reloftype);
12399 for (j = 0; j < tbinfo->numatts; j++)
12402 * Normally, dump if it's one of the table's own attrs, and not
12403 * dropped. But for binary upgrade, dump all the columns.
12405 if ((!tbinfo->inhAttrs[j] && !tbinfo->attisdropped[j]) ||
12409 * Default value --- suppress if inherited (except in
12410 * binary-upgrade case, where we're not doing normal
12411 * inheritance) or if it's to be printed separately.
12413 bool has_default = (tbinfo->attrdefs[j] != NULL
12414 && (!tbinfo->inhAttrDef[j] || binary_upgrade)
12415 && !tbinfo->attrdefs[j]->separate);
12418 * Not Null constraint --- suppress if inherited, except in
12419 * binary-upgrade case.
12421 bool has_notnull = (tbinfo->notnull[j]
12422 && (!tbinfo->inhNotNull[j] || binary_upgrade));
12424 if (tbinfo->reloftype && !has_default && !has_notnull && !binary_upgrade)
12427 /* Format properly if not first attr */
12428 if (actual_atts == 0)
12429 appendPQExpBuffer(q, " (");
12431 appendPQExpBuffer(q, ",");
12432 appendPQExpBuffer(q, "\n ");
12435 /* Attribute name */
12436 appendPQExpBuffer(q, "%s ",
12437 fmtId(tbinfo->attnames[j]));
12439 if (tbinfo->attisdropped[j])
12442 * ALTER TABLE DROP COLUMN clears pg_attribute.atttypid,
12443 * so we will not have gotten a valid type name; insert
12444 * INTEGER as a stopgap. We'll clean things up later.
12446 appendPQExpBuffer(q, "INTEGER /* dummy */");
12447 /* Skip all the rest, too */
12451 /* Attribute type */
12452 if (tbinfo->reloftype && !binary_upgrade)
12454 appendPQExpBuffer(q, "WITH OPTIONS");
12456 else if (g_fout->remoteVersion >= 70100)
12458 appendPQExpBuffer(q, "%s",
12459 tbinfo->atttypnames[j]);
12463 /* If no format_type, fake it */
12464 appendPQExpBuffer(q, "%s",
12465 myFormatType(tbinfo->atttypnames[j],
12466 tbinfo->atttypmod[j]));
12469 /* Add collation if not default for the type */
12470 if (OidIsValid(tbinfo->attcollation[j]))
12474 coll = findCollationByOid(tbinfo->attcollation[j]);
12477 /* always schema-qualify, don't try to be smart */
12478 appendPQExpBuffer(q, " COLLATE %s.",
12479 fmtId(coll->dobj.namespace->dobj.name));
12480 appendPQExpBuffer(q, "%s",
12481 fmtId(coll->dobj.name));
12486 appendPQExpBuffer(q, " DEFAULT %s",
12487 tbinfo->attrdefs[j]->adef_expr);
12490 appendPQExpBuffer(q, " NOT NULL");
12495 * Add non-inherited CHECK constraints, if any.
12497 for (j = 0; j < tbinfo->ncheck; j++)
12499 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12501 if (constr->separate || !constr->conislocal)
12504 if (actual_atts == 0)
12505 appendPQExpBuffer(q, " (\n ");
12507 appendPQExpBuffer(q, ",\n ");
12509 appendPQExpBuffer(q, "CONSTRAINT %s ",
12510 fmtId(constr->dobj.name));
12511 appendPQExpBuffer(q, "%s", constr->condef);
12517 appendPQExpBuffer(q, "\n)");
12518 else if (!(tbinfo->reloftype && !binary_upgrade))
12521 * We must have a parenthesized attribute list, even though empty,
12522 * when not using the OF TYPE syntax.
12524 appendPQExpBuffer(q, " (\n)");
12527 if (numParents > 0 && !binary_upgrade)
12529 appendPQExpBuffer(q, "\nINHERITS (");
12530 for (k = 0; k < numParents; k++)
12532 TableInfo *parentRel = parents[k];
12535 appendPQExpBuffer(q, ", ");
12536 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12537 appendPQExpBuffer(q, "%s.",
12538 fmtId(parentRel->dobj.namespace->dobj.name));
12539 appendPQExpBuffer(q, "%s",
12540 fmtId(parentRel->dobj.name));
12542 appendPQExpBuffer(q, ")");
12545 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
12546 appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
12548 if ((tbinfo->reloptions && strlen(tbinfo->reloptions) > 0) ||
12549 (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0))
12551 bool addcomma = false;
12553 appendPQExpBuffer(q, "\nWITH (");
12554 if (tbinfo->reloptions && strlen(tbinfo->reloptions) > 0)
12557 appendPQExpBuffer(q, "%s", tbinfo->reloptions);
12559 if (tbinfo->toast_reloptions && strlen(tbinfo->toast_reloptions) > 0)
12561 appendPQExpBuffer(q, "%s%s", addcomma ? ", " : "",
12562 tbinfo->toast_reloptions);
12564 appendPQExpBuffer(q, ")");
12567 /* Dump generic options if any */
12568 if (ftoptions && ftoptions[0])
12569 appendPQExpBuffer(q, "\nOPTIONS (%s)", ftoptions);
12571 appendPQExpBuffer(q, ";\n");
12574 * To create binary-compatible heap files, we have to ensure the same
12575 * physical column order, including dropped columns, as in the
12576 * original. Therefore, we create dropped columns above and drop them
12577 * here, also updating their attlen/attalign values so that the
12578 * dropped column can be skipped properly. (We do not bother with
12579 * restoring the original attbyval setting.) Also, inheritance
12580 * relationships are set up by doing ALTER INHERIT rather than using
12581 * an INHERITS clause --- the latter would possibly mess up the column
12582 * order. That also means we have to take care about setting
12583 * attislocal correctly, plus fix up any inherited CHECK constraints.
12584 * Analogously, we set up typed tables using ALTER TABLE / OF here.
12586 if (binary_upgrade && tbinfo->relkind == RELKIND_RELATION)
12588 for (j = 0; j < tbinfo->numatts; j++)
12590 if (tbinfo->attisdropped[j])
12592 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate dropped column.\n");
12593 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12594 "SET attlen = %d, "
12595 "attalign = '%c', attbyval = false\n"
12596 "WHERE attname = ",
12598 tbinfo->attalign[j]);
12599 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12600 appendPQExpBuffer(q, "\n AND attrelid = ");
12601 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12602 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12604 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12605 fmtId(tbinfo->dobj.name));
12606 appendPQExpBuffer(q, "DROP COLUMN %s;\n",
12607 fmtId(tbinfo->attnames[j]));
12609 else if (!tbinfo->attislocal[j])
12611 appendPQExpBuffer(q, "\n-- For binary upgrade, recreate inherited column.\n");
12612 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_attribute\n"
12613 "SET attislocal = false\n"
12614 "WHERE attname = ");
12615 appendStringLiteralAH(q, tbinfo->attnames[j], fout);
12616 appendPQExpBuffer(q, "\n AND attrelid = ");
12617 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12618 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12622 for (k = 0; k < tbinfo->ncheck; k++)
12624 ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
12626 if (constr->separate || constr->conislocal)
12629 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inherited constraint.\n");
12630 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12631 fmtId(tbinfo->dobj.name));
12632 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
12633 fmtId(constr->dobj.name));
12634 appendPQExpBuffer(q, "%s;\n", constr->condef);
12635 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_constraint\n"
12636 "SET conislocal = false\n"
12637 "WHERE contype = 'c' AND conname = ");
12638 appendStringLiteralAH(q, constr->dobj.name, fout);
12639 appendPQExpBuffer(q, "\n AND conrelid = ");
12640 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12641 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12644 if (numParents > 0)
12646 appendPQExpBuffer(q, "\n-- For binary upgrade, set up inheritance this way.\n");
12647 for (k = 0; k < numParents; k++)
12649 TableInfo *parentRel = parents[k];
12651 appendPQExpBuffer(q, "ALTER TABLE ONLY %s INHERIT ",
12652 fmtId(tbinfo->dobj.name));
12653 if (parentRel->dobj.namespace != tbinfo->dobj.namespace)
12654 appendPQExpBuffer(q, "%s.",
12655 fmtId(parentRel->dobj.namespace->dobj.name));
12656 appendPQExpBuffer(q, "%s;\n",
12657 fmtId(parentRel->dobj.name));
12661 if (tbinfo->reloftype)
12663 appendPQExpBuffer(q, "\n-- For binary upgrade, set up typed tables this way.\n");
12664 appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
12665 fmtId(tbinfo->dobj.name),
12666 tbinfo->reloftype);
12669 appendPQExpBuffer(q, "\n-- For binary upgrade, set heap's relfrozenxid\n");
12670 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12671 "SET relfrozenxid = '%u'\n"
12673 tbinfo->frozenxid);
12674 appendStringLiteralAH(q, fmtId(tbinfo->dobj.name), fout);
12675 appendPQExpBuffer(q, "::pg_catalog.regclass;\n");
12677 if (tbinfo->toast_oid)
12679 /* We preserve the toast oids, so we can use it during restore */
12680 appendPQExpBuffer(q, "\n-- For binary upgrade, set toast's relfrozenxid\n");
12681 appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
12682 "SET relfrozenxid = '%u'\n"
12683 "WHERE oid = '%u';\n",
12684 tbinfo->toast_frozenxid, tbinfo->toast_oid);
12688 /* Loop dumping statistics and storage statements */
12689 for (j = 0; j < tbinfo->numatts; j++)
12692 * Dump per-column statistics information. We only issue an ALTER
12693 * TABLE statement if the attstattarget entry for this column is
12694 * non-negative (i.e. it's not the default value)
12696 if (tbinfo->attstattarget[j] >= 0 &&
12697 !tbinfo->attisdropped[j])
12699 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12700 fmtId(tbinfo->dobj.name));
12701 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12702 fmtId(tbinfo->attnames[j]));
12703 appendPQExpBuffer(q, "SET STATISTICS %d;\n",
12704 tbinfo->attstattarget[j]);
12708 * Dump per-column storage information. The statement is only
12709 * dumped if the storage has been changed from the type's default.
12711 if (!tbinfo->attisdropped[j] && tbinfo->attstorage[j] != tbinfo->typstorage[j])
12713 switch (tbinfo->attstorage[j])
12719 storage = "EXTERNAL";
12725 storage = "EXTENDED";
12732 * Only dump the statement if it's a storage type we recognize
12734 if (storage != NULL)
12736 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12737 fmtId(tbinfo->dobj.name));
12738 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12739 fmtId(tbinfo->attnames[j]));
12740 appendPQExpBuffer(q, "SET STORAGE %s;\n",
12746 * Dump per-column attributes.
12748 if (tbinfo->attoptions[j] && tbinfo->attoptions[j][0] != '\0')
12750 appendPQExpBuffer(q, "ALTER TABLE ONLY %s ",
12751 fmtId(tbinfo->dobj.name));
12752 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12753 fmtId(tbinfo->attnames[j]));
12754 appendPQExpBuffer(q, "SET (%s);\n",
12755 tbinfo->attoptions[j]);
12759 * Dump per-column fdw options.
12761 if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
12762 tbinfo->attfdwoptions[j] &&
12763 tbinfo->attfdwoptions[j][0] != '\0')
12765 appendPQExpBuffer(q, "ALTER FOREIGN TABLE %s ",
12766 fmtId(tbinfo->dobj.name));
12767 appendPQExpBuffer(q, "ALTER COLUMN %s ",
12768 fmtId(tbinfo->attnames[j]));
12769 appendPQExpBuffer(q, "OPTIONS (%s);\n",
12770 tbinfo->attfdwoptions[j]);
12775 if (binary_upgrade)
12776 binary_upgrade_extension_member(q, &tbinfo->dobj, labelq->data);
12778 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
12780 tbinfo->dobj.namespace->dobj.name,
12781 (tbinfo->relkind == RELKIND_VIEW) ? NULL : tbinfo->reltablespace,
12783 (strcmp(reltypename, "TABLE") == 0) ? tbinfo->hasoids : false,
12784 reltypename, SECTION_PRE_DATA,
12785 q->data, delq->data, NULL,
12786 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
12790 /* Dump Table Comments */
12791 dumpTableComment(fout, tbinfo, reltypename);
12793 /* Dump Table Security Labels */
12794 dumpTableSecLabel(fout, tbinfo, reltypename);
12796 /* Dump comments on inlined table constraints */
12797 for (j = 0; j < tbinfo->ncheck; j++)
12799 ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
12801 if (constr->separate || !constr->conislocal)
12804 dumpTableConstraintComment(fout, constr);
12807 destroyPQExpBuffer(query);
12808 destroyPQExpBuffer(q);
12809 destroyPQExpBuffer(delq);
12810 destroyPQExpBuffer(labelq);
12814 * dumpAttrDef --- dump an attribute's default-value declaration
12817 dumpAttrDef(Archive *fout, AttrDefInfo *adinfo)
12819 TableInfo *tbinfo = adinfo->adtable;
12820 int adnum = adinfo->adnum;
12824 /* Only print it if "separate" mode is selected */
12825 if (!tbinfo->dobj.dump || !adinfo->separate || dataOnly)
12828 /* Don't print inherited defaults, either, except for binary upgrade */
12829 if (tbinfo->inhAttrDef[adnum - 1] && !binary_upgrade)
12832 q = createPQExpBuffer();
12833 delq = createPQExpBuffer();
12835 appendPQExpBuffer(q, "ALTER TABLE %s ",
12836 fmtId(tbinfo->dobj.name));
12837 appendPQExpBuffer(q, "ALTER COLUMN %s SET DEFAULT %s;\n",
12838 fmtId(tbinfo->attnames[adnum - 1]),
12839 adinfo->adef_expr);
12842 * DROP must be fully qualified in case same name appears in pg_catalog
12844 appendPQExpBuffer(delq, "ALTER TABLE %s.",
12845 fmtId(tbinfo->dobj.namespace->dobj.name));
12846 appendPQExpBuffer(delq, "%s ",
12847 fmtId(tbinfo->dobj.name));
12848 appendPQExpBuffer(delq, "ALTER COLUMN %s DROP DEFAULT;\n",
12849 fmtId(tbinfo->attnames[adnum - 1]));
12851 ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
12852 tbinfo->attnames[adnum - 1],
12853 tbinfo->dobj.namespace->dobj.name,
12856 false, "DEFAULT", SECTION_PRE_DATA,
12857 q->data, delq->data, NULL,
12858 adinfo->dobj.dependencies, adinfo->dobj.nDeps,
12861 destroyPQExpBuffer(q);
12862 destroyPQExpBuffer(delq);
12866 * getAttrName: extract the correct name for an attribute
12868 * The array tblInfo->attnames[] only provides names of user attributes;
12869 * if a system attribute number is supplied, we have to fake it.
12870 * We also do a little bit of bounds checking for safety's sake.
12872 static const char *
12873 getAttrName(int attrnum, TableInfo *tblInfo)
12875 if (attrnum > 0 && attrnum <= tblInfo->numatts)
12876 return tblInfo->attnames[attrnum - 1];
12879 case SelfItemPointerAttributeNumber:
12881 case ObjectIdAttributeNumber:
12883 case MinTransactionIdAttributeNumber:
12885 case MinCommandIdAttributeNumber:
12887 case MaxTransactionIdAttributeNumber:
12889 case MaxCommandIdAttributeNumber:
12891 case TableOidAttributeNumber:
12894 write_msg(NULL, "invalid column number %d for table \"%s\"\n",
12895 attrnum, tblInfo->dobj.name);
12897 return NULL; /* keep compiler quiet */
12902 * write out to fout a user-defined index
12905 dumpIndex(Archive *fout, IndxInfo *indxinfo)
12907 TableInfo *tbinfo = indxinfo->indextable;
12910 PQExpBuffer labelq;
12915 q = createPQExpBuffer();
12916 delq = createPQExpBuffer();
12917 labelq = createPQExpBuffer();
12919 appendPQExpBuffer(labelq, "INDEX %s",
12920 fmtId(indxinfo->dobj.name));
12923 * If there's an associated constraint, don't dump the index per se, but
12924 * do dump any comment for it. (This is safe because dependency ordering
12925 * will have ensured the constraint is emitted first.)
12927 if (indxinfo->indexconstraint == 0)
12929 if (binary_upgrade)
12930 binary_upgrade_set_pg_class_oids(q, indxinfo->dobj.catId.oid, true);
12932 /* Plain secondary index */
12933 appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
12935 /* If the index is clustered, we need to record that. */
12936 if (indxinfo->indisclustered)
12938 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
12939 fmtId(tbinfo->dobj.name));
12940 appendPQExpBuffer(q, " ON %s;\n",
12941 fmtId(indxinfo->dobj.name));
12945 * DROP must be fully qualified in case same name appears in
12948 appendPQExpBuffer(delq, "DROP INDEX %s.",
12949 fmtId(tbinfo->dobj.namespace->dobj.name));
12950 appendPQExpBuffer(delq, "%s;\n",
12951 fmtId(indxinfo->dobj.name));
12953 ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
12954 indxinfo->dobj.name,
12955 tbinfo->dobj.namespace->dobj.name,
12956 indxinfo->tablespace,
12957 tbinfo->rolname, false,
12958 "INDEX", SECTION_POST_DATA,
12959 q->data, delq->data, NULL,
12960 indxinfo->dobj.dependencies, indxinfo->dobj.nDeps,
12964 /* Dump Index Comments */
12965 dumpComment(fout, labelq->data,
12966 tbinfo->dobj.namespace->dobj.name,
12968 indxinfo->dobj.catId, 0, indxinfo->dobj.dumpId);
12970 destroyPQExpBuffer(q);
12971 destroyPQExpBuffer(delq);
12972 destroyPQExpBuffer(labelq);
12977 * write out to fout a user-defined constraint
12980 dumpConstraint(Archive *fout, ConstraintInfo *coninfo)
12982 TableInfo *tbinfo = coninfo->contable;
12986 /* Skip if not to be dumped */
12987 if (!coninfo->dobj.dump || dataOnly)
12990 q = createPQExpBuffer();
12991 delq = createPQExpBuffer();
12993 if (coninfo->contype == 'p' ||
12994 coninfo->contype == 'u' ||
12995 coninfo->contype == 'x')
12997 /* Index-related constraint */
12998 IndxInfo *indxinfo;
13001 indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
13003 if (indxinfo == NULL)
13005 write_msg(NULL, "missing index for constraint \"%s\"\n",
13006 coninfo->dobj.name);
13010 if (binary_upgrade)
13011 binary_upgrade_set_pg_class_oids(q, indxinfo->dobj.catId.oid, true);
13013 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13014 fmtId(tbinfo->dobj.name));
13015 appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
13016 fmtId(coninfo->dobj.name));
13018 if (coninfo->condef)
13020 /* pg_get_constraintdef should have provided everything */
13021 appendPQExpBuffer(q, "%s;\n", coninfo->condef);
13025 appendPQExpBuffer(q, "%s (",
13026 coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
13027 for (k = 0; k < indxinfo->indnkeys; k++)
13029 int indkey = (int) indxinfo->indkeys[k];
13030 const char *attname;
13032 if (indkey == InvalidAttrNumber)
13034 attname = getAttrName(indkey, tbinfo);
13036 appendPQExpBuffer(q, "%s%s",
13037 (k == 0) ? "" : ", ",
13041 appendPQExpBuffer(q, ")");
13043 if (indxinfo->options && strlen(indxinfo->options) > 0)
13044 appendPQExpBuffer(q, " WITH (%s)", indxinfo->options);
13046 if (coninfo->condeferrable)
13048 appendPQExpBuffer(q, " DEFERRABLE");
13049 if (coninfo->condeferred)
13050 appendPQExpBuffer(q, " INITIALLY DEFERRED");
13053 appendPQExpBuffer(q, ";\n");
13056 /* If the index is clustered, we need to record that. */
13057 if (indxinfo->indisclustered)
13059 appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
13060 fmtId(tbinfo->dobj.name));
13061 appendPQExpBuffer(q, " ON %s;\n",
13062 fmtId(indxinfo->dobj.name));
13066 * DROP must be fully qualified in case same name appears in
13069 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13070 fmtId(tbinfo->dobj.namespace->dobj.name));
13071 appendPQExpBuffer(delq, "%s ",
13072 fmtId(tbinfo->dobj.name));
13073 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13074 fmtId(coninfo->dobj.name));
13076 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13077 coninfo->dobj.name,
13078 tbinfo->dobj.namespace->dobj.name,
13079 indxinfo->tablespace,
13080 tbinfo->rolname, false,
13081 "CONSTRAINT", SECTION_POST_DATA,
13082 q->data, delq->data, NULL,
13083 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13086 else if (coninfo->contype == 'f')
13089 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
13090 * current table data is not processed
13092 appendPQExpBuffer(q, "ALTER TABLE ONLY %s\n",
13093 fmtId(tbinfo->dobj.name));
13094 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13095 fmtId(coninfo->dobj.name),
13099 * DROP must be fully qualified in case same name appears in
13102 appendPQExpBuffer(delq, "ALTER TABLE ONLY %s.",
13103 fmtId(tbinfo->dobj.namespace->dobj.name));
13104 appendPQExpBuffer(delq, "%s ",
13105 fmtId(tbinfo->dobj.name));
13106 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13107 fmtId(coninfo->dobj.name));
13109 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13110 coninfo->dobj.name,
13111 tbinfo->dobj.namespace->dobj.name,
13113 tbinfo->rolname, false,
13114 "FK CONSTRAINT", SECTION_POST_DATA,
13115 q->data, delq->data, NULL,
13116 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13119 else if (coninfo->contype == 'c' && tbinfo)
13121 /* CHECK constraint on a table */
13123 /* Ignore if not to be dumped separately */
13124 if (coninfo->separate)
13126 /* not ONLY since we want it to propagate to children */
13127 appendPQExpBuffer(q, "ALTER TABLE %s\n",
13128 fmtId(tbinfo->dobj.name));
13129 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13130 fmtId(coninfo->dobj.name),
13134 * DROP must be fully qualified in case same name appears in
13137 appendPQExpBuffer(delq, "ALTER TABLE %s.",
13138 fmtId(tbinfo->dobj.namespace->dobj.name));
13139 appendPQExpBuffer(delq, "%s ",
13140 fmtId(tbinfo->dobj.name));
13141 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13142 fmtId(coninfo->dobj.name));
13144 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13145 coninfo->dobj.name,
13146 tbinfo->dobj.namespace->dobj.name,
13148 tbinfo->rolname, false,
13149 "CHECK CONSTRAINT", SECTION_POST_DATA,
13150 q->data, delq->data, NULL,
13151 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13155 else if (coninfo->contype == 'c' && tbinfo == NULL)
13157 /* CHECK constraint on a domain */
13158 TypeInfo *tyinfo = coninfo->condomain;
13160 /* Ignore if not to be dumped separately */
13161 if (coninfo->separate)
13163 appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
13164 fmtId(tyinfo->dobj.name));
13165 appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
13166 fmtId(coninfo->dobj.name),
13170 * DROP must be fully qualified in case same name appears in
13173 appendPQExpBuffer(delq, "ALTER DOMAIN %s.",
13174 fmtId(tyinfo->dobj.namespace->dobj.name));
13175 appendPQExpBuffer(delq, "%s ",
13176 fmtId(tyinfo->dobj.name));
13177 appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
13178 fmtId(coninfo->dobj.name));
13180 ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
13181 coninfo->dobj.name,
13182 tyinfo->dobj.namespace->dobj.name,
13184 tyinfo->rolname, false,
13185 "CHECK CONSTRAINT", SECTION_POST_DATA,
13186 q->data, delq->data, NULL,
13187 coninfo->dobj.dependencies, coninfo->dobj.nDeps,
13193 write_msg(NULL, "unrecognized constraint type: %c\n", coninfo->contype);
13197 /* Dump Constraint Comments --- only works for table constraints */
13198 if (tbinfo && coninfo->separate)
13199 dumpTableConstraintComment(fout, coninfo);
13201 destroyPQExpBuffer(q);
13202 destroyPQExpBuffer(delq);
13206 * dumpTableConstraintComment --- dump a constraint's comment if any
13208 * This is split out because we need the function in two different places
13209 * depending on whether the constraint is dumped as part of CREATE TABLE
13210 * or as a separate ALTER command.
13213 dumpTableConstraintComment(Archive *fout, ConstraintInfo *coninfo)
13215 TableInfo *tbinfo = coninfo->contable;
13216 PQExpBuffer labelq = createPQExpBuffer();
13218 appendPQExpBuffer(labelq, "CONSTRAINT %s ",
13219 fmtId(coninfo->dobj.name));
13220 appendPQExpBuffer(labelq, "ON %s",
13221 fmtId(tbinfo->dobj.name));
13222 dumpComment(fout, labelq->data,
13223 tbinfo->dobj.namespace->dobj.name,
13225 coninfo->dobj.catId, 0,
13226 coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
13228 destroyPQExpBuffer(labelq);
13232 * findLastBuiltInOid -
13233 * find the last built in oid
13235 * For 7.1 and 7.2, we do this by retrieving datlastsysoid from the
13236 * pg_database entry for the current database
13239 findLastBuiltinOid_V71(const char *dbname)
13244 PQExpBuffer query = createPQExpBuffer();
13246 resetPQExpBuffer(query);
13247 appendPQExpBuffer(query, "SELECT datlastsysoid from pg_database where datname = ");
13248 appendStringLiteralAH(query, dbname, g_fout);
13250 res = PQexec(g_conn, query->data);
13251 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13253 ntups = PQntuples(res);
13256 write_msg(NULL, "missing pg_database entry for this database\n");
13261 write_msg(NULL, "found more than one pg_database entry for this database\n");
13264 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "datlastsysoid")));
13266 destroyPQExpBuffer(query);
13271 * findLastBuiltInOid -
13272 * find the last built in oid
13274 * For 7.0, we do this by assuming that the last thing that initdb does is to
13275 * create the pg_indexes view. This sucks in general, but seeing that 7.0.x
13276 * initdb won't be changing anymore, it'll do.
13279 findLastBuiltinOid_V70(void)
13285 res = PQexec(g_conn,
13286 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'");
13287 check_sql_result(res, g_conn,
13288 "SELECT oid FROM pg_class WHERE relname = 'pg_indexes'",
13290 ntups = PQntuples(res);
13293 write_msg(NULL, "could not find entry for pg_indexes in pg_class\n");
13298 write_msg(NULL, "found more than one entry for pg_indexes in pg_class\n");
13301 last_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
13307 dumpSequence(Archive *fout, TableInfo *tbinfo)
13320 PQExpBuffer query = createPQExpBuffer();
13321 PQExpBuffer delqry = createPQExpBuffer();
13322 PQExpBuffer labelq = createPQExpBuffer();
13324 /* Make sure we are in proper schema */
13325 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
13327 snprintf(bufm, sizeof(bufm), INT64_FORMAT, SEQ_MINVALUE);
13328 snprintf(bufx, sizeof(bufx), INT64_FORMAT, SEQ_MAXVALUE);
13330 if (g_fout->remoteVersion >= 80400)
13332 appendPQExpBuffer(query,
13333 "SELECT sequence_name, "
13334 "start_value, last_value, increment_by, "
13335 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13336 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13338 "END AS max_value, "
13339 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13340 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13342 "END AS min_value, "
13343 "cache_value, is_cycled, is_called from %s",
13345 fmtId(tbinfo->dobj.name));
13349 appendPQExpBuffer(query,
13350 "SELECT sequence_name, "
13351 "0 AS start_value, last_value, increment_by, "
13352 "CASE WHEN increment_by > 0 AND max_value = %s THEN NULL "
13353 " WHEN increment_by < 0 AND max_value = -1 THEN NULL "
13355 "END AS max_value, "
13356 "CASE WHEN increment_by > 0 AND min_value = 1 THEN NULL "
13357 " WHEN increment_by < 0 AND min_value = %s THEN NULL "
13359 "END AS min_value, "
13360 "cache_value, is_cycled, is_called from %s",
13362 fmtId(tbinfo->dobj.name));
13365 res = PQexec(g_conn, query->data);
13366 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13368 if (PQntuples(res) != 1)
13370 write_msg(NULL, ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)\n",
13371 "query to get data of sequence \"%s\" returned %d rows (expected 1)\n",
13373 tbinfo->dobj.name, PQntuples(res));
13377 /* Disable this check: it fails if sequence has been renamed */
13379 if (strcmp(PQgetvalue(res, 0, 0), tbinfo->dobj.name) != 0)
13381 write_msg(NULL, "query to get data of sequence \"%s\" returned name \"%s\"\n",
13382 tbinfo->dobj.name, PQgetvalue(res, 0, 0));
13387 startv = PQgetvalue(res, 0, 1);
13388 last = PQgetvalue(res, 0, 2);
13389 incby = PQgetvalue(res, 0, 3);
13390 if (!PQgetisnull(res, 0, 4))
13391 maxv = PQgetvalue(res, 0, 4);
13392 if (!PQgetisnull(res, 0, 5))
13393 minv = PQgetvalue(res, 0, 5);
13394 cache = PQgetvalue(res, 0, 6);
13395 cycled = (strcmp(PQgetvalue(res, 0, 7), "t") == 0);
13396 called = (strcmp(PQgetvalue(res, 0, 8), "t") == 0);
13399 * The logic we use for restoring sequences is as follows:
13401 * Add a CREATE SEQUENCE statement as part of a "schema" dump (use
13402 * last_val for start if called is false, else use min_val for start_val).
13403 * Also, if the sequence is owned by a column, add an ALTER SEQUENCE OWNED
13404 * BY command for it.
13406 * Add a 'SETVAL(seq, last_val, iscalled)' as part of a "data" dump.
13411 * DROP must be fully qualified in case same name appears in
13414 appendPQExpBuffer(delqry, "DROP SEQUENCE %s.",
13415 fmtId(tbinfo->dobj.namespace->dobj.name));
13416 appendPQExpBuffer(delqry, "%s;\n",
13417 fmtId(tbinfo->dobj.name));
13419 resetPQExpBuffer(query);
13421 if (binary_upgrade)
13423 binary_upgrade_set_pg_class_oids(query, tbinfo->dobj.catId.oid, false);
13424 binary_upgrade_set_type_oids_by_rel_oid(query, tbinfo->dobj.catId.oid);
13427 appendPQExpBuffer(query,
13428 "CREATE SEQUENCE %s\n",
13429 fmtId(tbinfo->dobj.name));
13431 if (g_fout->remoteVersion >= 80400)
13432 appendPQExpBuffer(query, " START WITH %s\n", startv);
13436 * Versions before 8.4 did not remember the true start value. If
13437 * is_called is false then the sequence has never been incremented
13438 * so we can use last_val. Otherwise punt and let it default.
13441 appendPQExpBuffer(query, " START WITH %s\n", last);
13444 appendPQExpBuffer(query, " INCREMENT BY %s\n", incby);
13447 appendPQExpBuffer(query, " MINVALUE %s\n", minv);
13449 appendPQExpBuffer(query, " NO MINVALUE\n");
13452 appendPQExpBuffer(query, " MAXVALUE %s\n", maxv);
13454 appendPQExpBuffer(query, " NO MAXVALUE\n");
13456 appendPQExpBuffer(query,
13458 cache, (cycled ? "\n CYCLE" : ""));
13460 appendPQExpBuffer(query, ";\n");
13462 appendPQExpBuffer(labelq, "SEQUENCE %s", fmtId(tbinfo->dobj.name));
13464 /* binary_upgrade: no need to clear TOAST table oid */
13466 if (binary_upgrade)
13467 binary_upgrade_extension_member(query, &tbinfo->dobj,
13470 ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
13472 tbinfo->dobj.namespace->dobj.name,
13475 false, "SEQUENCE", SECTION_PRE_DATA,
13476 query->data, delqry->data, NULL,
13477 tbinfo->dobj.dependencies, tbinfo->dobj.nDeps,
13481 * If the sequence is owned by a table column, emit the ALTER for it
13482 * as a separate TOC entry immediately following the sequence's own
13483 * entry. It's OK to do this rather than using full sorting logic,
13484 * because the dependency that tells us it's owned will have forced
13485 * the table to be created first. We can't just include the ALTER in
13486 * the TOC entry because it will fail if we haven't reassigned the
13487 * sequence owner to match the table's owner.
13489 * We need not schema-qualify the table reference because both
13490 * sequence and table must be in the same schema.
13492 if (OidIsValid(tbinfo->owning_tab))
13494 TableInfo *owning_tab = findTableByOid(tbinfo->owning_tab);
13496 if (owning_tab && owning_tab->dobj.dump)
13498 resetPQExpBuffer(query);
13499 appendPQExpBuffer(query, "ALTER SEQUENCE %s",
13500 fmtId(tbinfo->dobj.name));
13501 appendPQExpBuffer(query, " OWNED BY %s",
13502 fmtId(owning_tab->dobj.name));
13503 appendPQExpBuffer(query, ".%s;\n",
13504 fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
13506 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13508 tbinfo->dobj.namespace->dobj.name,
13511 false, "SEQUENCE OWNED BY", SECTION_PRE_DATA,
13512 query->data, "", NULL,
13513 &(tbinfo->dobj.dumpId), 1,
13518 /* Dump Sequence Comments and Security Labels */
13519 dumpComment(fout, labelq->data,
13520 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13521 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13522 dumpSecLabel(fout, labelq->data,
13523 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13524 tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
13529 resetPQExpBuffer(query);
13530 appendPQExpBuffer(query, "SELECT pg_catalog.setval(");
13531 appendStringLiteralAH(query, fmtId(tbinfo->dobj.name), fout);
13532 appendPQExpBuffer(query, ", %s, %s);\n",
13533 last, (called ? "true" : "false"));
13535 ArchiveEntry(fout, nilCatalogId, createDumpId(),
13537 tbinfo->dobj.namespace->dobj.name,
13540 false, "SEQUENCE SET", SECTION_PRE_DATA,
13541 query->data, "", NULL,
13542 &(tbinfo->dobj.dumpId), 1,
13548 destroyPQExpBuffer(query);
13549 destroyPQExpBuffer(delqry);
13550 destroyPQExpBuffer(labelq);
13554 dumpTrigger(Archive *fout, TriggerInfo *tginfo)
13556 TableInfo *tbinfo = tginfo->tgtable;
13558 PQExpBuffer delqry;
13559 PQExpBuffer labelq;
13568 query = createPQExpBuffer();
13569 delqry = createPQExpBuffer();
13570 labelq = createPQExpBuffer();
13573 * DROP must be fully qualified in case same name appears in pg_catalog
13575 appendPQExpBuffer(delqry, "DROP TRIGGER %s ",
13576 fmtId(tginfo->dobj.name));
13577 appendPQExpBuffer(delqry, "ON %s.",
13578 fmtId(tbinfo->dobj.namespace->dobj.name));
13579 appendPQExpBuffer(delqry, "%s;\n",
13580 fmtId(tbinfo->dobj.name));
13584 appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
13588 if (tginfo->tgisconstraint)
13590 appendPQExpBuffer(query, "CREATE CONSTRAINT TRIGGER ");
13591 appendPQExpBufferStr(query, fmtId(tginfo->tgconstrname));
13595 appendPQExpBuffer(query, "CREATE TRIGGER ");
13596 appendPQExpBufferStr(query, fmtId(tginfo->dobj.name));
13598 appendPQExpBuffer(query, "\n ");
13601 if (TRIGGER_FOR_BEFORE(tginfo->tgtype))
13602 appendPQExpBuffer(query, "BEFORE");
13603 else if (TRIGGER_FOR_AFTER(tginfo->tgtype))
13604 appendPQExpBuffer(query, "AFTER");
13605 else if (TRIGGER_FOR_INSTEAD(tginfo->tgtype))
13606 appendPQExpBuffer(query, "INSTEAD OF");
13609 write_msg(NULL, "unexpected tgtype value: %d\n", tginfo->tgtype);
13614 if (TRIGGER_FOR_INSERT(tginfo->tgtype))
13616 appendPQExpBuffer(query, " INSERT");
13619 if (TRIGGER_FOR_DELETE(tginfo->tgtype))
13622 appendPQExpBuffer(query, " OR DELETE");
13624 appendPQExpBuffer(query, " DELETE");
13627 if (TRIGGER_FOR_UPDATE(tginfo->tgtype))
13630 appendPQExpBuffer(query, " OR UPDATE");
13632 appendPQExpBuffer(query, " UPDATE");
13635 if (TRIGGER_FOR_TRUNCATE(tginfo->tgtype))
13638 appendPQExpBuffer(query, " OR TRUNCATE");
13640 appendPQExpBuffer(query, " TRUNCATE");
13643 appendPQExpBuffer(query, " ON %s\n",
13644 fmtId(tbinfo->dobj.name));
13646 if (tginfo->tgisconstraint)
13648 if (OidIsValid(tginfo->tgconstrrelid))
13650 /* If we are using regclass, name is already quoted */
13651 if (g_fout->remoteVersion >= 70300)
13652 appendPQExpBuffer(query, " FROM %s\n ",
13653 tginfo->tgconstrrelname);
13655 appendPQExpBuffer(query, " FROM %s\n ",
13656 fmtId(tginfo->tgconstrrelname));
13658 if (!tginfo->tgdeferrable)
13659 appendPQExpBuffer(query, "NOT ");
13660 appendPQExpBuffer(query, "DEFERRABLE INITIALLY ");
13661 if (tginfo->tginitdeferred)
13662 appendPQExpBuffer(query, "DEFERRED\n");
13664 appendPQExpBuffer(query, "IMMEDIATE\n");
13667 if (TRIGGER_FOR_ROW(tginfo->tgtype))
13668 appendPQExpBuffer(query, " FOR EACH ROW\n ");
13670 appendPQExpBuffer(query, " FOR EACH STATEMENT\n ");
13672 /* In 7.3, result of regproc is already quoted */
13673 if (g_fout->remoteVersion >= 70300)
13674 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13677 appendPQExpBuffer(query, "EXECUTE PROCEDURE %s(",
13678 fmtId(tginfo->tgfname));
13680 tgargs = (char *) PQunescapeBytea((unsigned char *) tginfo->tgargs,
13683 for (findx = 0; findx < tginfo->tgnargs; findx++)
13685 /* find the embedded null that terminates this trigger argument */
13686 size_t tlen = strlen(p);
13688 if (p + tlen >= tgargs + lentgargs)
13690 /* hm, not found before end of bytea value... */
13691 write_msg(NULL, "invalid argument string (%s) for trigger \"%s\" on table \"%s\"\n",
13694 tbinfo->dobj.name);
13699 appendPQExpBuffer(query, ", ");
13700 appendStringLiteralAH(query, p, fout);
13704 appendPQExpBuffer(query, ");\n");
13707 if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
13709 appendPQExpBuffer(query, "\nALTER TABLE %s ",
13710 fmtId(tbinfo->dobj.name));
13711 switch (tginfo->tgenabled)
13715 appendPQExpBuffer(query, "DISABLE");
13718 appendPQExpBuffer(query, "ENABLE ALWAYS");
13721 appendPQExpBuffer(query, "ENABLE REPLICA");
13724 appendPQExpBuffer(query, "ENABLE");
13727 appendPQExpBuffer(query, " TRIGGER %s;\n",
13728 fmtId(tginfo->dobj.name));
13731 appendPQExpBuffer(labelq, "TRIGGER %s ",
13732 fmtId(tginfo->dobj.name));
13733 appendPQExpBuffer(labelq, "ON %s",
13734 fmtId(tbinfo->dobj.name));
13736 ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
13738 tbinfo->dobj.namespace->dobj.name,
13740 tbinfo->rolname, false,
13741 "TRIGGER", SECTION_POST_DATA,
13742 query->data, delqry->data, NULL,
13743 tginfo->dobj.dependencies, tginfo->dobj.nDeps,
13746 dumpComment(fout, labelq->data,
13747 tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
13748 tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
13750 destroyPQExpBuffer(query);
13751 destroyPQExpBuffer(delqry);
13752 destroyPQExpBuffer(labelq);
13760 dumpRule(Archive *fout, RuleInfo *rinfo)
13762 TableInfo *tbinfo = rinfo->ruletable;
13765 PQExpBuffer delcmd;
13766 PQExpBuffer labelq;
13769 /* Skip if not to be dumped */
13770 if (!rinfo->dobj.dump || dataOnly)
13774 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
13775 * we do not want to dump it as a separate object.
13777 if (!rinfo->separate)
13781 * Make sure we are in proper schema.
13783 selectSourceSchema(tbinfo->dobj.namespace->dobj.name);
13785 query = createPQExpBuffer();
13786 cmd = createPQExpBuffer();
13787 delcmd = createPQExpBuffer();
13788 labelq = createPQExpBuffer();
13790 if (g_fout->remoteVersion >= 70300)
13792 appendPQExpBuffer(query,
13793 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid) AS definition",
13794 rinfo->dobj.catId.oid);
13798 /* Rule name was unique before 7.3 ... */
13799 appendPQExpBuffer(query,
13800 "SELECT pg_get_ruledef('%s') AS definition",
13804 res = PQexec(g_conn, query->data);
13805 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13807 if (PQntuples(res) != 1)
13809 write_msg(NULL, "query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned\n",
13810 rinfo->dobj.name, tbinfo->dobj.name);
13814 printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
13817 * Add the command to alter the rules replication firing semantics if it
13818 * differs from the default.
13820 if (rinfo->ev_enabled != 'O')
13822 appendPQExpBuffer(cmd, "ALTER TABLE %s.",
13823 fmtId(tbinfo->dobj.namespace->dobj.name));
13824 appendPQExpBuffer(cmd, "%s ",
13825 fmtId(tbinfo->dobj.name));
13826 switch (rinfo->ev_enabled)
13829 appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
13830 fmtId(rinfo->dobj.name));
13833 appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
13834 fmtId(rinfo->dobj.name));
13837 appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
13838 fmtId(rinfo->dobj.name));
13844 * DROP must be fully qualified in case same name appears in pg_catalog
13846 appendPQExpBuffer(delcmd, "DROP RULE %s ",
13847 fmtId(rinfo->dobj.name));
13848 appendPQExpBuffer(delcmd, "ON %s.",
13849 fmtId(tbinfo->dobj.namespace->dobj.name));
13850 appendPQExpBuffer(delcmd, "%s;\n",
13851 fmtId(tbinfo->dobj.name));
13853 appendPQExpBuffer(labelq, "RULE %s",
13854 fmtId(rinfo->dobj.name));
13855 appendPQExpBuffer(labelq, " ON %s",
13856 fmtId(tbinfo->dobj.name));
13858 ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
13860 tbinfo->dobj.namespace->dobj.name,
13862 tbinfo->rolname, false,
13863 "RULE", SECTION_POST_DATA,
13864 cmd->data, delcmd->data, NULL,
13865 rinfo->dobj.dependencies, rinfo->dobj.nDeps,
13868 /* Dump rule comments */
13869 dumpComment(fout, labelq->data,
13870 tbinfo->dobj.namespace->dobj.name,
13872 rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
13876 destroyPQExpBuffer(query);
13877 destroyPQExpBuffer(cmd);
13878 destroyPQExpBuffer(delcmd);
13879 destroyPQExpBuffer(labelq);
13883 * getExtensionMembership --- obtain extension membership data
13886 getExtensionMembership(ExtensionInfo extinfo[], int numExtensions)
13896 DumpableObject *dobj,
13899 /* Nothing to do if no extensions */
13900 if (numExtensions == 0)
13903 /* Make sure we are in proper schema */
13904 selectSourceSchema("pg_catalog");
13906 query = createPQExpBuffer();
13908 /* refclassid constraint is redundant but may speed the search */
13909 appendPQExpBuffer(query, "SELECT "
13910 "classid, objid, refclassid, refobjid "
13912 "WHERE refclassid = 'pg_extension'::regclass "
13913 "AND deptype = 'e' "
13916 res = PQexec(g_conn, query->data);
13917 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
13919 ntups = PQntuples(res);
13921 i_classid = PQfnumber(res, "classid");
13922 i_objid = PQfnumber(res, "objid");
13923 i_refclassid = PQfnumber(res, "refclassid");
13924 i_refobjid = PQfnumber(res, "refobjid");
13927 * Since we ordered the SELECT by referenced ID, we can expect that
13928 * multiple entries for the same extension will appear together; this
13929 * saves on searches.
13933 for (i = 0; i < ntups; i++)
13936 CatalogId refobjId;
13938 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
13939 objId.oid = atooid(PQgetvalue(res, i, i_objid));
13940 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
13941 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
13943 if (refdobj == NULL ||
13944 refdobj->catId.tableoid != refobjId.tableoid ||
13945 refdobj->catId.oid != refobjId.oid)
13946 refdobj = findObjectByCatalogId(refobjId);
13949 * Failure to find objects mentioned in pg_depend is not unexpected,
13950 * since for example we don't collect info about TOAST tables.
13952 if (refdobj == NULL)
13955 fprintf(stderr, "no referenced object %u %u\n",
13956 refobjId.tableoid, refobjId.oid);
13961 dobj = findObjectByCatalogId(objId);
13966 fprintf(stderr, "no referencing object %u %u\n",
13967 objId.tableoid, objId.oid);
13972 /* Record dependency so that getDependencies needn't repeat this */
13973 addObjectDependency(dobj, refdobj->dumpId);
13975 dobj->ext_member = true;
13978 * Normally, mark the member object as not to be dumped. But in
13979 * binary upgrades, we still dump the members individually, since the
13980 * idea is to exactly reproduce the database contents rather than
13981 * replace the extension contents with something different.
13983 if (!binary_upgrade)
13984 dobj->dump = false;
13986 dobj->dump = refdobj->dump;
13992 * Now identify extension configuration tables and create TableDataInfo
13993 * objects for them, ensuring their data will be dumped even though the
13994 * tables themselves won't be.
13996 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
13997 * user data in a configuration table is treated like schema data. This
13998 * seems appropriate since system data in a config table would get
13999 * reloaded by CREATE EXTENSION.
14001 for (i = 0; i < numExtensions; i++)
14003 char *extconfig = extinfo[i].extconfig;
14004 char *extcondition = extinfo[i].extcondition;
14005 char **extconfigarray = NULL;
14006 char **extconditionarray = NULL;
14008 int nconditionitems;
14010 if (parsePGArray(extconfig, &extconfigarray, &nconfigitems) &&
14011 parsePGArray(extcondition, &extconditionarray, &nconditionitems) &&
14012 nconfigitems == nconditionitems)
14016 for (j = 0; j < nconfigitems; j++)
14018 TableInfo *configtbl;
14020 configtbl = findTableByOid(atooid(extconfigarray[j]));
14021 if (configtbl && configtbl->dataObj == NULL)
14024 * Note: config tables are dumped without OIDs regardless
14025 * of the --oids setting. This is because row filtering
14026 * conditions aren't compatible with dumping OIDs.
14028 makeTableDataInfo(configtbl, false);
14029 if (strlen(extconditionarray[j]) > 0)
14030 configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
14034 if (extconfigarray)
14035 free(extconfigarray);
14036 if (extconditionarray)
14037 free(extconditionarray);
14040 destroyPQExpBuffer(query);
14044 * getDependencies --- obtain available dependency data
14047 getDependencies(void)
14058 DumpableObject *dobj,
14061 /* No dependency info available before 7.3 */
14062 if (g_fout->remoteVersion < 70300)
14066 write_msg(NULL, "reading dependency data\n");
14068 /* Make sure we are in proper schema */
14069 selectSourceSchema("pg_catalog");
14071 query = createPQExpBuffer();
14074 * PIN dependencies aren't interesting, and EXTENSION dependencies were
14075 * already processed by getExtensionMembership.
14077 appendPQExpBuffer(query, "SELECT "
14078 "classid, objid, refclassid, refobjid, deptype "
14080 "WHERE deptype != 'p' AND deptype != 'e' "
14083 res = PQexec(g_conn, query->data);
14084 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
14086 ntups = PQntuples(res);
14088 i_classid = PQfnumber(res, "classid");
14089 i_objid = PQfnumber(res, "objid");
14090 i_refclassid = PQfnumber(res, "refclassid");
14091 i_refobjid = PQfnumber(res, "refobjid");
14092 i_deptype = PQfnumber(res, "deptype");
14095 * Since we ordered the SELECT by referencing ID, we can expect that
14096 * multiple entries for the same object will appear together; this saves
14101 for (i = 0; i < ntups; i++)
14104 CatalogId refobjId;
14107 objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
14108 objId.oid = atooid(PQgetvalue(res, i, i_objid));
14109 refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
14110 refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
14111 deptype = *(PQgetvalue(res, i, i_deptype));
14113 if (dobj == NULL ||
14114 dobj->catId.tableoid != objId.tableoid ||
14115 dobj->catId.oid != objId.oid)
14116 dobj = findObjectByCatalogId(objId);
14119 * Failure to find objects mentioned in pg_depend is not unexpected,
14120 * since for example we don't collect info about TOAST tables.
14125 fprintf(stderr, "no referencing object %u %u\n",
14126 objId.tableoid, objId.oid);
14131 refdobj = findObjectByCatalogId(refobjId);
14133 if (refdobj == NULL)
14136 fprintf(stderr, "no referenced object %u %u\n",
14137 refobjId.tableoid, refobjId.oid);
14143 * Ordinarily, table rowtypes have implicit dependencies on their
14144 * tables. However, for a composite type the implicit dependency goes
14145 * the other way in pg_depend; which is the right thing for DROP but
14146 * it doesn't produce the dependency ordering we need. So in that one
14147 * case, we reverse the direction of the dependency.
14149 if (deptype == 'i' &&
14150 dobj->objType == DO_TABLE &&
14151 refdobj->objType == DO_TYPE)
14152 addObjectDependency(refdobj, dobj->dumpId);
14155 addObjectDependency(dobj, refdobj->dumpId);
14160 destroyPQExpBuffer(query);
14165 * selectSourceSchema - make the specified schema the active search path
14166 * in the source database.
14168 * NB: pg_catalog is explicitly searched after the specified schema;
14169 * so user names are only qualified if they are cross-schema references,
14170 * and system names are only qualified if they conflict with a user name
14171 * in the current schema.
14173 * Whenever the selected schema is not pg_catalog, be careful to qualify
14174 * references to system catalogs and types in our emitted commands!
14177 selectSourceSchema(const char *schemaName)
14179 static char *curSchemaName = NULL;
14182 /* Not relevant if fetching from pre-7.3 DB */
14183 if (g_fout->remoteVersion < 70300)
14185 /* Ignore null schema names */
14186 if (schemaName == NULL || *schemaName == '\0')
14188 /* Optimize away repeated selection of same schema */
14189 if (curSchemaName && strcmp(curSchemaName, schemaName) == 0)
14192 query = createPQExpBuffer();
14193 appendPQExpBuffer(query, "SET search_path = %s",
14194 fmtId(schemaName));
14195 if (strcmp(schemaName, "pg_catalog") != 0)
14196 appendPQExpBuffer(query, ", pg_catalog");
14198 do_sql_command(g_conn, query->data);
14200 destroyPQExpBuffer(query);
14202 free(curSchemaName);
14203 curSchemaName = pg_strdup(schemaName);
14207 * getFormattedTypeName - retrieve a nicely-formatted type name for the
14210 * NB: in 7.3 and up the result may depend on the currently-selected
14211 * schema; this is why we don't try to cache the names.
14214 getFormattedTypeName(Oid oid, OidOptions opts)
14223 if ((opts & zeroAsOpaque) != 0)
14224 return pg_strdup(g_opaque_type);
14225 else if ((opts & zeroAsAny) != 0)
14226 return pg_strdup("'any'");
14227 else if ((opts & zeroAsStar) != 0)
14228 return pg_strdup("*");
14229 else if ((opts & zeroAsNone) != 0)
14230 return pg_strdup("NONE");
14233 query = createPQExpBuffer();
14234 if (g_fout->remoteVersion >= 70300)
14236 appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
14239 else if (g_fout->remoteVersion >= 70100)
14241 appendPQExpBuffer(query, "SELECT format_type('%u'::oid, NULL)",
14246 appendPQExpBuffer(query, "SELECT typname "
14248 "WHERE oid = '%u'::oid",
14252 res = PQexec(g_conn, query->data);
14253 check_sql_result(res, g_conn, query->data, PGRES_TUPLES_OK);
14255 /* Expecting a single result only */
14256 ntups = PQntuples(res);
14259 write_msg(NULL, ngettext("query returned %d row instead of one: %s\n",
14260 "query returned %d rows instead of one: %s\n",
14262 ntups, query->data);
14266 if (g_fout->remoteVersion >= 70100)
14268 /* already quoted */
14269 result = pg_strdup(PQgetvalue(res, 0, 0));
14273 /* may need to quote it */
14274 result = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
14278 destroyPQExpBuffer(query);
14284 * myFormatType --- local implementation of format_type for use with 7.0.
14287 myFormatType(const char *typname, int32 typmod)
14290 bool isarray = false;
14291 PQExpBuffer buf = createPQExpBuffer();
14293 /* Handle array types */
14294 if (typname[0] == '_')
14300 /* Show lengths on bpchar and varchar */
14301 if (!strcmp(typname, "bpchar"))
14303 int len = (typmod - VARHDRSZ);
14305 appendPQExpBuffer(buf, "character");
14307 appendPQExpBuffer(buf, "(%d)",
14308 typmod - VARHDRSZ);
14310 else if (!strcmp(typname, "varchar"))
14312 appendPQExpBuffer(buf, "character varying");
14314 appendPQExpBuffer(buf, "(%d)",
14315 typmod - VARHDRSZ);
14317 else if (!strcmp(typname, "numeric"))
14319 appendPQExpBuffer(buf, "numeric");
14326 tmp_typmod = typmod - VARHDRSZ;
14327 precision = (tmp_typmod >> 16) & 0xffff;
14328 scale = tmp_typmod & 0xffff;
14329 appendPQExpBuffer(buf, "(%d,%d)",
14335 * char is an internal single-byte data type; Let's make sure we force it
14336 * through with quotes. - thomas 1998-12-13
14338 else if (strcmp(typname, "char") == 0)
14339 appendPQExpBuffer(buf, "\"char\"");
14341 appendPQExpBuffer(buf, "%s", fmtId(typname));
14343 /* Append array qualifier for array types */
14345 appendPQExpBuffer(buf, "[]");
14347 result = pg_strdup(buf->data);
14348 destroyPQExpBuffer(buf);
14354 * fmtQualifiedId - convert a qualified name to the proper format for
14355 * the source database.
14357 * Like fmtId, use the result before calling again.
14359 static const char *
14360 fmtQualifiedId(const char *schema, const char *id)
14362 static PQExpBuffer id_return = NULL;
14364 if (id_return) /* first time through? */
14365 resetPQExpBuffer(id_return);
14367 id_return = createPQExpBuffer();
14369 /* Suppress schema name if fetching from pre-7.3 DB */
14370 if (g_fout->remoteVersion >= 70300 && schema && *schema)
14372 appendPQExpBuffer(id_return, "%s.",
14375 appendPQExpBuffer(id_return, "%s",
14378 return id_return->data;
14382 * Return a column list clause for the given relation.
14384 * Special case: if there are no undropped columns in the relation, return
14385 * "", not an invalid "()" column list.
14387 static const char *
14388 fmtCopyColumnList(const TableInfo *ti)
14390 static PQExpBuffer q = NULL;
14391 int numatts = ti->numatts;
14392 char **attnames = ti->attnames;
14393 bool *attisdropped = ti->attisdropped;
14397 if (q) /* first time through? */
14398 resetPQExpBuffer(q);
14400 q = createPQExpBuffer();
14402 appendPQExpBuffer(q, "(");
14404 for (i = 0; i < numatts; i++)
14406 if (attisdropped[i])
14409 appendPQExpBuffer(q, ", ");
14410 appendPQExpBuffer(q, "%s", fmtId(attnames[i]));
14415 return ""; /* no undropped columns */
14417 appendPQExpBuffer(q, ")");
14422 * Convenience subroutine to execute a SQL command and check for
14423 * COMMAND_OK status.
14426 do_sql_command(PGconn *conn, const char *query)
14430 res = PQexec(conn, query);
14431 check_sql_result(res, conn, query, PGRES_COMMAND_OK);
14436 * Convenience subroutine to verify a SQL command succeeded,
14437 * and exit with a useful error message if not.
14440 check_sql_result(PGresult *res, PGconn *conn, const char *query,
14441 ExecStatusType expected)
14445 if (res && PQresultStatus(res) == expected)
14448 write_msg(NULL, "SQL command failed\n");
14450 err = PQresultErrorMessage(res);
14452 err = PQerrorMessage(conn);
14453 write_msg(NULL, "Error message from server: %s", err);
14454 write_msg(NULL, "The command was: %s\n", query);