1 /*-------------------------------------------------------------------------
4 * pg_dump is a utility for dumping out a postgres database
7 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
10 * pg_dump will read the system catalogs in a database and dump out a
11 * script that reproduces the schema in terms of SQL that is understood
14 * Note that pg_dump runs in a transaction-snapshot mode transaction,
15 * so it sees a consistent snapshot of the database including system
16 * catalogs. However, it relies in part on various specialized backend
17 * functions like pg_get_indexdef(), and those things tend to look at
18 * the currently committed state. So it is possible to get 'cache
19 * lookup failed' error if someone performs DDL changes while a dump is
20 * happening. The window for this sort of thing is from the acquisition
21 * of the transaction snapshot to getSchemaData() (when pg_dump acquires
22 * AccessShareLock on every table it intends to dump). It isn't very large,
25 * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
28 * src/bin/pg_dump/pg_dump.c
30 *-------------------------------------------------------------------------
32 #include "postgres_fe.h"
41 #include "getopt_long.h"
43 #include "access/attnum.h"
44 #include "access/sysattr.h"
45 #include "access/transam.h"
46 #include "catalog/pg_aggregate_d.h"
47 #include "catalog/pg_am_d.h"
48 #include "catalog/pg_attribute_d.h"
49 #include "catalog/pg_cast_d.h"
50 #include "catalog/pg_class_d.h"
51 #include "catalog/pg_default_acl_d.h"
52 #include "catalog/pg_largeobject_d.h"
53 #include "catalog/pg_largeobject_metadata_d.h"
54 #include "catalog/pg_proc_d.h"
55 #include "catalog/pg_trigger_d.h"
56 #include "catalog/pg_type_d.h"
57 #include "libpq/libpq-fs.h"
58 #include "storage/block.h"
60 #include "dumputils.h"
62 #include "pg_backup_db.h"
63 #include "pg_backup_utils.h"
65 #include "fe_utils/connect.h"
66 #include "fe_utils/string_utils.h"
71 const char *descr
; /* comment for an object */
72 Oid classoid
; /* object class (catalog OID) */
73 Oid objoid
; /* object OID */
74 int objsubid
; /* subobject (table column #) */
79 const char *provider
; /* label provider of this security label */
80 const char *label
; /* security label for an object */
81 Oid classoid
; /* object class (catalog OID) */
82 Oid objoid
; /* object OID */
83 int objsubid
; /* subobject (table column #) */
86 typedef enum OidOptions
95 static bool dosync
= true; /* Issue fsync() to make dump durable on disk. */
97 /* subquery used to convert user ID (eg, datdba) to user name */
98 static const char *username_subquery
;
101 * For 8.0 and earlier servers, pulled from pg_database, for 8.1+ we use
102 * FirstNormalObjectId - 1.
104 static Oid g_last_builtin_oid
; /* value of the last builtin oid */
106 /* The specified names/patterns should to match at least one entity */
107 static int strict_names
= 0;
110 * Object inclusion/exclusion lists
112 * The string lists record the patterns given by command-line switches,
113 * which we then convert to lists of OIDs of matching objects.
115 static SimpleStringList schema_include_patterns
= {NULL
, NULL
};
116 static SimpleOidList schema_include_oids
= {NULL
, NULL
};
117 static SimpleStringList schema_exclude_patterns
= {NULL
, NULL
};
118 static SimpleOidList schema_exclude_oids
= {NULL
, NULL
};
120 static SimpleStringList table_include_patterns
= {NULL
, NULL
};
121 static SimpleOidList table_include_oids
= {NULL
, NULL
};
122 static SimpleStringList table_exclude_patterns
= {NULL
, NULL
};
123 static SimpleOidList table_exclude_oids
= {NULL
, NULL
};
124 static SimpleStringList tabledata_exclude_patterns
= {NULL
, NULL
};
125 static SimpleOidList tabledata_exclude_oids
= {NULL
, NULL
};
128 char g_opaque_type
[10]; /* name for the opaque type */
130 /* placeholders for the delimiters for comments */
131 char g_comment_start
[10];
132 char g_comment_end
[10];
134 static const CatalogId nilCatalogId
= {0, 0};
136 /* override for standard extra_float_digits setting */
137 static bool have_extra_float_digits
= false;
138 static int extra_float_digits
;
141 * The default number of rows per INSERT when
142 * --inserts is specified without --rows-per-insert
144 #define DUMP_DEFAULT_ROWS_PER_INSERT 1
147 * Macro for producing quoted, schema-qualified name of a dumpable object.
149 #define fmtQualifiedDumpable(obj) \
150 fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
153 static void help(const char *progname
);
154 static void setup_connection(Archive
*AH
,
155 const char *dumpencoding
, const char *dumpsnapshot
,
157 static ArchiveFormat
parseArchiveFormat(const char *format
, ArchiveMode
*mode
);
158 static void expand_schema_name_patterns(Archive
*fout
,
159 SimpleStringList
*patterns
,
162 static void expand_table_name_patterns(Archive
*fout
,
163 SimpleStringList
*patterns
,
166 static NamespaceInfo
*findNamespace(Archive
*fout
, Oid nsoid
);
167 static void dumpTableData(Archive
*fout
, TableDataInfo
*tdinfo
);
168 static void refreshMatViewData(Archive
*fout
, TableDataInfo
*tdinfo
);
169 static void guessConstraintInheritance(TableInfo
*tblinfo
, int numTables
);
170 static void dumpComment(Archive
*fout
, const char *type
, const char *name
,
171 const char *namespace, const char *owner
,
172 CatalogId catalogId
, int subid
, DumpId dumpId
);
173 static int findComments(Archive
*fout
, Oid classoid
, Oid objoid
,
174 CommentItem
**items
);
175 static int collectComments(Archive
*fout
, CommentItem
**items
);
176 static void dumpSecLabel(Archive
*fout
, const char *type
, const char *name
,
177 const char *namespace, const char *owner
,
178 CatalogId catalogId
, int subid
, DumpId dumpId
);
179 static int findSecLabels(Archive
*fout
, Oid classoid
, Oid objoid
,
180 SecLabelItem
**items
);
181 static int collectSecLabels(Archive
*fout
, SecLabelItem
**items
);
182 static void dumpDumpableObject(Archive
*fout
, DumpableObject
*dobj
);
183 static void dumpNamespace(Archive
*fout
, NamespaceInfo
*nspinfo
);
184 static void dumpExtension(Archive
*fout
, ExtensionInfo
*extinfo
);
185 static void dumpType(Archive
*fout
, TypeInfo
*tyinfo
);
186 static void dumpBaseType(Archive
*fout
, TypeInfo
*tyinfo
);
187 static void dumpEnumType(Archive
*fout
, TypeInfo
*tyinfo
);
188 static void dumpRangeType(Archive
*fout
, TypeInfo
*tyinfo
);
189 static void dumpUndefinedType(Archive
*fout
, TypeInfo
*tyinfo
);
190 static void dumpDomain(Archive
*fout
, TypeInfo
*tyinfo
);
191 static void dumpCompositeType(Archive
*fout
, TypeInfo
*tyinfo
);
192 static void dumpCompositeTypeColComments(Archive
*fout
, TypeInfo
*tyinfo
);
193 static void dumpShellType(Archive
*fout
, ShellTypeInfo
*stinfo
);
194 static void dumpProcLang(Archive
*fout
, ProcLangInfo
*plang
);
195 static void dumpFunc(Archive
*fout
, FuncInfo
*finfo
);
196 static void dumpCast(Archive
*fout
, CastInfo
*cast
);
197 static void dumpTransform(Archive
*fout
, TransformInfo
*transform
);
198 static void dumpOpr(Archive
*fout
, OprInfo
*oprinfo
);
199 static void dumpAccessMethod(Archive
*fout
, AccessMethodInfo
*oprinfo
);
200 static void dumpOpclass(Archive
*fout
, OpclassInfo
*opcinfo
);
201 static void dumpOpfamily(Archive
*fout
, OpfamilyInfo
*opfinfo
);
202 static void dumpCollation(Archive
*fout
, CollInfo
*collinfo
);
203 static void dumpConversion(Archive
*fout
, ConvInfo
*convinfo
);
204 static void dumpRule(Archive
*fout
, RuleInfo
*rinfo
);
205 static void dumpAgg(Archive
*fout
, AggInfo
*agginfo
);
206 static void dumpTrigger(Archive
*fout
, TriggerInfo
*tginfo
);
207 static void dumpEventTrigger(Archive
*fout
, EventTriggerInfo
*evtinfo
);
208 static void dumpTable(Archive
*fout
, TableInfo
*tbinfo
);
209 static void dumpTableSchema(Archive
*fout
, TableInfo
*tbinfo
);
210 static void dumpAttrDef(Archive
*fout
, AttrDefInfo
*adinfo
);
211 static void dumpSequence(Archive
*fout
, TableInfo
*tbinfo
);
212 static void dumpSequenceData(Archive
*fout
, TableDataInfo
*tdinfo
);
213 static void dumpIndex(Archive
*fout
, IndxInfo
*indxinfo
);
214 static void dumpIndexAttach(Archive
*fout
, IndexAttachInfo
*attachinfo
);
215 static void dumpStatisticsExt(Archive
*fout
, StatsExtInfo
*statsextinfo
);
216 static void dumpConstraint(Archive
*fout
, ConstraintInfo
*coninfo
);
217 static void dumpTableConstraintComment(Archive
*fout
, ConstraintInfo
*coninfo
);
218 static void dumpTSParser(Archive
*fout
, TSParserInfo
*prsinfo
);
219 static void dumpTSDictionary(Archive
*fout
, TSDictInfo
*dictinfo
);
220 static void dumpTSTemplate(Archive
*fout
, TSTemplateInfo
*tmplinfo
);
221 static void dumpTSConfig(Archive
*fout
, TSConfigInfo
*cfginfo
);
222 static void dumpForeignDataWrapper(Archive
*fout
, FdwInfo
*fdwinfo
);
223 static void dumpForeignServer(Archive
*fout
, ForeignServerInfo
*srvinfo
);
224 static void dumpUserMappings(Archive
*fout
,
225 const char *servername
, const char *namespace,
226 const char *owner
, CatalogId catalogId
, DumpId dumpId
);
227 static void dumpDefaultACL(Archive
*fout
, DefaultACLInfo
*daclinfo
);
229 static DumpId
dumpACL(Archive
*fout
, DumpId objDumpId
, DumpId altDumpId
,
230 const char *type
, const char *name
, const char *subname
,
231 const char *nspname
, const char *owner
,
232 const char *acls
, const char *racls
,
233 const char *initacls
, const char *initracls
);
235 static void getDependencies(Archive
*fout
);
236 static void BuildArchiveDependencies(Archive
*fout
);
237 static void findDumpableDependencies(ArchiveHandle
*AH
, DumpableObject
*dobj
,
238 DumpId
**dependencies
, int *nDeps
, int *allocDeps
);
240 static DumpableObject
*createBoundaryObjects(void);
241 static void addBoundaryDependencies(DumpableObject
**dobjs
, int numObjs
,
242 DumpableObject
*boundaryObjs
);
244 static void addConstrChildIdxDeps(DumpableObject
*dobj
, IndxInfo
*refidx
);
245 static void getDomainConstraints(Archive
*fout
, TypeInfo
*tyinfo
);
246 static void getTableData(DumpOptions
*dopt
, TableInfo
*tblinfo
, int numTables
, char relkind
);
247 static void makeTableDataInfo(DumpOptions
*dopt
, TableInfo
*tbinfo
);
248 static void buildMatViewRefreshDependencies(Archive
*fout
);
249 static void getTableDataFKConstraints(void);
250 static char *format_function_arguments(FuncInfo
*finfo
, char *funcargs
,
252 static char *format_function_arguments_old(Archive
*fout
,
253 FuncInfo
*finfo
, int nallargs
,
257 static char *format_function_signature(Archive
*fout
,
258 FuncInfo
*finfo
, bool honor_quotes
);
259 static char *convertRegProcReference(Archive
*fout
,
261 static char *getFormattedOperatorName(Archive
*fout
, const char *oproid
);
262 static char *convertTSFunction(Archive
*fout
, Oid funcOid
);
263 static Oid
findLastBuiltinOid_V71(Archive
*fout
);
264 static const char *getFormattedTypeName(Archive
*fout
, Oid oid
, OidOptions opts
);
265 static void getBlobs(Archive
*fout
);
266 static void dumpBlob(Archive
*fout
, BlobInfo
*binfo
);
267 static int dumpBlobs(Archive
*fout
, void *arg
);
268 static void dumpPolicy(Archive
*fout
, PolicyInfo
*polinfo
);
269 static void dumpPublication(Archive
*fout
, PublicationInfo
*pubinfo
);
270 static void dumpPublicationTable(Archive
*fout
, PublicationRelInfo
*pubrinfo
);
271 static void dumpSubscription(Archive
*fout
, SubscriptionInfo
*subinfo
);
272 static void dumpDatabase(Archive
*AH
);
273 static void dumpDatabaseConfig(Archive
*AH
, PQExpBuffer outbuf
,
274 const char *dbname
, Oid dboid
);
275 static void dumpEncoding(Archive
*AH
);
276 static void dumpStdStrings(Archive
*AH
);
277 static void dumpSearchPath(Archive
*AH
);
278 static void binary_upgrade_set_type_oids_by_type_oid(Archive
*fout
,
279 PQExpBuffer upgrade_buffer
,
281 bool force_array_type
);
282 static bool binary_upgrade_set_type_oids_by_rel_oid(Archive
*fout
,
283 PQExpBuffer upgrade_buffer
, Oid pg_rel_oid
);
284 static void binary_upgrade_set_pg_class_oids(Archive
*fout
,
285 PQExpBuffer upgrade_buffer
,
286 Oid pg_class_oid
, bool is_index
);
287 static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer
,
288 DumpableObject
*dobj
,
291 const char *objnamespace
);
292 static const char *getAttrName(int attrnum
, TableInfo
*tblInfo
);
293 static const char *fmtCopyColumnList(const TableInfo
*ti
, PQExpBuffer buffer
);
294 static bool nonemptyReloptions(const char *reloptions
);
295 static void appendReloptionsArrayAH(PQExpBuffer buffer
, const char *reloptions
,
296 const char *prefix
, Archive
*fout
);
297 static char *get_synchronized_snapshot(Archive
*fout
);
298 static void setupDumpWorker(Archive
*AHX
);
299 static TableInfo
*getRootTableInfo(TableInfo
*tbinfo
);
300 static bool forcePartitionRootLoad(const TableInfo
*tbinfo
);
304 main(int argc
, char **argv
)
307 const char *filename
= NULL
;
308 const char *format
= "p";
311 DumpableObject
**dobjs
;
313 DumpableObject
*boundaryObjs
;
317 RestoreOptions
*ropt
;
318 Archive
*fout
; /* the script file */
319 bool g_verbose
= false;
320 const char *dumpencoding
= NULL
;
321 const char *dumpsnapshot
= NULL
;
322 char *use_role
= NULL
;
325 int compressLevel
= -1;
327 ArchiveFormat archiveFormat
= archUnknown
;
328 ArchiveMode archiveMode
;
330 static DumpOptions dopt
;
332 static struct option long_options
[] = {
333 {"data-only", no_argument
, NULL
, 'a'},
334 {"blobs", no_argument
, NULL
, 'b'},
335 {"no-blobs", no_argument
, NULL
, 'B'},
336 {"clean", no_argument
, NULL
, 'c'},
337 {"create", no_argument
, NULL
, 'C'},
338 {"dbname", required_argument
, NULL
, 'd'},
339 {"file", required_argument
, NULL
, 'f'},
340 {"format", required_argument
, NULL
, 'F'},
341 {"host", required_argument
, NULL
, 'h'},
342 {"jobs", 1, NULL
, 'j'},
343 {"no-reconnect", no_argument
, NULL
, 'R'},
344 {"no-owner", no_argument
, NULL
, 'O'},
345 {"port", required_argument
, NULL
, 'p'},
346 {"schema", required_argument
, NULL
, 'n'},
347 {"exclude-schema", required_argument
, NULL
, 'N'},
348 {"schema-only", no_argument
, NULL
, 's'},
349 {"superuser", required_argument
, NULL
, 'S'},
350 {"table", required_argument
, NULL
, 't'},
351 {"exclude-table", required_argument
, NULL
, 'T'},
352 {"no-password", no_argument
, NULL
, 'w'},
353 {"password", no_argument
, NULL
, 'W'},
354 {"username", required_argument
, NULL
, 'U'},
355 {"verbose", no_argument
, NULL
, 'v'},
356 {"no-privileges", no_argument
, NULL
, 'x'},
357 {"no-acl", no_argument
, NULL
, 'x'},
358 {"compress", required_argument
, NULL
, 'Z'},
359 {"encoding", required_argument
, NULL
, 'E'},
360 {"help", no_argument
, NULL
, '?'},
361 {"version", no_argument
, NULL
, 'V'},
364 * the following options don't have an equivalent short option letter
366 {"attribute-inserts", no_argument
, &dopt
.column_inserts
, 1},
367 {"binary-upgrade", no_argument
, &dopt
.binary_upgrade
, 1},
368 {"column-inserts", no_argument
, &dopt
.column_inserts
, 1},
369 {"disable-dollar-quoting", no_argument
, &dopt
.disable_dollar_quoting
, 1},
370 {"disable-triggers", no_argument
, &dopt
.disable_triggers
, 1},
371 {"enable-row-security", no_argument
, &dopt
.enable_row_security
, 1},
372 {"exclude-table-data", required_argument
, NULL
, 4},
373 {"extra-float-digits", required_argument
, NULL
, 8},
374 {"if-exists", no_argument
, &dopt
.if_exists
, 1},
375 {"inserts", no_argument
, NULL
, 9},
376 {"lock-wait-timeout", required_argument
, NULL
, 2},
377 {"no-tablespaces", no_argument
, &dopt
.outputNoTablespaces
, 1},
378 {"quote-all-identifiers", no_argument
, "e_all_identifiers
, 1},
379 {"load-via-partition-root", no_argument
, &dopt
.load_via_partition_root
, 1},
380 {"role", required_argument
, NULL
, 3},
381 {"section", required_argument
, NULL
, 5},
382 {"serializable-deferrable", no_argument
, &dopt
.serializable_deferrable
, 1},
383 {"snapshot", required_argument
, NULL
, 6},
384 {"strict-names", no_argument
, &strict_names
, 1},
385 {"use-set-session-authorization", no_argument
, &dopt
.use_setsessauth
, 1},
386 {"no-comments", no_argument
, &dopt
.no_comments
, 1},
387 {"no-publications", no_argument
, &dopt
.no_publications
, 1},
388 {"no-security-labels", no_argument
, &dopt
.no_security_labels
, 1},
389 {"no-synchronized-snapshots", no_argument
, &dopt
.no_synchronized_snapshots
, 1},
390 {"no-unlogged-table-data", no_argument
, &dopt
.no_unlogged_table_data
, 1},
391 {"no-subscriptions", no_argument
, &dopt
.no_subscriptions
, 1},
392 {"no-sync", no_argument
, NULL
, 7},
393 {"on-conflict-do-nothing", no_argument
, &dopt
.do_nothing
, 1},
394 {"rows-per-insert", required_argument
, NULL
, 10},
399 pg_logging_init(argv
[0]);
400 pg_logging_set_level(PG_LOG_WARNING
);
401 set_pglocale_pgservice(argv
[0], PG_TEXTDOMAIN("pg_dump"));
404 * Initialize what we need for parallel execution, especially for thread
405 * support on Windows.
407 init_parallel_dump_utils();
409 strcpy(g_comment_start
, "-- ");
410 g_comment_end
[0] = '\0';
411 strcpy(g_opaque_type
, "opaque");
413 progname
= get_progname(argv
[0]);
417 if (strcmp(argv
[1], "--help") == 0 || strcmp(argv
[1], "-?") == 0)
422 if (strcmp(argv
[1], "--version") == 0 || strcmp(argv
[1], "-V") == 0)
424 puts("pg_dump (PostgreSQL) " PG_VERSION
);
429 InitDumpOptions(&dopt
);
431 while ((c
= getopt_long(argc
, argv
, "abBcCd:E:f:F:h:j:n:N:Op:RsS:t:T:U:vwWxZ:",
432 long_options
, &optindex
)) != -1)
436 case 'a': /* Dump data only */
437 dopt
.dataOnly
= true;
440 case 'b': /* Dump blobs */
441 dopt
.outputBlobs
= true;
444 case 'B': /* Don't dump blobs */
445 dopt
.dontOutputBlobs
= true;
448 case 'c': /* clean (i.e., drop) schema prior to create */
449 dopt
.outputClean
= 1;
452 case 'C': /* Create DB */
453 dopt
.outputCreateDB
= 1;
456 case 'd': /* database name */
457 dopt
.cparams
.dbname
= pg_strdup(optarg
);
460 case 'E': /* Dump encoding */
461 dumpencoding
= pg_strdup(optarg
);
465 filename
= pg_strdup(optarg
);
469 format
= pg_strdup(optarg
);
472 case 'h': /* server host */
473 dopt
.cparams
.pghost
= pg_strdup(optarg
);
476 case 'j': /* number of dump jobs */
477 numWorkers
= atoi(optarg
);
480 case 'n': /* include schema(s) */
481 simple_string_list_append(&schema_include_patterns
, optarg
);
482 dopt
.include_everything
= false;
485 case 'N': /* exclude schema(s) */
486 simple_string_list_append(&schema_exclude_patterns
, optarg
);
489 case 'O': /* Don't reconnect to match owner */
490 dopt
.outputNoOwner
= 1;
493 case 'p': /* server port */
494 dopt
.cparams
.pgport
= pg_strdup(optarg
);
498 /* no-op, still accepted for backwards compatibility */
501 case 's': /* dump schema only */
502 dopt
.schemaOnly
= true;
505 case 'S': /* Username for superuser in plain text output */
506 dopt
.outputSuperuser
= pg_strdup(optarg
);
509 case 't': /* include table(s) */
510 simple_string_list_append(&table_include_patterns
, optarg
);
511 dopt
.include_everything
= false;
514 case 'T': /* exclude table(s) */
515 simple_string_list_append(&table_exclude_patterns
, optarg
);
519 dopt
.cparams
.username
= pg_strdup(optarg
);
522 case 'v': /* verbose */
524 pg_logging_set_level(PG_LOG_INFO
);
528 dopt
.cparams
.promptPassword
= TRI_NO
;
532 dopt
.cparams
.promptPassword
= TRI_YES
;
535 case 'x': /* skip ACL dump */
536 dopt
.aclsSkip
= true;
539 case 'Z': /* Compression Level */
540 compressLevel
= atoi(optarg
);
541 if (compressLevel
< 0 || compressLevel
> 9)
543 pg_log_error("compression level must be in range 0..9");
549 /* This covers the long options. */
552 case 2: /* lock-wait-timeout */
553 dopt
.lockWaitTimeout
= pg_strdup(optarg
);
556 case 3: /* SET ROLE */
557 use_role
= pg_strdup(optarg
);
560 case 4: /* exclude table(s) data */
561 simple_string_list_append(&tabledata_exclude_patterns
, optarg
);
564 case 5: /* section */
565 set_dump_section(optarg
, &dopt
.dumpSections
);
568 case 6: /* snapshot */
569 dumpsnapshot
= pg_strdup(optarg
);
572 case 7: /* no-sync */
577 have_extra_float_digits
= true;
578 extra_float_digits
= atoi(optarg
);
579 if (extra_float_digits
< -15 || extra_float_digits
> 3)
581 pg_log_error("extra_float_digits must be in range -15..3");
586 case 9: /* inserts */
589 * dump_inserts also stores --rows-per-insert, careful not to
592 if (dopt
.dump_inserts
== 0)
593 dopt
.dump_inserts
= DUMP_DEFAULT_ROWS_PER_INSERT
;
596 case 10: /* rows per insert */
598 rowsPerInsert
= strtol(optarg
, &endptr
, 10);
600 if (endptr
== optarg
|| *endptr
!= '\0' ||
601 rowsPerInsert
<= 0 || rowsPerInsert
> INT_MAX
||
604 pg_log_error("rows-per-insert must be in range %d..%d",
608 dopt
.dump_inserts
= (int) rowsPerInsert
;
612 fprintf(stderr
, _("Try \"%s --help\" for more information.\n"), progname
);
618 * Non-option argument specifies database name as long as it wasn't
619 * already specified with -d / --dbname
621 if (optind
< argc
&& dopt
.cparams
.dbname
== NULL
)
622 dopt
.cparams
.dbname
= argv
[optind
++];
624 /* Complain if any arguments remain */
627 pg_log_error("too many command-line arguments (first is \"%s\")",
629 fprintf(stderr
, _("Try \"%s --help\" for more information.\n"),
634 /* --column-inserts implies --inserts */
635 if (dopt
.column_inserts
&& dopt
.dump_inserts
== 0)
636 dopt
.dump_inserts
= DUMP_DEFAULT_ROWS_PER_INSERT
;
639 * Binary upgrade mode implies dumping sequence data even in schema-only
640 * mode. This is not exposed as a separate option, but kept separate
641 * internally for clarity.
643 if (dopt
.binary_upgrade
)
644 dopt
.sequence_data
= 1;
646 if (dopt
.dataOnly
&& dopt
.schemaOnly
)
648 pg_log_error("options -s/--schema-only and -a/--data-only cannot be used together");
652 if (dopt
.dataOnly
&& dopt
.outputClean
)
654 pg_log_error("options -c/--clean and -a/--data-only cannot be used together");
658 if (dopt
.if_exists
&& !dopt
.outputClean
)
659 fatal("option --if-exists requires option -c/--clean");
662 * --inserts are already implied above if --column-inserts or
663 * --rows-per-insert were specified.
665 if (dopt
.do_nothing
&& dopt
.dump_inserts
== 0)
666 fatal("option --on-conflict-do-nothing requires option --inserts, --rows-per-insert, or --column-inserts");
668 /* Identify archive format to emit */
669 archiveFormat
= parseArchiveFormat(format
, &archiveMode
);
671 /* archiveFormat specific setup */
672 if (archiveFormat
== archNull
)
675 /* Custom and directory formats are compressed by default, others not */
676 if (compressLevel
== -1)
679 if (archiveFormat
== archCustom
|| archiveFormat
== archDirectory
)
680 compressLevel
= Z_DEFAULT_COMPRESSION
;
687 if (compressLevel
!= 0)
688 pg_log_warning("requested compression not available in this installation -- archive will be uncompressed");
693 * If emitting an archive format, we always want to emit a DATABASE item,
694 * in case --create is specified at pg_restore time.
697 dopt
.outputCreateDB
= 1;
700 * On Windows we can only have at most MAXIMUM_WAIT_OBJECTS (= 64 usually)
701 * parallel jobs because that's the maximum limit for the
702 * WaitForMultipleObjects() call.
706 || numWorkers
> MAXIMUM_WAIT_OBJECTS
709 fatal("invalid number of parallel jobs");
711 /* Parallel backup only in the directory archive format so far */
712 if (archiveFormat
!= archDirectory
&& numWorkers
> 1)
713 fatal("parallel backup only supported by the directory format");
715 /* Open the output file */
716 fout
= CreateArchive(filename
, archiveFormat
, compressLevel
, dosync
,
717 archiveMode
, setupDumpWorker
);
719 /* Make dump options accessible right away */
720 SetArchiveOptions(fout
, &dopt
, NULL
);
722 /* Register the cleanup hook */
723 on_exit_close_archive(fout
);
725 /* Let the archiver know how noisy to be */
726 fout
->verbose
= g_verbose
;
730 * We allow the server to be back to 8.0, and up to any minor release of
731 * our own major version. (See also version check in pg_dumpall.c.)
733 fout
->minRemoteVersion
= 80000;
734 fout
->maxRemoteVersion
= (PG_VERSION_NUM
/ 100) * 100 + 99;
736 fout
->numWorkers
= numWorkers
;
739 * Open the database using the Archiver, so it knows about it. Errors mean
742 ConnectDatabase(fout
, &dopt
.cparams
, false);
743 setup_connection(fout
, dumpencoding
, dumpsnapshot
, use_role
);
746 * Disable security label support if server version < v9.1.x (prevents
747 * access to nonexistent pg_seclabel catalog)
749 if (fout
->remoteVersion
< 90100)
750 dopt
.no_security_labels
= 1;
753 * On hot standbys, never try to dump unlogged table data, since it will
754 * just throw an error.
757 dopt
.no_unlogged_table_data
= true;
759 /* Select the appropriate subquery to convert user IDs to names */
760 if (fout
->remoteVersion
>= 80100)
761 username_subquery
= "SELECT rolname FROM pg_catalog.pg_roles WHERE oid =";
763 username_subquery
= "SELECT usename FROM pg_catalog.pg_user WHERE usesysid =";
765 /* check the version for the synchronized snapshots feature */
766 if (numWorkers
> 1 && fout
->remoteVersion
< 90200
767 && !dopt
.no_synchronized_snapshots
)
768 fatal("Synchronized snapshots are not supported by this server version.\n"
769 "Run with --no-synchronized-snapshots instead if you do not need\n"
770 "synchronized snapshots.");
772 /* check the version when a snapshot is explicitly specified by user */
773 if (dumpsnapshot
&& fout
->remoteVersion
< 90200)
774 fatal("Exported snapshots are not supported by this server version.");
777 * Find the last built-in OID, if needed (prior to 8.1)
779 * With 8.1 and above, we can just use FirstNormalObjectId - 1.
781 if (fout
->remoteVersion
< 80100)
782 g_last_builtin_oid
= findLastBuiltinOid_V71(fout
);
784 g_last_builtin_oid
= FirstNormalObjectId
- 1;
786 pg_log_info("last built-in OID is %u", g_last_builtin_oid
);
788 /* Expand schema selection patterns into OID lists */
789 if (schema_include_patterns
.head
!= NULL
)
791 expand_schema_name_patterns(fout
, &schema_include_patterns
,
792 &schema_include_oids
,
794 if (schema_include_oids
.head
== NULL
)
795 fatal("no matching schemas were found");
797 expand_schema_name_patterns(fout
, &schema_exclude_patterns
,
798 &schema_exclude_oids
,
800 /* non-matching exclusion patterns aren't an error */
802 /* Expand table selection patterns into OID lists */
803 if (table_include_patterns
.head
!= NULL
)
805 expand_table_name_patterns(fout
, &table_include_patterns
,
808 if (table_include_oids
.head
== NULL
)
809 fatal("no matching tables were found");
811 expand_table_name_patterns(fout
, &table_exclude_patterns
,
815 expand_table_name_patterns(fout
, &tabledata_exclude_patterns
,
816 &tabledata_exclude_oids
,
819 /* non-matching exclusion patterns aren't an error */
822 * Dumping blobs is the default for dumps where an inclusion switch is not
823 * used (an "include everything" dump). -B can be used to exclude blobs
824 * from those dumps. -b can be used to include blobs even when an
825 * inclusion switch is used.
827 * -s means "schema only" and blobs are data, not schema, so we never
828 * include blobs when -s is used.
830 if (dopt
.include_everything
&& !dopt
.schemaOnly
&& !dopt
.dontOutputBlobs
)
831 dopt
.outputBlobs
= true;
834 * Now scan the database and create DumpableObject structs for all the
835 * objects we intend to dump.
837 tblinfo
= getSchemaData(fout
, &numTables
);
839 if (fout
->remoteVersion
< 80400)
840 guessConstraintInheritance(tblinfo
, numTables
);
842 if (!dopt
.schemaOnly
)
844 getTableData(&dopt
, tblinfo
, numTables
, 0);
845 buildMatViewRefreshDependencies(fout
);
847 getTableDataFKConstraints();
850 if (dopt
.schemaOnly
&& dopt
.sequence_data
)
851 getTableData(&dopt
, tblinfo
, numTables
, RELKIND_SEQUENCE
);
854 * In binary-upgrade mode, we do not have to worry about the actual blob
855 * data or the associated metadata that resides in the pg_largeobject and
856 * pg_largeobject_metadata tables, respectively.
858 * However, we do need to collect blob information as there may be
859 * comments or other information on blobs that we do need to dump out.
861 if (dopt
.outputBlobs
|| dopt
.binary_upgrade
)
865 * Collect dependency data to assist in ordering the objects.
867 getDependencies(fout
);
869 /* Lastly, create dummy objects to represent the section boundaries */
870 boundaryObjs
= createBoundaryObjects();
872 /* Get pointers to all the known DumpableObjects */
873 getDumpableObjects(&dobjs
, &numObjs
);
876 * Add dummy dependencies to enforce the dump section ordering.
878 addBoundaryDependencies(dobjs
, numObjs
, boundaryObjs
);
881 * Sort the objects into a safe dump order (no forward references).
883 * We rely on dependency information to help us determine a safe order, so
884 * the initial sort is mostly for cosmetic purposes: we sort by name to
885 * ensure that logically identical schemas will dump identically.
887 sortDumpableObjectsByTypeName(dobjs
, numObjs
);
889 sortDumpableObjects(dobjs
, numObjs
,
890 boundaryObjs
[0].dumpId
, boundaryObjs
[1].dumpId
);
893 * Create archive TOC entries for all the objects to be dumped, in a safe
897 /* First the special ENCODING, STDSTRINGS, and SEARCHPATH entries. */
899 dumpStdStrings(fout
);
900 dumpSearchPath(fout
);
902 /* The database items are always next, unless we don't want them at all */
903 if (dopt
.outputCreateDB
)
906 /* Now the rearrangeable objects. */
907 for (i
= 0; i
< numObjs
; i
++)
908 dumpDumpableObject(fout
, dobjs
[i
]);
911 * Set up options info to ensure we dump what we want.
913 ropt
= NewRestoreOptions();
914 ropt
->filename
= filename
;
916 /* if you change this list, see dumpOptionsFromRestoreOptions */
917 ropt
->cparams
.dbname
= dopt
.cparams
.dbname
? pg_strdup(dopt
.cparams
.dbname
) : NULL
;
918 ropt
->cparams
.pgport
= dopt
.cparams
.pgport
? pg_strdup(dopt
.cparams
.pgport
) : NULL
;
919 ropt
->cparams
.pghost
= dopt
.cparams
.pghost
? pg_strdup(dopt
.cparams
.pghost
) : NULL
;
920 ropt
->cparams
.username
= dopt
.cparams
.username
? pg_strdup(dopt
.cparams
.username
) : NULL
;
921 ropt
->cparams
.promptPassword
= dopt
.cparams
.promptPassword
;
922 ropt
->dropSchema
= dopt
.outputClean
;
923 ropt
->dataOnly
= dopt
.dataOnly
;
924 ropt
->schemaOnly
= dopt
.schemaOnly
;
925 ropt
->if_exists
= dopt
.if_exists
;
926 ropt
->column_inserts
= dopt
.column_inserts
;
927 ropt
->dumpSections
= dopt
.dumpSections
;
928 ropt
->aclsSkip
= dopt
.aclsSkip
;
929 ropt
->superuser
= dopt
.outputSuperuser
;
930 ropt
->createDB
= dopt
.outputCreateDB
;
931 ropt
->noOwner
= dopt
.outputNoOwner
;
932 ropt
->noTablespace
= dopt
.outputNoTablespaces
;
933 ropt
->disable_triggers
= dopt
.disable_triggers
;
934 ropt
->use_setsessauth
= dopt
.use_setsessauth
;
935 ropt
->disable_dollar_quoting
= dopt
.disable_dollar_quoting
;
936 ropt
->dump_inserts
= dopt
.dump_inserts
;
937 ropt
->no_comments
= dopt
.no_comments
;
938 ropt
->no_publications
= dopt
.no_publications
;
939 ropt
->no_security_labels
= dopt
.no_security_labels
;
940 ropt
->no_subscriptions
= dopt
.no_subscriptions
;
941 ropt
->lockWaitTimeout
= dopt
.lockWaitTimeout
;
942 ropt
->include_everything
= dopt
.include_everything
;
943 ropt
->enable_row_security
= dopt
.enable_row_security
;
944 ropt
->sequence_data
= dopt
.sequence_data
;
945 ropt
->binary_upgrade
= dopt
.binary_upgrade
;
947 if (compressLevel
== -1)
948 ropt
->compression
= 0;
950 ropt
->compression
= compressLevel
;
952 ropt
->suppressDumpWarnings
= true; /* We've already shown them */
954 SetArchiveOptions(fout
, &dopt
, ropt
);
956 /* Mark which entries should be output */
957 ProcessArchiveRestoreOptions(fout
);
960 * The archive's TOC entries are now marked as to which ones will actually
961 * be output, so we can set up their dependency lists properly. This isn't
962 * necessary for plain-text output, though.
965 BuildArchiveDependencies(fout
);
968 * And finally we can do the actual output.
970 * Note: for non-plain-text output formats, the output file is written
971 * inside CloseArchive(). This is, um, bizarre; but not worth changing
975 RestoreArchive(fout
);
984 help(const char *progname
)
986 printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname
);
987 printf(_("Usage:\n"));
988 printf(_(" %s [OPTION]... [DBNAME]\n"), progname
);
990 printf(_("\nGeneral options:\n"));
991 printf(_(" -f, --file=FILENAME output file or directory name\n"));
992 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
993 " plain text (default))\n"));
994 printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
995 printf(_(" -v, --verbose verbose mode\n"));
996 printf(_(" -V, --version output version information, then exit\n"));
997 printf(_(" -Z, --compress=0-9 compression level for compressed formats\n"));
998 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
999 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
1000 printf(_(" -?, --help show this help, then exit\n"));
1002 printf(_("\nOptions controlling the output content:\n"));
1003 printf(_(" -a, --data-only dump only the data, not the schema\n"));
1004 printf(_(" -b, --blobs include large objects in dump\n"));
1005 printf(_(" -B, --no-blobs exclude large objects in dump\n"));
1006 printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
1007 printf(_(" -C, --create include commands to create database in dump\n"));
1008 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
1009 printf(_(" -n, --schema=PATTERN dump the specified schema(s) only\n"));
1010 printf(_(" -N, --exclude-schema=PATTERN do NOT dump the specified schema(s)\n"));
1011 printf(_(" -O, --no-owner skip restoration of object ownership in\n"
1012 " plain-text format\n"));
1013 printf(_(" -s, --schema-only dump only the schema, no data\n"));
1014 printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
1015 printf(_(" -t, --table=PATTERN dump the specified table(s) only\n"));
1016 printf(_(" -T, --exclude-table=PATTERN do NOT dump the specified table(s)\n"));
1017 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
1018 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
1019 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
1020 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
1021 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
1022 printf(_(" --enable-row-security enable row security (dump only content user has\n"
1024 printf(_(" --exclude-table-data=PATTERN do NOT dump data for the specified table(s)\n"));
1025 printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
1026 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
1027 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
1028 printf(_(" --load-via-partition-root load partitions via the root table\n"));
1029 printf(_(" --no-comments do not dump comments\n"));
1030 printf(_(" --no-publications do not dump publications\n"));
1031 printf(_(" --no-security-labels do not dump security label assignments\n"));
1032 printf(_(" --no-subscriptions do not dump subscriptions\n"));
1033 printf(_(" --no-synchronized-snapshots do not use synchronized snapshots in parallel jobs\n"));
1034 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
1035 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
1036 printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
1037 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
1038 printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
1039 printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
1040 printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
1041 printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
1042 printf(_(" --strict-names require table and/or schema include patterns to\n"
1043 " match at least one entity each\n"));
1044 printf(_(" --use-set-session-authorization\n"
1045 " use SET SESSION AUTHORIZATION commands instead of\n"
1046 " ALTER OWNER commands to set ownership\n"));
1048 printf(_("\nConnection options:\n"));
1049 printf(_(" -d, --dbname=DBNAME database to dump\n"));
1050 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1051 printf(_(" -p, --port=PORT database server port number\n"));
1052 printf(_(" -U, --username=NAME connect as specified database user\n"));
1053 printf(_(" -w, --no-password never prompt for password\n"));
1054 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1055 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1057 printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1058 "variable value is used.\n\n"));
1059 printf(_("Report bugs to <pgsql-bugs@lists.postgresql.org>.\n"));
1063 setup_connection(Archive
*AH
, const char *dumpencoding
,
1064 const char *dumpsnapshot
, char *use_role
)
1066 DumpOptions
*dopt
= AH
->dopt
;
1067 PGconn
*conn
= GetConnection(AH
);
1068 const char *std_strings
;
1070 PQclear(ExecuteSqlQueryForSingleRow(AH
, ALWAYS_SECURE_SEARCH_PATH_SQL
));
1073 * Set the client encoding if requested.
1077 if (PQsetClientEncoding(conn
, dumpencoding
) < 0)
1078 fatal("invalid client encoding \"%s\" specified",
1083 * Get the active encoding and the standard_conforming_strings setting, so
1084 * we know how to escape strings.
1086 AH
->encoding
= PQclientEncoding(conn
);
1088 std_strings
= PQparameterStatus(conn
, "standard_conforming_strings");
1089 AH
->std_strings
= (std_strings
&& strcmp(std_strings
, "on") == 0);
1092 * Set the role if requested. In a parallel dump worker, we'll be passed
1093 * use_role == NULL, but AH->use_role is already set (if user specified it
1094 * originally) and we should use that.
1096 if (!use_role
&& AH
->use_role
)
1097 use_role
= AH
->use_role
;
1099 /* Set the role if requested */
1100 if (use_role
&& AH
->remoteVersion
>= 80100)
1102 PQExpBuffer query
= createPQExpBuffer();
1104 appendPQExpBuffer(query
, "SET ROLE %s", fmtId(use_role
));
1105 ExecuteSqlStatement(AH
, query
->data
);
1106 destroyPQExpBuffer(query
);
1108 /* save it for possible later use by parallel workers */
1110 AH
->use_role
= pg_strdup(use_role
);
1113 /* Set the datestyle to ISO to ensure the dump's portability */
1114 ExecuteSqlStatement(AH
, "SET DATESTYLE = ISO");
1116 /* Likewise, avoid using sql_standard intervalstyle */
1117 if (AH
->remoteVersion
>= 80400)
1118 ExecuteSqlStatement(AH
, "SET INTERVALSTYLE = POSTGRES");
1121 * Use an explicitly specified extra_float_digits if it has been provided.
1122 * Otherwise, set extra_float_digits so that we can dump float data
1123 * exactly (given correctly implemented float I/O code, anyway).
1125 if (have_extra_float_digits
)
1127 PQExpBuffer q
= createPQExpBuffer();
1129 appendPQExpBuffer(q
, "SET extra_float_digits TO %d",
1130 extra_float_digits
);
1131 ExecuteSqlStatement(AH
, q
->data
);
1132 destroyPQExpBuffer(q
);
1134 else if (AH
->remoteVersion
>= 90000)
1135 ExecuteSqlStatement(AH
, "SET extra_float_digits TO 3");
1137 ExecuteSqlStatement(AH
, "SET extra_float_digits TO 2");
1140 * If synchronized scanning is supported, disable it, to prevent
1141 * unpredictable changes in row ordering across a dump and reload.
1143 if (AH
->remoteVersion
>= 80300)
1144 ExecuteSqlStatement(AH
, "SET synchronize_seqscans TO off");
1147 * Disable timeouts if supported.
1149 ExecuteSqlStatement(AH
, "SET statement_timeout = 0");
1150 if (AH
->remoteVersion
>= 90300)
1151 ExecuteSqlStatement(AH
, "SET lock_timeout = 0");
1152 if (AH
->remoteVersion
>= 90600)
1153 ExecuteSqlStatement(AH
, "SET idle_in_transaction_session_timeout = 0");
1156 * Quote all identifiers, if requested.
1158 if (quote_all_identifiers
&& AH
->remoteVersion
>= 90100)
1159 ExecuteSqlStatement(AH
, "SET quote_all_identifiers = true");
1162 * Adjust row-security mode, if supported.
1164 if (AH
->remoteVersion
>= 90500)
1166 if (dopt
->enable_row_security
)
1167 ExecuteSqlStatement(AH
, "SET row_security = on");
1169 ExecuteSqlStatement(AH
, "SET row_security = off");
1173 * Start transaction-snapshot mode transaction to dump consistent data.
1175 ExecuteSqlStatement(AH
, "BEGIN");
1176 if (AH
->remoteVersion
>= 90100)
1179 * To support the combination of serializable_deferrable with the jobs
1180 * option we use REPEATABLE READ for the worker connections that are
1181 * passed a snapshot. As long as the snapshot is acquired in a
1182 * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1183 * REPEATABLE READ transaction provides the appropriate integrity
1184 * guarantees. This is a kluge, but safe for back-patching.
1186 if (dopt
->serializable_deferrable
&& AH
->sync_snapshot_id
== NULL
)
1187 ExecuteSqlStatement(AH
,
1188 "SET TRANSACTION ISOLATION LEVEL "
1189 "SERIALIZABLE, READ ONLY, DEFERRABLE");
1191 ExecuteSqlStatement(AH
,
1192 "SET TRANSACTION ISOLATION LEVEL "
1193 "REPEATABLE READ, READ ONLY");
1197 ExecuteSqlStatement(AH
,
1198 "SET TRANSACTION ISOLATION LEVEL "
1199 "SERIALIZABLE, READ ONLY");
1203 * If user specified a snapshot to use, select that. In a parallel dump
1204 * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1205 * is already set (if the server can handle it) and we should use that.
1208 AH
->sync_snapshot_id
= pg_strdup(dumpsnapshot
);
1210 if (AH
->sync_snapshot_id
)
1212 PQExpBuffer query
= createPQExpBuffer();
1214 appendPQExpBuffer(query
, "SET TRANSACTION SNAPSHOT ");
1215 appendStringLiteralConn(query
, AH
->sync_snapshot_id
, conn
);
1216 ExecuteSqlStatement(AH
, query
->data
);
1217 destroyPQExpBuffer(query
);
1219 else if (AH
->numWorkers
> 1 &&
1220 AH
->remoteVersion
>= 90200 &&
1221 !dopt
->no_synchronized_snapshots
)
1223 if (AH
->isStandby
&& AH
->remoteVersion
< 100000)
1224 fatal("Synchronized snapshots on standby servers are not supported by this server version.\n"
1225 "Run with --no-synchronized-snapshots instead if you do not need\n"
1226 "synchronized snapshots.");
1229 AH
->sync_snapshot_id
= get_synchronized_snapshot(AH
);
1233 /* Set up connection for a parallel worker process */
1235 setupDumpWorker(Archive
*AH
)
1238 * We want to re-select all the same values the master connection is
1239 * using. We'll have inherited directly-usable values in
1240 * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1241 * inherited encoding value back to a string to pass to setup_connection.
1243 setup_connection(AH
,
1244 pg_encoding_to_char(AH
->encoding
),
1250 get_synchronized_snapshot(Archive
*fout
)
1252 char *query
= "SELECT pg_catalog.pg_export_snapshot()";
1256 res
= ExecuteSqlQueryForSingleRow(fout
, query
);
1257 result
= pg_strdup(PQgetvalue(res
, 0, 0));
1263 static ArchiveFormat
1264 parseArchiveFormat(const char *format
, ArchiveMode
*mode
)
1266 ArchiveFormat archiveFormat
;
1268 *mode
= archModeWrite
;
1270 if (pg_strcasecmp(format
, "a") == 0 || pg_strcasecmp(format
, "append") == 0)
1272 /* This is used by pg_dumpall, and is not documented */
1273 archiveFormat
= archNull
;
1274 *mode
= archModeAppend
;
1276 else if (pg_strcasecmp(format
, "c") == 0)
1277 archiveFormat
= archCustom
;
1278 else if (pg_strcasecmp(format
, "custom") == 0)
1279 archiveFormat
= archCustom
;
1280 else if (pg_strcasecmp(format
, "d") == 0)
1281 archiveFormat
= archDirectory
;
1282 else if (pg_strcasecmp(format
, "directory") == 0)
1283 archiveFormat
= archDirectory
;
1284 else if (pg_strcasecmp(format
, "p") == 0)
1285 archiveFormat
= archNull
;
1286 else if (pg_strcasecmp(format
, "plain") == 0)
1287 archiveFormat
= archNull
;
1288 else if (pg_strcasecmp(format
, "t") == 0)
1289 archiveFormat
= archTar
;
1290 else if (pg_strcasecmp(format
, "tar") == 0)
1291 archiveFormat
= archTar
;
1293 fatal("invalid output format \"%s\" specified", format
);
1294 return archiveFormat
;
1298 * Find the OIDs of all schemas matching the given list of patterns,
1299 * and append them to the given OID list.
1302 expand_schema_name_patterns(Archive
*fout
,
1303 SimpleStringList
*patterns
,
1304 SimpleOidList
*oids
,
1309 SimpleStringListCell
*cell
;
1312 if (patterns
->head
== NULL
)
1313 return; /* nothing to do */
1315 query
= createPQExpBuffer();
1318 * The loop below runs multiple SELECTs might sometimes result in
1319 * duplicate entries in the OID list, but we don't care.
1322 for (cell
= patterns
->head
; cell
; cell
= cell
->next
)
1324 appendPQExpBuffer(query
,
1325 "SELECT oid FROM pg_catalog.pg_namespace n\n");
1326 processSQLNamePattern(GetConnection(fout
), query
, cell
->val
, false,
1327 false, NULL
, "n.nspname", NULL
, NULL
);
1329 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
1330 if (strict_names
&& PQntuples(res
) == 0)
1331 fatal("no matching schemas were found for pattern \"%s\"", cell
->val
);
1333 for (i
= 0; i
< PQntuples(res
); i
++)
1335 simple_oid_list_append(oids
, atooid(PQgetvalue(res
, i
, 0)));
1339 resetPQExpBuffer(query
);
1342 destroyPQExpBuffer(query
);
1346 * Find the OIDs of all tables matching the given list of patterns,
1347 * and append them to the given OID list. See also expand_dbname_patterns()
1351 expand_table_name_patterns(Archive
*fout
,
1352 SimpleStringList
*patterns
, SimpleOidList
*oids
,
1357 SimpleStringListCell
*cell
;
1360 if (patterns
->head
== NULL
)
1361 return; /* nothing to do */
1363 query
= createPQExpBuffer();
1366 * this might sometimes result in duplicate entries in the OID list, but
1370 for (cell
= patterns
->head
; cell
; cell
= cell
->next
)
1373 * Query must remain ABSOLUTELY devoid of unqualified names. This
1374 * would be unnecessary given a pg_table_is_visible() variant taking a
1375 * search_path argument.
1377 appendPQExpBuffer(query
,
1379 "\nFROM pg_catalog.pg_class c"
1380 "\n LEFT JOIN pg_catalog.pg_namespace n"
1381 "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1382 "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1383 "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1384 RELKIND_RELATION
, RELKIND_SEQUENCE
, RELKIND_VIEW
,
1385 RELKIND_MATVIEW
, RELKIND_FOREIGN_TABLE
,
1386 RELKIND_PARTITIONED_TABLE
);
1387 processSQLNamePattern(GetConnection(fout
), query
, cell
->val
, true,
1388 false, "n.nspname", "c.relname", NULL
,
1389 "pg_catalog.pg_table_is_visible(c.oid)");
1391 ExecuteSqlStatement(fout
, "RESET search_path");
1392 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
1393 PQclear(ExecuteSqlQueryForSingleRow(fout
,
1394 ALWAYS_SECURE_SEARCH_PATH_SQL
));
1395 if (strict_names
&& PQntuples(res
) == 0)
1396 fatal("no matching tables were found for pattern \"%s\"", cell
->val
);
1398 for (i
= 0; i
< PQntuples(res
); i
++)
1400 simple_oid_list_append(oids
, atooid(PQgetvalue(res
, i
, 0)));
1404 resetPQExpBuffer(query
);
1407 destroyPQExpBuffer(query
);
1411 * checkExtensionMembership
1412 * Determine whether object is an extension member, and if so,
1413 * record an appropriate dependency and set the object's dump flag.
1415 * It's important to call this for each object that could be an extension
1416 * member. Generally, we integrate this with determining the object's
1417 * to-be-dumped-ness, since extension membership overrides other rules for that.
1419 * Returns true if object is an extension member, else false.
1422 checkExtensionMembership(DumpableObject
*dobj
, Archive
*fout
)
1424 ExtensionInfo
*ext
= findOwningExtension(dobj
->catId
);
1429 dobj
->ext_member
= true;
1431 /* Record dependency so that getDependencies needn't deal with that */
1432 addObjectDependency(dobj
, ext
->dobj
.dumpId
);
1435 * In 9.6 and above, mark the member object to have any non-initial ACLs
1436 * dumped. (Any initial ACLs will be removed later, using data from
1437 * pg_init_privs, so that we'll dump only the delta from the extension's
1440 * Prior to 9.6, we do not include any extension member components.
1442 * In binary upgrades, we still dump all components of the members
1443 * individually, since the idea is to exactly reproduce the database
1444 * contents rather than replace the extension contents with something
1447 * Note: it might be interesting someday to implement storage and delta
1448 * dumping of extension members' RLS policies and/or security labels.
1449 * However there is a pitfall for RLS policies: trying to dump them
1450 * requires getting a lock on their tables, and the calling user might not
1451 * have privileges for that. We need no lock to examine a table's ACLs,
1452 * so the current feature doesn't have a problem of that sort.
1454 if (fout
->dopt
->binary_upgrade
)
1455 dobj
->dump
= ext
->dobj
.dump
;
1458 if (fout
->remoteVersion
< 90600)
1459 dobj
->dump
= DUMP_COMPONENT_NONE
;
1461 dobj
->dump
= ext
->dobj
.dump_contains
& (DUMP_COMPONENT_ACL
);
1468 * selectDumpableNamespace: policy-setting subroutine
1469 * Mark a namespace as to be dumped or not
1472 selectDumpableNamespace(NamespaceInfo
*nsinfo
, Archive
*fout
)
1475 * If specific tables are being dumped, do not dump any complete
1476 * namespaces. If specific namespaces are being dumped, dump just those
1477 * namespaces. Otherwise, dump all non-system namespaces.
1479 if (table_include_oids
.head
!= NULL
)
1480 nsinfo
->dobj
.dump_contains
= nsinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1481 else if (schema_include_oids
.head
!= NULL
)
1482 nsinfo
->dobj
.dump_contains
= nsinfo
->dobj
.dump
=
1483 simple_oid_list_member(&schema_include_oids
,
1484 nsinfo
->dobj
.catId
.oid
) ?
1485 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1486 else if (fout
->remoteVersion
>= 90600 &&
1487 strcmp(nsinfo
->dobj
.name
, "pg_catalog") == 0)
1490 * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1491 * they are interesting (and not the original ACLs which were set at
1492 * initdb time, see pg_init_privs).
1494 nsinfo
->dobj
.dump_contains
= nsinfo
->dobj
.dump
= DUMP_COMPONENT_ACL
;
1496 else if (strncmp(nsinfo
->dobj
.name
, "pg_", 3) == 0 ||
1497 strcmp(nsinfo
->dobj
.name
, "information_schema") == 0)
1499 /* Other system schemas don't get dumped */
1500 nsinfo
->dobj
.dump_contains
= nsinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1502 else if (strcmp(nsinfo
->dobj
.name
, "public") == 0)
1505 * The public schema is a strange beast that sits in a sort of
1506 * no-mans-land between being a system object and a user object. We
1507 * don't want to dump creation or comment commands for it, because
1508 * that complicates matters for non-superuser use of pg_dump. But we
1509 * should dump any ACL changes that have occurred for it, and of
1510 * course we should dump contained objects.
1512 nsinfo
->dobj
.dump
= DUMP_COMPONENT_ACL
;
1513 nsinfo
->dobj
.dump_contains
= DUMP_COMPONENT_ALL
;
1516 nsinfo
->dobj
.dump_contains
= nsinfo
->dobj
.dump
= DUMP_COMPONENT_ALL
;
1519 * In any case, a namespace can be excluded by an exclusion switch
1521 if (nsinfo
->dobj
.dump_contains
&&
1522 simple_oid_list_member(&schema_exclude_oids
,
1523 nsinfo
->dobj
.catId
.oid
))
1524 nsinfo
->dobj
.dump_contains
= nsinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1527 * If the schema belongs to an extension, allow extension membership to
1528 * override the dump decision for the schema itself. However, this does
1529 * not change dump_contains, so this won't change what we do with objects
1530 * within the schema. (If they belong to the extension, they'll get
1531 * suppressed by it, otherwise not.)
1533 (void) checkExtensionMembership(&nsinfo
->dobj
, fout
);
1537 * selectDumpableTable: policy-setting subroutine
1538 * Mark a table as to be dumped or not
1541 selectDumpableTable(TableInfo
*tbinfo
, Archive
*fout
)
1543 if (checkExtensionMembership(&tbinfo
->dobj
, fout
))
1544 return; /* extension membership overrides all else */
1547 * If specific tables are being dumped, dump just those tables; else, dump
1548 * according to the parent namespace's dump flag.
1550 if (table_include_oids
.head
!= NULL
)
1551 tbinfo
->dobj
.dump
= simple_oid_list_member(&table_include_oids
,
1552 tbinfo
->dobj
.catId
.oid
) ?
1553 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1555 tbinfo
->dobj
.dump
= tbinfo
->dobj
.namespace->dobj
.dump_contains
;
1558 * In any case, a table can be excluded by an exclusion switch
1560 if (tbinfo
->dobj
.dump
&&
1561 simple_oid_list_member(&table_exclude_oids
,
1562 tbinfo
->dobj
.catId
.oid
))
1563 tbinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1567 * selectDumpableType: policy-setting subroutine
1568 * Mark a type as to be dumped or not
1570 * If it's a table's rowtype or an autogenerated array type, we also apply a
1571 * special type code to facilitate sorting into the desired order. (We don't
1572 * want to consider those to be ordinary types because that would bring tables
1573 * up into the datatype part of the dump order.) We still set the object's
1574 * dump flag; that's not going to cause the dummy type to be dumped, but we
1575 * need it so that casts involving such types will be dumped correctly -- see
1576 * dumpCast. This means the flag should be set the same as for the underlying
1577 * object (the table or base type).
1580 selectDumpableType(TypeInfo
*tyinfo
, Archive
*fout
)
1582 /* skip complex types, except for standalone composite types */
1583 if (OidIsValid(tyinfo
->typrelid
) &&
1584 tyinfo
->typrelkind
!= RELKIND_COMPOSITE_TYPE
)
1586 TableInfo
*tytable
= findTableByOid(tyinfo
->typrelid
);
1588 tyinfo
->dobj
.objType
= DO_DUMMY_TYPE
;
1589 if (tytable
!= NULL
)
1590 tyinfo
->dobj
.dump
= tytable
->dobj
.dump
;
1592 tyinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1596 /* skip auto-generated array types */
1597 if (tyinfo
->isArray
)
1599 tyinfo
->dobj
.objType
= DO_DUMMY_TYPE
;
1602 * Fall through to set the dump flag; we assume that the subsequent
1603 * rules will do the same thing as they would for the array's base
1604 * type. (We cannot reliably look up the base type here, since
1605 * getTypes may not have processed it yet.)
1609 if (checkExtensionMembership(&tyinfo
->dobj
, fout
))
1610 return; /* extension membership overrides all else */
1612 /* Dump based on if the contents of the namespace are being dumped */
1613 tyinfo
->dobj
.dump
= tyinfo
->dobj
.namespace->dobj
.dump_contains
;
1617 * selectDumpableDefaultACL: policy-setting subroutine
1618 * Mark a default ACL as to be dumped or not
1620 * For per-schema default ACLs, dump if the schema is to be dumped.
1621 * Otherwise dump if we are dumping "everything". Note that dataOnly
1622 * and aclsSkip are checked separately.
1625 selectDumpableDefaultACL(DefaultACLInfo
*dinfo
, DumpOptions
*dopt
)
1627 /* Default ACLs can't be extension members */
1629 if (dinfo
->dobj
.namespace)
1630 /* default ACLs are considered part of the namespace */
1631 dinfo
->dobj
.dump
= dinfo
->dobj
.namespace->dobj
.dump_contains
;
1633 dinfo
->dobj
.dump
= dopt
->include_everything
?
1634 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1638 * selectDumpableCast: policy-setting subroutine
1639 * Mark a cast as to be dumped or not
1641 * Casts do not belong to any particular namespace (since they haven't got
1642 * names), nor do they have identifiable owners. To distinguish user-defined
1643 * casts from built-in ones, we must resort to checking whether the cast's
1644 * OID is in the range reserved for initdb.
1647 selectDumpableCast(CastInfo
*cast
, Archive
*fout
)
1649 if (checkExtensionMembership(&cast
->dobj
, fout
))
1650 return; /* extension membership overrides all else */
1653 * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
1654 * support ACLs currently.
1656 if (cast
->dobj
.catId
.oid
<= (Oid
) g_last_builtin_oid
)
1657 cast
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1659 cast
->dobj
.dump
= fout
->dopt
->include_everything
?
1660 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1664 * selectDumpableProcLang: policy-setting subroutine
1665 * Mark a procedural language as to be dumped or not
1667 * Procedural languages do not belong to any particular namespace. To
1668 * identify built-in languages, we must resort to checking whether the
1669 * language's OID is in the range reserved for initdb.
1672 selectDumpableProcLang(ProcLangInfo
*plang
, Archive
*fout
)
1674 if (checkExtensionMembership(&plang
->dobj
, fout
))
1675 return; /* extension membership overrides all else */
1678 * Only include procedural languages when we are dumping everything.
1680 * For from-initdb procedural languages, only include ACLs, as we do for
1681 * the pg_catalog namespace. We need this because procedural languages do
1682 * not live in any namespace.
1684 if (!fout
->dopt
->include_everything
)
1685 plang
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1688 if (plang
->dobj
.catId
.oid
<= (Oid
) g_last_builtin_oid
)
1689 plang
->dobj
.dump
= fout
->remoteVersion
< 90600 ?
1690 DUMP_COMPONENT_NONE
: DUMP_COMPONENT_ACL
;
1692 plang
->dobj
.dump
= DUMP_COMPONENT_ALL
;
1697 * selectDumpableAccessMethod: policy-setting subroutine
1698 * Mark an access method as to be dumped or not
1700 * Access methods do not belong to any particular namespace. To identify
1701 * built-in access methods, we must resort to checking whether the
1702 * method's OID is in the range reserved for initdb.
1705 selectDumpableAccessMethod(AccessMethodInfo
*method
, Archive
*fout
)
1707 if (checkExtensionMembership(&method
->dobj
, fout
))
1708 return; /* extension membership overrides all else */
1711 * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
1712 * they do not support ACLs currently.
1714 if (method
->dobj
.catId
.oid
<= (Oid
) g_last_builtin_oid
)
1715 method
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1717 method
->dobj
.dump
= fout
->dopt
->include_everything
?
1718 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1722 * selectDumpableExtension: policy-setting subroutine
1723 * Mark an extension as to be dumped or not
1725 * Built-in extensions should be skipped except for checking ACLs, since we
1726 * assume those will already be installed in the target database. We identify
1727 * such extensions by their having OIDs in the range reserved for initdb.
1728 * We dump all user-added extensions by default, or none of them if
1729 * include_everything is false (i.e., a --schema or --table switch was given).
1732 selectDumpableExtension(ExtensionInfo
*extinfo
, DumpOptions
*dopt
)
1735 * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
1736 * change permissions on their member objects, if they wish to, and have
1737 * those changes preserved.
1739 if (extinfo
->dobj
.catId
.oid
<= (Oid
) g_last_builtin_oid
)
1740 extinfo
->dobj
.dump
= extinfo
->dobj
.dump_contains
= DUMP_COMPONENT_ACL
;
1742 extinfo
->dobj
.dump
= extinfo
->dobj
.dump_contains
=
1743 dopt
->include_everything
? DUMP_COMPONENT_ALL
:
1744 DUMP_COMPONENT_NONE
;
1748 * selectDumpablePublicationTable: policy-setting subroutine
1749 * Mark a publication table as to be dumped or not
1751 * Publication tables have schemas, but those are ignored in decision making,
1752 * because publications are only dumped when we are dumping everything.
1755 selectDumpablePublicationTable(DumpableObject
*dobj
, Archive
*fout
)
1757 if (checkExtensionMembership(dobj
, fout
))
1758 return; /* extension membership overrides all else */
1760 dobj
->dump
= fout
->dopt
->include_everything
?
1761 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1765 * selectDumpableStatisticsObject: policy-setting subroutine
1766 * Mark an extended statistics object as to be dumped or not
1768 * We dump an extended statistics object if the schema it's in and the table
1769 * it's for are being dumped. (This'll need more thought if statistics
1770 * objects ever support cross-table stats.)
1773 selectDumpableStatisticsObject(StatsExtInfo
*sobj
, Archive
*fout
)
1775 if (checkExtensionMembership(&sobj
->dobj
, fout
))
1776 return; /* extension membership overrides all else */
1778 sobj
->dobj
.dump
= sobj
->dobj
.namespace->dobj
.dump_contains
;
1779 if (sobj
->stattable
== NULL
||
1780 !(sobj
->stattable
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
1781 sobj
->dobj
.dump
= DUMP_COMPONENT_NONE
;
1785 * selectDumpableObject: policy-setting subroutine
1786 * Mark a generic dumpable object as to be dumped or not
1788 * Use this only for object types without a special-case routine above.
1791 selectDumpableObject(DumpableObject
*dobj
, Archive
*fout
)
1793 if (checkExtensionMembership(dobj
, fout
))
1794 return; /* extension membership overrides all else */
1797 * Default policy is to dump if parent namespace is dumpable, or for
1798 * non-namespace-associated items, dump if we're dumping "everything".
1800 if (dobj
->namespace)
1801 dobj
->dump
= dobj
->namespace->dobj
.dump_contains
;
1803 dobj
->dump
= fout
->dopt
->include_everything
?
1804 DUMP_COMPONENT_ALL
: DUMP_COMPONENT_NONE
;
1808 * Dump a table's contents for loading using the COPY command
1809 * - this routine is called by the Archiver when it wants the table
1814 dumpTableData_copy(Archive
*fout
, void *dcontext
)
1816 TableDataInfo
*tdinfo
= (TableDataInfo
*) dcontext
;
1817 TableInfo
*tbinfo
= tdinfo
->tdtable
;
1818 const char *classname
= tbinfo
->dobj
.name
;
1819 PQExpBuffer q
= createPQExpBuffer();
1822 * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
1823 * which uses it already.
1825 PQExpBuffer clistBuf
= createPQExpBuffer();
1826 PGconn
*conn
= GetConnection(fout
);
1830 const char *column_list
;
1832 pg_log_info("dumping contents of table \"%s.%s\"",
1833 tbinfo
->dobj
.namespace->dobj
.name
, classname
);
1836 * Specify the column list explicitly so that we have no possibility of
1837 * retrieving data in the wrong column order. (The default column
1838 * ordering of COPY will not be what we want in certain corner cases
1839 * involving ADD COLUMN and inheritance.)
1841 column_list
= fmtCopyColumnList(tbinfo
, clistBuf
);
1843 if (tdinfo
->filtercond
)
1845 /* Note: this syntax is only supported in 8.2 and up */
1846 appendPQExpBufferStr(q
, "COPY (SELECT ");
1847 /* klugery to get rid of parens in column list */
1848 if (strlen(column_list
) > 2)
1850 appendPQExpBufferStr(q
, column_list
+ 1);
1851 q
->data
[q
->len
- 1] = ' ';
1854 appendPQExpBufferStr(q
, "* ");
1855 appendPQExpBuffer(q
, "FROM %s %s) TO stdout;",
1856 fmtQualifiedDumpable(tbinfo
),
1857 tdinfo
->filtercond
);
1861 appendPQExpBuffer(q
, "COPY %s %s TO stdout;",
1862 fmtQualifiedDumpable(tbinfo
),
1865 res
= ExecuteSqlQuery(fout
, q
->data
, PGRES_COPY_OUT
);
1867 destroyPQExpBuffer(clistBuf
);
1871 ret
= PQgetCopyData(conn
, ©buf
, 0);
1874 break; /* done or error */
1878 WriteData(fout
, copybuf
, ret
);
1885 * There was considerable discussion in late July, 2000 regarding
1886 * slowing down pg_dump when backing up large tables. Users with both
1887 * slow & fast (multi-processor) machines experienced performance
1888 * degradation when doing a backup.
1890 * Initial attempts based on sleeping for a number of ms for each ms
1891 * of work were deemed too complex, then a simple 'sleep in each loop'
1892 * implementation was suggested. The latter failed because the loop
1893 * was too tight. Finally, the following was implemented:
1895 * If throttle is non-zero, then
1896 * See how long since the last sleep.
1897 * Work out how long to sleep (based on ratio).
1898 * If sleep is more than 100ms, then
1904 * where the throttle value was the number of ms to sleep per ms of
1905 * work. The calculation was done in each loop.
1907 * Most of the hard work is done in the backend, and this solution
1908 * still did not work particularly well: on slow machines, the ratio
1909 * was 50:1, and on medium paced machines, 1:1, and on fast
1910 * multi-processor machines, it had little or no effect, for reasons
1911 * that were unclear.
1913 * Further discussion ensued, and the proposal was dropped.
1915 * For those people who want this feature, it can be implemented using
1916 * gettimeofday in each loop, calculating the time since last sleep,
1917 * multiplying that by the sleep ratio, then if the result is more
1918 * than a preset 'minimum sleep time' (say 100ms), call the 'select'
1919 * function to sleep for a subsecond period ie.
1921 * select(0, NULL, NULL, NULL, &tvi);
1923 * This will return after the interval specified in the structure tvi.
1924 * Finally, call gettimeofday again to save the 'last sleep time'.
1928 archprintf(fout
, "\\.\n\n\n");
1932 /* copy data transfer failed */
1933 pg_log_error("Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.", classname
);
1934 pg_log_error("Error message from server: %s", PQerrorMessage(conn
));
1935 pg_log_error("The command was: %s", q
->data
);
1939 /* Check command status and return to normal libpq state */
1940 res
= PQgetResult(conn
);
1941 if (PQresultStatus(res
) != PGRES_COMMAND_OK
)
1943 pg_log_error("Dumping the contents of table \"%s\" failed: PQgetResult() failed.", classname
);
1944 pg_log_error("Error message from server: %s", PQerrorMessage(conn
));
1945 pg_log_error("The command was: %s", q
->data
);
1950 /* Do this to ensure we've pumped libpq back to idle state */
1951 if (PQgetResult(conn
) != NULL
)
1952 pg_log_warning("unexpected extra results during COPY of table \"%s\"",
1955 destroyPQExpBuffer(q
);
1960 * Dump table data using INSERT commands.
1962 * Caution: when we restore from an archive file direct to database, the
1963 * INSERT commands emitted by this function have to be parsed by
1964 * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
1965 * E'' strings, or dollar-quoted strings. So don't emit anything like that.
1968 dumpTableData_insert(Archive
*fout
, void *dcontext
)
1970 TableDataInfo
*tdinfo
= (TableDataInfo
*) dcontext
;
1971 TableInfo
*tbinfo
= tdinfo
->tdtable
;
1972 DumpOptions
*dopt
= fout
->dopt
;
1973 PQExpBuffer q
= createPQExpBuffer();
1974 PQExpBuffer insertStmt
= NULL
;
1979 int rows_per_statement
= dopt
->dump_inserts
;
1980 int rows_this_statement
= 0;
1983 * If we're going to emit INSERTs with column names, the most efficient
1984 * way to deal with generated columns is to exclude them entirely. For
1985 * INSERTs without column names, we have to emit DEFAULT rather than the
1986 * actual column value --- but we can save a few cycles by fetching nulls
1987 * rather than the uninteresting-to-us value.
1989 attgenerated
= (char *) pg_malloc(tbinfo
->numatts
* sizeof(char));
1990 appendPQExpBufferStr(q
, "DECLARE _pg_dump_cursor CURSOR FOR SELECT ");
1992 for (i
= 0; i
< tbinfo
->numatts
; i
++)
1994 if (tbinfo
->attisdropped
[i
])
1996 if (tbinfo
->attgenerated
[i
] && dopt
->column_inserts
)
1999 appendPQExpBufferStr(q
, ", ");
2000 if (tbinfo
->attgenerated
[i
])
2001 appendPQExpBufferStr(q
, "NULL");
2003 appendPQExpBufferStr(q
, fmtId(tbinfo
->attnames
[i
]));
2004 attgenerated
[nfields
] = tbinfo
->attgenerated
[i
];
2007 /* Servers before 9.4 will complain about zero-column SELECT */
2009 appendPQExpBufferStr(q
, "NULL");
2010 appendPQExpBuffer(q
, " FROM ONLY %s",
2011 fmtQualifiedDumpable(tbinfo
));
2012 if (tdinfo
->filtercond
)
2013 appendPQExpBuffer(q
, " %s", tdinfo
->filtercond
);
2015 ExecuteSqlStatement(fout
, q
->data
);
2019 res
= ExecuteSqlQuery(fout
, "FETCH 100 FROM _pg_dump_cursor",
2022 /* cross-check field count, allowing for dummy NULL if any */
2023 if (nfields
!= PQnfields(res
) &&
2024 !(nfields
== 0 && PQnfields(res
) == 1))
2025 fatal("wrong number of fields retrieved from table \"%s\"",
2029 * First time through, we build as much of the INSERT statement as
2030 * possible in "insertStmt", which we can then just print for each
2031 * statement. If the table happens to have zero dumpable columns then
2032 * this will be a complete statement, otherwise it will end in
2033 * "VALUES" and be ready to have the row's column values printed.
2035 if (insertStmt
== NULL
)
2037 TableInfo
*targettab
;
2039 insertStmt
= createPQExpBuffer();
2042 * When load-via-partition-root is set or forced, get the root
2043 * table name for the partition table, so that we can reload data
2044 * through the root table.
2046 if (tbinfo
->ispartition
&&
2047 (dopt
->load_via_partition_root
||
2048 forcePartitionRootLoad(tbinfo
)))
2049 targettab
= getRootTableInfo(tbinfo
);
2053 appendPQExpBuffer(insertStmt
, "INSERT INTO %s ",
2054 fmtQualifiedDumpable(targettab
));
2056 /* corner case for zero-column table */
2059 appendPQExpBufferStr(insertStmt
, "DEFAULT VALUES;\n");
2063 /* append the list of column names if required */
2064 if (dopt
->column_inserts
)
2066 appendPQExpBufferChar(insertStmt
, '(');
2067 for (int field
= 0; field
< nfields
; field
++)
2070 appendPQExpBufferStr(insertStmt
, ", ");
2071 appendPQExpBufferStr(insertStmt
,
2072 fmtId(PQfname(res
, field
)));
2074 appendPQExpBufferStr(insertStmt
, ") ");
2077 if (tbinfo
->needs_override
)
2078 appendPQExpBufferStr(insertStmt
, "OVERRIDING SYSTEM VALUE ");
2080 appendPQExpBufferStr(insertStmt
, "VALUES");
2084 for (int tuple
= 0; tuple
< PQntuples(res
); tuple
++)
2086 /* Write the INSERT if not in the middle of a multi-row INSERT. */
2087 if (rows_this_statement
== 0)
2088 archputs(insertStmt
->data
, fout
);
2091 * If it is zero-column table then we've already written the
2092 * complete statement, which will mean we've disobeyed
2093 * --rows-per-insert when it's set greater than 1. We do support
2094 * a way to make this multi-row with: SELECT UNION ALL SELECT
2095 * UNION ALL ... but that's non-standard so we should avoid it
2096 * given that using INSERTs is mostly only ever needed for
2097 * cross-database exports.
2102 /* Emit a row heading */
2103 if (rows_per_statement
== 1)
2104 archputs(" (", fout
);
2105 else if (rows_this_statement
> 0)
2106 archputs(",\n\t(", fout
);
2108 archputs("\n\t(", fout
);
2110 for (int field
= 0; field
< nfields
; field
++)
2113 archputs(", ", fout
);
2114 if (attgenerated
[field
])
2116 archputs("DEFAULT", fout
);
2119 if (PQgetisnull(res
, tuple
, field
))
2121 archputs("NULL", fout
);
2125 /* XXX This code is partially duplicated in ruleutils.c */
2126 switch (PQftype(res
, field
))
2137 * These types are printed without quotes unless
2138 * they contain values that aren't accepted by the
2139 * scanner unquoted (e.g., 'NaN'). Note that
2140 * strtod() and friends might accept NaN, so we
2141 * can't use that to test.
2143 * In reality we only need to defend against
2144 * infinity and NaN, so we need not get too crazy
2145 * about pattern matching here.
2147 const char *s
= PQgetvalue(res
, tuple
, field
);
2149 if (strspn(s
, "0123456789 +-eE.") == strlen(s
))
2152 archprintf(fout
, "'%s'", s
);
2158 archprintf(fout
, "B'%s'",
2159 PQgetvalue(res
, tuple
, field
));
2163 if (strcmp(PQgetvalue(res
, tuple
, field
), "t") == 0)
2164 archputs("true", fout
);
2166 archputs("false", fout
);
2170 /* All other types are printed as string literals. */
2171 resetPQExpBuffer(q
);
2172 appendStringLiteralAH(q
,
2173 PQgetvalue(res
, tuple
, field
),
2175 archputs(q
->data
, fout
);
2180 /* Terminate the row ... */
2181 archputs(")", fout
);
2183 /* ... and the statement, if the target no. of rows is reached */
2184 if (++rows_this_statement
>= rows_per_statement
)
2186 if (dopt
->do_nothing
)
2187 archputs(" ON CONFLICT DO NOTHING;\n", fout
);
2189 archputs(";\n", fout
);
2190 /* Reset the row counter */
2191 rows_this_statement
= 0;
2195 if (PQntuples(res
) <= 0)
2203 /* Terminate any statements that didn't make the row count. */
2204 if (rows_this_statement
> 0)
2206 if (dopt
->do_nothing
)
2207 archputs(" ON CONFLICT DO NOTHING;\n", fout
);
2209 archputs(";\n", fout
);
2212 archputs("\n\n", fout
);
2214 ExecuteSqlStatement(fout
, "CLOSE _pg_dump_cursor");
2216 destroyPQExpBuffer(q
);
2217 if (insertStmt
!= NULL
)
2218 destroyPQExpBuffer(insertStmt
);
2226 * get the root TableInfo for the given partition table.
2229 getRootTableInfo(TableInfo
*tbinfo
)
2231 TableInfo
*parentTbinfo
;
2233 Assert(tbinfo
->ispartition
);
2234 Assert(tbinfo
->numParents
== 1);
2236 parentTbinfo
= tbinfo
->parents
[0];
2237 while (parentTbinfo
->ispartition
)
2239 Assert(parentTbinfo
->numParents
== 1);
2240 parentTbinfo
= parentTbinfo
->parents
[0];
2243 return parentTbinfo
;
2247 * forcePartitionRootLoad
2248 * Check if we must force load_via_partition_root for this partition.
2250 * This is required if any level of ancestral partitioned table has an
2251 * unsafe partitioning scheme.
2254 forcePartitionRootLoad(const TableInfo
*tbinfo
)
2256 TableInfo
*parentTbinfo
;
2258 Assert(tbinfo
->ispartition
);
2259 Assert(tbinfo
->numParents
== 1);
2261 parentTbinfo
= tbinfo
->parents
[0];
2262 if (parentTbinfo
->unsafe_partitions
)
2264 while (parentTbinfo
->ispartition
)
2266 Assert(parentTbinfo
->numParents
== 1);
2267 parentTbinfo
= parentTbinfo
->parents
[0];
2268 if (parentTbinfo
->unsafe_partitions
)
2277 * dump the contents of a single table
2279 * Actually, this just makes an ArchiveEntry for the table contents.
2282 dumpTableData(Archive
*fout
, TableDataInfo
*tdinfo
)
2284 DumpOptions
*dopt
= fout
->dopt
;
2285 TableInfo
*tbinfo
= tdinfo
->tdtable
;
2286 PQExpBuffer copyBuf
= createPQExpBuffer();
2287 PQExpBuffer clistBuf
= createPQExpBuffer();
2288 DataDumperPtr dumpFn
;
2289 char *tdDefn
= NULL
;
2291 const char *copyFrom
;
2293 /* We had better have loaded per-column details about this table */
2294 Assert(tbinfo
->interesting
);
2297 * When load-via-partition-root is set or forced, get the root table name
2298 * for the partition table, so that we can reload data through the root
2299 * table. Then construct a comment to be inserted into the TOC entry's
2300 * defn field, so that such cases can be identified reliably.
2302 if (tbinfo
->ispartition
&&
2303 (dopt
->load_via_partition_root
||
2304 forcePartitionRootLoad(tbinfo
)))
2306 TableInfo
*parentTbinfo
;
2308 parentTbinfo
= getRootTableInfo(tbinfo
);
2309 copyFrom
= fmtQualifiedDumpable(parentTbinfo
);
2310 printfPQExpBuffer(copyBuf
, "-- load via partition root %s",
2312 tdDefn
= pg_strdup(copyBuf
->data
);
2315 copyFrom
= fmtQualifiedDumpable(tbinfo
);
2317 if (!dopt
->dump_inserts
)
2319 /* Dump/restore using COPY */
2320 dumpFn
= dumpTableData_copy
;
2321 /* must use 2 steps here 'cause fmtId is nonreentrant */
2322 printfPQExpBuffer(copyBuf
, "COPY %s ",
2324 appendPQExpBuffer(copyBuf
, "%s FROM stdin;\n",
2325 fmtCopyColumnList(tbinfo
, clistBuf
));
2326 copyStmt
= copyBuf
->data
;
2330 /* Restore using INSERT */
2331 dumpFn
= dumpTableData_insert
;
2336 * Note: although the TableDataInfo is a full DumpableObject, we treat its
2337 * dependency on its table as "special" and pass it to ArchiveEntry now.
2338 * See comments for BuildArchiveDependencies.
2340 if (tdinfo
->dobj
.dump
& DUMP_COMPONENT_DATA
)
2344 te
= ArchiveEntry(fout
, tdinfo
->dobj
.catId
, tdinfo
->dobj
.dumpId
,
2345 ARCHIVE_OPTS(.tag
= tbinfo
->dobj
.name
,
2346 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
2347 .owner
= tbinfo
->rolname
,
2348 .description
= "TABLE DATA",
2349 .section
= SECTION_DATA
,
2350 .createStmt
= tdDefn
,
2351 .copyStmt
= copyStmt
,
2352 .deps
= &(tbinfo
->dobj
.dumpId
),
2355 .dumpArg
= tdinfo
));
2358 * Set the TocEntry's dataLength in case we are doing a parallel dump
2359 * and want to order dump jobs by table size. We choose to measure
2360 * dataLength in table pages during dump, so no scaling is needed.
2361 * However, relpages is declared as "integer" in pg_class, and hence
2362 * also in TableInfo, but it's really BlockNumber a/k/a unsigned int.
2363 * Cast so that we get the right interpretation of table sizes
2364 * exceeding INT_MAX pages.
2366 te
->dataLength
= (BlockNumber
) tbinfo
->relpages
;
2369 destroyPQExpBuffer(copyBuf
);
2370 destroyPQExpBuffer(clistBuf
);
2374 * refreshMatViewData -
2375 * load or refresh the contents of a single materialized view
2377 * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2381 refreshMatViewData(Archive
*fout
, TableDataInfo
*tdinfo
)
2383 TableInfo
*tbinfo
= tdinfo
->tdtable
;
2386 /* If the materialized view is not flagged as populated, skip this. */
2387 if (!tbinfo
->relispopulated
)
2390 q
= createPQExpBuffer();
2392 appendPQExpBuffer(q
, "REFRESH MATERIALIZED VIEW %s;\n",
2393 fmtQualifiedDumpable(tbinfo
));
2395 if (tdinfo
->dobj
.dump
& DUMP_COMPONENT_DATA
)
2397 tdinfo
->dobj
.catId
, /* catalog ID */
2398 tdinfo
->dobj
.dumpId
, /* dump ID */
2399 ARCHIVE_OPTS(.tag
= tbinfo
->dobj
.name
,
2400 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
2401 .owner
= tbinfo
->rolname
,
2402 .description
= "MATERIALIZED VIEW DATA",
2403 .section
= SECTION_POST_DATA
,
2404 .createStmt
= q
->data
,
2405 .deps
= tdinfo
->dobj
.dependencies
,
2406 .nDeps
= tdinfo
->dobj
.nDeps
));
2408 destroyPQExpBuffer(q
);
2413 * set up dumpable objects representing the contents of tables
2416 getTableData(DumpOptions
*dopt
, TableInfo
*tblinfo
, int numTables
, char relkind
)
2420 for (i
= 0; i
< numTables
; i
++)
2422 if (tblinfo
[i
].dobj
.dump
& DUMP_COMPONENT_DATA
&&
2423 (!relkind
|| tblinfo
[i
].relkind
== relkind
))
2424 makeTableDataInfo(dopt
, &(tblinfo
[i
]));
2429 * Make a dumpable object for the data of this specific table
2431 * Note: we make a TableDataInfo if and only if we are going to dump the
2432 * table data; the "dump" flag in such objects isn't used.
2435 makeTableDataInfo(DumpOptions
*dopt
, TableInfo
*tbinfo
)
2437 TableDataInfo
*tdinfo
;
2440 * Nothing to do if we already decided to dump the table. This will
2441 * happen for "config" tables.
2443 if (tbinfo
->dataObj
!= NULL
)
2446 /* Skip VIEWs (no data to dump) */
2447 if (tbinfo
->relkind
== RELKIND_VIEW
)
2449 /* Skip FOREIGN TABLEs (no data to dump) */
2450 if (tbinfo
->relkind
== RELKIND_FOREIGN_TABLE
)
2452 /* Skip partitioned tables (data in partitions) */
2453 if (tbinfo
->relkind
== RELKIND_PARTITIONED_TABLE
)
2456 /* Don't dump data in unlogged tables, if so requested */
2457 if (tbinfo
->relpersistence
== RELPERSISTENCE_UNLOGGED
&&
2458 dopt
->no_unlogged_table_data
)
2461 /* Check that the data is not explicitly excluded */
2462 if (simple_oid_list_member(&tabledata_exclude_oids
,
2463 tbinfo
->dobj
.catId
.oid
))
2466 /* OK, let's dump it */
2467 tdinfo
= (TableDataInfo
*) pg_malloc(sizeof(TableDataInfo
));
2469 if (tbinfo
->relkind
== RELKIND_MATVIEW
)
2470 tdinfo
->dobj
.objType
= DO_REFRESH_MATVIEW
;
2471 else if (tbinfo
->relkind
== RELKIND_SEQUENCE
)
2472 tdinfo
->dobj
.objType
= DO_SEQUENCE_SET
;
2474 tdinfo
->dobj
.objType
= DO_TABLE_DATA
;
2477 * Note: use tableoid 0 so that this object won't be mistaken for
2478 * something that pg_depend entries apply to.
2480 tdinfo
->dobj
.catId
.tableoid
= 0;
2481 tdinfo
->dobj
.catId
.oid
= tbinfo
->dobj
.catId
.oid
;
2482 AssignDumpId(&tdinfo
->dobj
);
2483 tdinfo
->dobj
.name
= tbinfo
->dobj
.name
;
2484 tdinfo
->dobj
.namespace = tbinfo
->dobj
.namespace;
2485 tdinfo
->tdtable
= tbinfo
;
2486 tdinfo
->filtercond
= NULL
; /* might get set later */
2487 addObjectDependency(&tdinfo
->dobj
, tbinfo
->dobj
.dumpId
);
2489 tbinfo
->dataObj
= tdinfo
;
2491 /* Make sure that we'll collect per-column info for this table. */
2492 tbinfo
->interesting
= true;
2496 * The refresh for a materialized view must be dependent on the refresh for
2497 * any materialized view that this one is dependent on.
2499 * This must be called after all the objects are created, but before they are
2503 buildMatViewRefreshDependencies(Archive
*fout
)
2513 /* No Mat Views before 9.3. */
2514 if (fout
->remoteVersion
< 90300)
2517 query
= createPQExpBuffer();
2519 appendPQExpBufferStr(query
, "WITH RECURSIVE w AS "
2521 "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2522 "FROM pg_depend d1 "
2523 "JOIN pg_class c1 ON c1.oid = d1.objid "
2524 "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW
)
2525 " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2526 "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2527 "AND d2.objid = r1.oid "
2528 "AND d2.refobjid <> d1.objid "
2529 "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2530 "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW
) ","
2531 CppAsString2(RELKIND_VIEW
) ") "
2532 "WHERE d1.classid = 'pg_class'::regclass "
2534 "SELECT w.objid, d3.refobjid, c3.relkind "
2536 "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2537 "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2538 "AND d3.objid = r3.oid "
2539 "AND d3.refobjid <> w.refobjid "
2540 "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2541 "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW
) ","
2542 CppAsString2(RELKIND_VIEW
) ") "
2544 "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2546 "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW
));
2548 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
2550 ntups
= PQntuples(res
);
2552 i_classid
= PQfnumber(res
, "classid");
2553 i_objid
= PQfnumber(res
, "objid");
2554 i_refobjid
= PQfnumber(res
, "refobjid");
2556 for (i
= 0; i
< ntups
; i
++)
2560 DumpableObject
*dobj
;
2561 DumpableObject
*refdobj
;
2563 TableInfo
*reftbinfo
;
2565 objId
.tableoid
= atooid(PQgetvalue(res
, i
, i_classid
));
2566 objId
.oid
= atooid(PQgetvalue(res
, i
, i_objid
));
2567 refobjId
.tableoid
= objId
.tableoid
;
2568 refobjId
.oid
= atooid(PQgetvalue(res
, i
, i_refobjid
));
2570 dobj
= findObjectByCatalogId(objId
);
2574 Assert(dobj
->objType
== DO_TABLE
);
2575 tbinfo
= (TableInfo
*) dobj
;
2576 Assert(tbinfo
->relkind
== RELKIND_MATVIEW
);
2577 dobj
= (DumpableObject
*) tbinfo
->dataObj
;
2580 Assert(dobj
->objType
== DO_REFRESH_MATVIEW
);
2582 refdobj
= findObjectByCatalogId(refobjId
);
2583 if (refdobj
== NULL
)
2586 Assert(refdobj
->objType
== DO_TABLE
);
2587 reftbinfo
= (TableInfo
*) refdobj
;
2588 Assert(reftbinfo
->relkind
== RELKIND_MATVIEW
);
2589 refdobj
= (DumpableObject
*) reftbinfo
->dataObj
;
2590 if (refdobj
== NULL
)
2592 Assert(refdobj
->objType
== DO_REFRESH_MATVIEW
);
2594 addObjectDependency(dobj
, refdobj
->dumpId
);
2596 if (!reftbinfo
->relispopulated
)
2597 tbinfo
->relispopulated
= false;
2602 destroyPQExpBuffer(query
);
2606 * getTableDataFKConstraints -
2607 * add dump-order dependencies reflecting foreign key constraints
2609 * This code is executed only in a data-only dump --- in schema+data dumps
2610 * we handle foreign key issues by not creating the FK constraints until
2611 * after the data is loaded. In a data-only dump, however, we want to
2612 * order the table data objects in such a way that a table's referenced
2613 * tables are restored first. (In the presence of circular references or
2614 * self-references this may be impossible; we'll detect and complain about
2615 * that during the dependency sorting step.)
2618 getTableDataFKConstraints(void)
2620 DumpableObject
**dobjs
;
2624 /* Search through all the dumpable objects for FK constraints */
2625 getDumpableObjects(&dobjs
, &numObjs
);
2626 for (i
= 0; i
< numObjs
; i
++)
2628 if (dobjs
[i
]->objType
== DO_FK_CONSTRAINT
)
2630 ConstraintInfo
*cinfo
= (ConstraintInfo
*) dobjs
[i
];
2633 /* Not interesting unless both tables are to be dumped */
2634 if (cinfo
->contable
== NULL
||
2635 cinfo
->contable
->dataObj
== NULL
)
2637 ftable
= findTableByOid(cinfo
->confrelid
);
2638 if (ftable
== NULL
||
2639 ftable
->dataObj
== NULL
)
2643 * Okay, make referencing table's TABLE_DATA object depend on the
2644 * referenced table's TABLE_DATA object.
2646 addObjectDependency(&cinfo
->contable
->dataObj
->dobj
,
2647 ftable
->dataObj
->dobj
.dumpId
);
2655 * guessConstraintInheritance:
2656 * In pre-8.4 databases, we can't tell for certain which constraints
2657 * are inherited. We assume a CHECK constraint is inherited if its name
2658 * matches the name of any constraint in the parent. Originally this code
2659 * tried to compare the expression texts, but that can fail for various
2660 * reasons --- for example, if the parent and child tables are in different
2661 * schemas, reverse-listing of function calls may produce different text
2662 * (schema-qualified or not) depending on search path.
2664 * In 8.4 and up we can rely on the conislocal field to decide which
2665 * constraints must be dumped; much safer.
2667 * This function assumes all conislocal flags were initialized to true.
2668 * It clears the flag on anything that seems to be inherited.
2671 guessConstraintInheritance(TableInfo
*tblinfo
, int numTables
)
2677 for (i
= 0; i
< numTables
; i
++)
2679 TableInfo
*tbinfo
= &(tblinfo
[i
]);
2681 TableInfo
**parents
;
2684 /* Sequences and views never have parents */
2685 if (tbinfo
->relkind
== RELKIND_SEQUENCE
||
2686 tbinfo
->relkind
== RELKIND_VIEW
)
2689 /* Don't bother computing anything for non-target tables, either */
2690 if (!(tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
2693 numParents
= tbinfo
->numParents
;
2694 parents
= tbinfo
->parents
;
2696 if (numParents
== 0)
2697 continue; /* nothing to see here, move along */
2699 /* scan for inherited CHECK constraints */
2700 for (j
= 0; j
< tbinfo
->ncheck
; j
++)
2702 ConstraintInfo
*constr
;
2704 constr
= &(tbinfo
->checkexprs
[j
]);
2706 for (k
= 0; k
< numParents
; k
++)
2710 parent
= parents
[k
];
2711 for (l
= 0; l
< parent
->ncheck
; l
++)
2713 ConstraintInfo
*pconstr
= &(parent
->checkexprs
[l
]);
2715 if (strcmp(pconstr
->dobj
.name
, constr
->dobj
.name
) == 0)
2717 constr
->conislocal
= false;
2721 if (!constr
->conislocal
)
2731 * dump the database definition
2734 dumpDatabase(Archive
*fout
)
2736 DumpOptions
*dopt
= fout
->dopt
;
2737 PQExpBuffer dbQry
= createPQExpBuffer();
2738 PQExpBuffer delQry
= createPQExpBuffer();
2739 PQExpBuffer creaQry
= createPQExpBuffer();
2740 PQExpBuffer labelq
= createPQExpBuffer();
2741 PGconn
*conn
= GetConnection(fout
);
2759 const char *datname
,
2773 pg_log_info("saving database definition");
2776 * Fetch the database-level properties for this database.
2778 * The order in which privileges are in the ACL string (the order they
2779 * have been GRANT'd in, which the backend maintains) must be preserved to
2780 * ensure that GRANTs WITH GRANT OPTION and subsequent GRANTs based on
2781 * those are dumped in the correct order. Note that initial privileges
2782 * (pg_init_privs) are not supported on databases, so this logic cannot
2783 * make use of buildACLQueries().
2785 if (fout
->remoteVersion
>= 90600)
2787 appendPQExpBuffer(dbQry
, "SELECT tableoid, oid, datname, "
2788 "(%s datdba) AS dba, "
2789 "pg_encoding_to_char(encoding) AS encoding, "
2790 "datcollate, datctype, datfrozenxid, datminmxid, "
2791 "(SELECT array_agg(acl ORDER BY row_n) FROM "
2792 " (SELECT acl, row_n FROM "
2793 " unnest(coalesce(datacl,acldefault('d',datdba))) "
2794 " WITH ORDINALITY AS perm(acl,row_n) "
2795 " WHERE NOT EXISTS ( "
2797 " FROM unnest(acldefault('d',datdba)) "
2798 " AS init(init_acl) "
2799 " WHERE acl = init_acl)) AS datacls) "
2801 "(SELECT array_agg(acl ORDER BY row_n) FROM "
2802 " (SELECT acl, row_n FROM "
2803 " unnest(acldefault('d',datdba)) "
2804 " WITH ORDINALITY AS initp(acl,row_n) "
2805 " WHERE NOT EXISTS ( "
2807 " FROM unnest(coalesce(datacl,acldefault('d',datdba))) "
2808 " AS permp(orig_acl) "
2809 " WHERE acl = orig_acl)) AS rdatacls) "
2811 "datistemplate, datconnlimit, "
2812 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2813 "shobj_description(oid, 'pg_database') AS description "
2816 "WHERE datname = current_database()",
2819 else if (fout
->remoteVersion
>= 90300)
2821 appendPQExpBuffer(dbQry
, "SELECT tableoid, oid, datname, "
2822 "(%s datdba) AS dba, "
2823 "pg_encoding_to_char(encoding) AS encoding, "
2824 "datcollate, datctype, datfrozenxid, datminmxid, "
2825 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2826 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2827 "shobj_description(oid, 'pg_database') AS description "
2830 "WHERE datname = current_database()",
2833 else if (fout
->remoteVersion
>= 80400)
2835 appendPQExpBuffer(dbQry
, "SELECT tableoid, oid, datname, "
2836 "(%s datdba) AS dba, "
2837 "pg_encoding_to_char(encoding) AS encoding, "
2838 "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
2839 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2840 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2841 "shobj_description(oid, 'pg_database') AS description "
2844 "WHERE datname = current_database()",
2847 else if (fout
->remoteVersion
>= 80200)
2849 appendPQExpBuffer(dbQry
, "SELECT tableoid, oid, datname, "
2850 "(%s datdba) AS dba, "
2851 "pg_encoding_to_char(encoding) AS encoding, "
2852 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2853 "datacl, '' as rdatacl, datistemplate, datconnlimit, "
2854 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
2855 "shobj_description(oid, 'pg_database') AS description "
2858 "WHERE datname = current_database()",
2863 appendPQExpBuffer(dbQry
, "SELECT tableoid, oid, datname, "
2864 "(%s datdba) AS dba, "
2865 "pg_encoding_to_char(encoding) AS encoding, "
2866 "NULL AS datcollate, NULL AS datctype, datfrozenxid, 0 AS datminmxid, "
2867 "datacl, '' as rdatacl, datistemplate, "
2868 "-1 as datconnlimit, "
2869 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace "
2871 "WHERE datname = current_database()",
2875 res
= ExecuteSqlQueryForSingleRow(fout
, dbQry
->data
);
2877 i_tableoid
= PQfnumber(res
, "tableoid");
2878 i_oid
= PQfnumber(res
, "oid");
2879 i_datname
= PQfnumber(res
, "datname");
2880 i_dba
= PQfnumber(res
, "dba");
2881 i_encoding
= PQfnumber(res
, "encoding");
2882 i_collate
= PQfnumber(res
, "datcollate");
2883 i_ctype
= PQfnumber(res
, "datctype");
2884 i_frozenxid
= PQfnumber(res
, "datfrozenxid");
2885 i_minmxid
= PQfnumber(res
, "datminmxid");
2886 i_datacl
= PQfnumber(res
, "datacl");
2887 i_rdatacl
= PQfnumber(res
, "rdatacl");
2888 i_datistemplate
= PQfnumber(res
, "datistemplate");
2889 i_datconnlimit
= PQfnumber(res
, "datconnlimit");
2890 i_tablespace
= PQfnumber(res
, "tablespace");
2892 dbCatId
.tableoid
= atooid(PQgetvalue(res
, 0, i_tableoid
));
2893 dbCatId
.oid
= atooid(PQgetvalue(res
, 0, i_oid
));
2894 datname
= PQgetvalue(res
, 0, i_datname
);
2895 dba
= PQgetvalue(res
, 0, i_dba
);
2896 encoding
= PQgetvalue(res
, 0, i_encoding
);
2897 collate
= PQgetvalue(res
, 0, i_collate
);
2898 ctype
= PQgetvalue(res
, 0, i_ctype
);
2899 frozenxid
= atooid(PQgetvalue(res
, 0, i_frozenxid
));
2900 minmxid
= atooid(PQgetvalue(res
, 0, i_minmxid
));
2901 datacl
= PQgetvalue(res
, 0, i_datacl
);
2902 rdatacl
= PQgetvalue(res
, 0, i_rdatacl
);
2903 datistemplate
= PQgetvalue(res
, 0, i_datistemplate
);
2904 datconnlimit
= PQgetvalue(res
, 0, i_datconnlimit
);
2905 tablespace
= PQgetvalue(res
, 0, i_tablespace
);
2907 qdatname
= pg_strdup(fmtId(datname
));
2910 * Prepare the CREATE DATABASE command. We must specify encoding, locale,
2911 * and tablespace since those can't be altered later. Other DB properties
2912 * are left to the DATABASE PROPERTIES entry, so that they can be applied
2913 * after reconnecting to the target DB.
2915 appendPQExpBuffer(creaQry
, "CREATE DATABASE %s WITH TEMPLATE = template0",
2917 if (strlen(encoding
) > 0)
2919 appendPQExpBufferStr(creaQry
, " ENCODING = ");
2920 appendStringLiteralAH(creaQry
, encoding
, fout
);
2922 if (strlen(collate
) > 0)
2924 appendPQExpBufferStr(creaQry
, " LC_COLLATE = ");
2925 appendStringLiteralAH(creaQry
, collate
, fout
);
2927 if (strlen(ctype
) > 0)
2929 appendPQExpBufferStr(creaQry
, " LC_CTYPE = ");
2930 appendStringLiteralAH(creaQry
, ctype
, fout
);
2934 * Note: looking at dopt->outputNoTablespaces here is completely the wrong
2935 * thing; the decision whether to specify a tablespace should be left till
2936 * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
2937 * label the DATABASE entry with the tablespace and let the normal
2938 * tablespace selection logic work ... but CREATE DATABASE doesn't pay
2939 * attention to default_tablespace, so that won't work.
2941 if (strlen(tablespace
) > 0 && strcmp(tablespace
, "pg_default") != 0 &&
2942 !dopt
->outputNoTablespaces
)
2943 appendPQExpBuffer(creaQry
, " TABLESPACE = %s",
2945 appendPQExpBufferStr(creaQry
, ";\n");
2947 appendPQExpBuffer(delQry
, "DROP DATABASE %s;\n",
2950 dbDumpId
= createDumpId();
2953 dbCatId
, /* catalog ID */
2954 dbDumpId
, /* dump ID */
2955 ARCHIVE_OPTS(.tag
= datname
,
2957 .description
= "DATABASE",
2958 .section
= SECTION_PRE_DATA
,
2959 .createStmt
= creaQry
->data
,
2960 .dropStmt
= delQry
->data
));
2962 /* Compute correct tag for archive entry */
2963 appendPQExpBuffer(labelq
, "DATABASE %s", qdatname
);
2965 /* Dump DB comment if any */
2966 if (fout
->remoteVersion
>= 80200)
2969 * 8.2 and up keep comments on shared objects in a shared table, so we
2970 * cannot use the dumpComment() code used for other database objects.
2971 * Be careful that the ArchiveEntry parameters match that function.
2973 char *comment
= PQgetvalue(res
, 0, PQfnumber(res
, "description"));
2975 if (comment
&& *comment
&& !dopt
->no_comments
)
2977 resetPQExpBuffer(dbQry
);
2980 * Generates warning when loaded into a differently-named
2983 appendPQExpBuffer(dbQry
, "COMMENT ON DATABASE %s IS ", qdatname
);
2984 appendStringLiteralAH(dbQry
, comment
, fout
);
2985 appendPQExpBufferStr(dbQry
, ";\n");
2987 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
2988 ARCHIVE_OPTS(.tag
= labelq
->data
,
2990 .description
= "COMMENT",
2991 .section
= SECTION_NONE
,
2992 .createStmt
= dbQry
->data
,
2999 dumpComment(fout
, "DATABASE", qdatname
, NULL
, dba
,
3000 dbCatId
, 0, dbDumpId
);
3003 /* Dump DB security label, if enabled */
3004 if (!dopt
->no_security_labels
&& fout
->remoteVersion
>= 90200)
3007 PQExpBuffer seclabelQry
;
3009 seclabelQry
= createPQExpBuffer();
3011 buildShSecLabelQuery(conn
, "pg_database", dbCatId
.oid
, seclabelQry
);
3012 shres
= ExecuteSqlQuery(fout
, seclabelQry
->data
, PGRES_TUPLES_OK
);
3013 resetPQExpBuffer(seclabelQry
);
3014 emitShSecLabels(conn
, shres
, seclabelQry
, "DATABASE", datname
);
3015 if (seclabelQry
->len
> 0)
3016 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
3017 ARCHIVE_OPTS(.tag
= labelq
->data
,
3019 .description
= "SECURITY LABEL",
3020 .section
= SECTION_NONE
,
3021 .createStmt
= seclabelQry
->data
,
3024 destroyPQExpBuffer(seclabelQry
);
3029 * Dump ACL if any. Note that we do not support initial privileges
3030 * (pg_init_privs) on databases.
3032 dumpACL(fout
, dbDumpId
, InvalidDumpId
, "DATABASE",
3033 qdatname
, NULL
, NULL
,
3034 dba
, datacl
, rdatacl
, "", "");
3037 * Now construct a DATABASE PROPERTIES archive entry to restore any
3038 * non-default database-level properties. (The reason this must be
3039 * separate is that we cannot put any additional commands into the TOC
3040 * entry that has CREATE DATABASE. pg_restore would execute such a group
3041 * in an implicit transaction block, and the backend won't allow CREATE
3042 * DATABASE in that context.)
3044 resetPQExpBuffer(creaQry
);
3045 resetPQExpBuffer(delQry
);
3047 if (strlen(datconnlimit
) > 0 && strcmp(datconnlimit
, "-1") != 0)
3048 appendPQExpBuffer(creaQry
, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
3049 qdatname
, datconnlimit
);
3051 if (strcmp(datistemplate
, "t") == 0)
3053 appendPQExpBuffer(creaQry
, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
3057 * The backend won't accept DROP DATABASE on a template database. We
3058 * can deal with that by removing the template marking before the DROP
3059 * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
3060 * since no such command is currently supported, fake it with a direct
3061 * UPDATE on pg_database.
3063 appendPQExpBufferStr(delQry
, "UPDATE pg_catalog.pg_database "
3064 "SET datistemplate = false WHERE datname = ");
3065 appendStringLiteralAH(delQry
, datname
, fout
);
3066 appendPQExpBufferStr(delQry
, ";\n");
3069 /* Add database-specific SET options */
3070 dumpDatabaseConfig(fout
, creaQry
, datname
, dbCatId
.oid
);
3073 * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
3074 * entry, too, for lack of a better place.
3076 if (dopt
->binary_upgrade
)
3078 appendPQExpBufferStr(creaQry
, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
3079 appendPQExpBuffer(creaQry
, "UPDATE pg_catalog.pg_database\n"
3080 "SET datfrozenxid = '%u', datminmxid = '%u'\n"
3082 frozenxid
, minmxid
);
3083 appendStringLiteralAH(creaQry
, datname
, fout
);
3084 appendPQExpBufferStr(creaQry
, ";\n");
3087 if (creaQry
->len
> 0)
3088 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
3089 ARCHIVE_OPTS(.tag
= datname
,
3091 .description
= "DATABASE PROPERTIES",
3092 .section
= SECTION_PRE_DATA
,
3093 .createStmt
= creaQry
->data
,
3094 .dropStmt
= delQry
->data
,
3095 .deps
= &dbDumpId
));
3098 * pg_largeobject comes from the old system intact, so set its
3099 * relfrozenxids and relminmxids.
3101 if (dopt
->binary_upgrade
)
3104 PQExpBuffer loFrozenQry
= createPQExpBuffer();
3105 PQExpBuffer loOutQry
= createPQExpBuffer();
3112 if (fout
->remoteVersion
>= 90300)
3113 appendPQExpBuffer(loFrozenQry
, "SELECT relfrozenxid, relminmxid\n"
3114 "FROM pg_catalog.pg_class\n"
3115 "WHERE oid = %u;\n",
3116 LargeObjectRelationId
);
3118 appendPQExpBuffer(loFrozenQry
, "SELECT relfrozenxid, 0 AS relminmxid\n"
3119 "FROM pg_catalog.pg_class\n"
3120 "WHERE oid = %u;\n",
3121 LargeObjectRelationId
);
3123 lo_res
= ExecuteSqlQueryForSingleRow(fout
, loFrozenQry
->data
);
3125 i_relfrozenxid
= PQfnumber(lo_res
, "relfrozenxid");
3126 i_relminmxid
= PQfnumber(lo_res
, "relminmxid");
3128 appendPQExpBufferStr(loOutQry
, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
3129 appendPQExpBuffer(loOutQry
, "UPDATE pg_catalog.pg_class\n"
3130 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
3131 "WHERE oid = %u;\n",
3132 atooid(PQgetvalue(lo_res
, 0, i_relfrozenxid
)),
3133 atooid(PQgetvalue(lo_res
, 0, i_relminmxid
)),
3134 LargeObjectRelationId
);
3135 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
3136 ARCHIVE_OPTS(.tag
= "pg_largeobject",
3137 .description
= "pg_largeobject",
3138 .section
= SECTION_PRE_DATA
,
3139 .createStmt
= loOutQry
->data
));
3143 destroyPQExpBuffer(loFrozenQry
);
3144 destroyPQExpBuffer(loOutQry
);
3150 destroyPQExpBuffer(dbQry
);
3151 destroyPQExpBuffer(delQry
);
3152 destroyPQExpBuffer(creaQry
);
3153 destroyPQExpBuffer(labelq
);
3157 * Collect any database-specific or role-and-database-specific SET options
3158 * for this database, and append them to outbuf.
3161 dumpDatabaseConfig(Archive
*AH
, PQExpBuffer outbuf
,
3162 const char *dbname
, Oid dboid
)
3164 PGconn
*conn
= GetConnection(AH
);
3165 PQExpBuffer buf
= createPQExpBuffer();
3170 * First collect database-specific options. Pre-8.4 server versions lack
3171 * unnest(), so we do this the hard way by querying once per subscript.
3175 if (AH
->remoteVersion
>= 90000)
3176 printfPQExpBuffer(buf
, "SELECT setconfig[%d] FROM pg_db_role_setting "
3177 "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3180 printfPQExpBuffer(buf
, "SELECT datconfig[%d] FROM pg_database WHERE oid = '%u'::oid", count
, dboid
);
3182 res
= ExecuteSqlQuery(AH
, buf
->data
, PGRES_TUPLES_OK
);
3184 if (PQntuples(res
) == 1 &&
3185 !PQgetisnull(res
, 0, 0))
3187 makeAlterConfigCommand(conn
, PQgetvalue(res
, 0, 0),
3188 "DATABASE", dbname
, NULL
, NULL
,
3200 /* Now look for role-and-database-specific options */
3201 if (AH
->remoteVersion
>= 90000)
3203 /* Here we can assume we have unnest() */
3204 printfPQExpBuffer(buf
, "SELECT rolname, unnest(setconfig) "
3205 "FROM pg_db_role_setting s, pg_roles r "
3206 "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3209 res
= ExecuteSqlQuery(AH
, buf
->data
, PGRES_TUPLES_OK
);
3211 if (PQntuples(res
) > 0)
3215 for (i
= 0; i
< PQntuples(res
); i
++)
3216 makeAlterConfigCommand(conn
, PQgetvalue(res
, i
, 1),
3217 "ROLE", PQgetvalue(res
, i
, 0),
3225 destroyPQExpBuffer(buf
);
3229 * dumpEncoding: put the correct encoding into the archive
3232 dumpEncoding(Archive
*AH
)
3234 const char *encname
= pg_encoding_to_char(AH
->encoding
);
3235 PQExpBuffer qry
= createPQExpBuffer();
3237 pg_log_info("saving encoding = %s", encname
);
3239 appendPQExpBufferStr(qry
, "SET client_encoding = ");
3240 appendStringLiteralAH(qry
, encname
, AH
);
3241 appendPQExpBufferStr(qry
, ";\n");
3243 ArchiveEntry(AH
, nilCatalogId
, createDumpId(),
3244 ARCHIVE_OPTS(.tag
= "ENCODING",
3245 .description
= "ENCODING",
3246 .section
= SECTION_PRE_DATA
,
3247 .createStmt
= qry
->data
));
3249 destroyPQExpBuffer(qry
);
3254 * dumpStdStrings: put the correct escape string behavior into the archive
3257 dumpStdStrings(Archive
*AH
)
3259 const char *stdstrings
= AH
->std_strings
? "on" : "off";
3260 PQExpBuffer qry
= createPQExpBuffer();
3262 pg_log_info("saving standard_conforming_strings = %s",
3265 appendPQExpBuffer(qry
, "SET standard_conforming_strings = '%s';\n",
3268 ArchiveEntry(AH
, nilCatalogId
, createDumpId(),
3269 ARCHIVE_OPTS(.tag
= "STDSTRINGS",
3270 .description
= "STDSTRINGS",
3271 .section
= SECTION_PRE_DATA
,
3272 .createStmt
= qry
->data
));
3274 destroyPQExpBuffer(qry
);
3278 * dumpSearchPath: record the active search_path in the archive
3281 dumpSearchPath(Archive
*AH
)
3283 PQExpBuffer qry
= createPQExpBuffer();
3284 PQExpBuffer path
= createPQExpBuffer();
3286 char **schemanames
= NULL
;
3287 int nschemanames
= 0;
3291 * We use the result of current_schemas(), not the search_path GUC,
3292 * because that might contain wildcards such as "$user", which won't
3293 * necessarily have the same value during restore. Also, this way avoids
3294 * listing schemas that may appear in search_path but not actually exist,
3295 * which seems like a prudent exclusion.
3297 res
= ExecuteSqlQueryForSingleRow(AH
,
3298 "SELECT pg_catalog.current_schemas(false)");
3300 if (!parsePGArray(PQgetvalue(res
, 0, 0), &schemanames
, &nschemanames
))
3301 fatal("could not parse result of current_schemas()");
3304 * We use set_config(), not a simple "SET search_path" command, because
3305 * the latter has less-clean behavior if the search path is empty. While
3306 * that's likely to get fixed at some point, it seems like a good idea to
3307 * be as backwards-compatible as possible in what we put into archives.
3309 for (i
= 0; i
< nschemanames
; i
++)
3312 appendPQExpBufferStr(path
, ", ");
3313 appendPQExpBufferStr(path
, fmtId(schemanames
[i
]));
3316 appendPQExpBufferStr(qry
, "SELECT pg_catalog.set_config('search_path', ");
3317 appendStringLiteralAH(qry
, path
->data
, AH
);
3318 appendPQExpBufferStr(qry
, ", false);\n");
3320 pg_log_info("saving search_path = %s", path
->data
);
3322 ArchiveEntry(AH
, nilCatalogId
, createDumpId(),
3323 ARCHIVE_OPTS(.tag
= "SEARCHPATH",
3324 .description
= "SEARCHPATH",
3325 .section
= SECTION_PRE_DATA
,
3326 .createStmt
= qry
->data
));
3328 /* Also save it in AH->searchpath, in case we're doing plain text dump */
3329 AH
->searchpath
= pg_strdup(qry
->data
);
3334 destroyPQExpBuffer(qry
);
3335 destroyPQExpBuffer(path
);
3341 * Collect schema-level data about large objects
3344 getBlobs(Archive
*fout
)
3346 DumpOptions
*dopt
= fout
->dopt
;
3347 PQExpBuffer blobQry
= createPQExpBuffer();
3349 DumpableObject
*bdata
;
3360 pg_log_info("reading large objects");
3362 /* Fetch BLOB OIDs, and owner/ACL data if >= 9.0 */
3363 if (fout
->remoteVersion
>= 90600)
3365 PQExpBuffer acl_subquery
= createPQExpBuffer();
3366 PQExpBuffer racl_subquery
= createPQExpBuffer();
3367 PQExpBuffer init_acl_subquery
= createPQExpBuffer();
3368 PQExpBuffer init_racl_subquery
= createPQExpBuffer();
3370 buildACLQueries(acl_subquery
, racl_subquery
, init_acl_subquery
,
3371 init_racl_subquery
, "l.lomacl", "l.lomowner", "'L'",
3372 dopt
->binary_upgrade
);
3374 appendPQExpBuffer(blobQry
,
3375 "SELECT l.oid, (%s l.lomowner) AS rolname, "
3378 "%s AS initlomacl, "
3379 "%s AS initrlomacl "
3380 "FROM pg_largeobject_metadata l "
3381 "LEFT JOIN pg_init_privs pip ON "
3382 "(l.oid = pip.objoid "
3383 "AND pip.classoid = 'pg_largeobject'::regclass "
3384 "AND pip.objsubid = 0) ",
3387 racl_subquery
->data
,
3388 init_acl_subquery
->data
,
3389 init_racl_subquery
->data
);
3391 destroyPQExpBuffer(acl_subquery
);
3392 destroyPQExpBuffer(racl_subquery
);
3393 destroyPQExpBuffer(init_acl_subquery
);
3394 destroyPQExpBuffer(init_racl_subquery
);
3396 else if (fout
->remoteVersion
>= 90000)
3397 appendPQExpBuffer(blobQry
,
3398 "SELECT oid, (%s lomowner) AS rolname, lomacl, "
3399 "NULL AS rlomacl, NULL AS initlomacl, "
3400 "NULL AS initrlomacl "
3401 " FROM pg_largeobject_metadata",
3404 appendPQExpBufferStr(blobQry
,
3405 "SELECT DISTINCT loid AS oid, "
3406 "NULL::name AS rolname, NULL::oid AS lomacl, "
3407 "NULL::oid AS rlomacl, NULL::oid AS initlomacl, "
3408 "NULL::oid AS initrlomacl "
3409 " FROM pg_largeobject");
3411 res
= ExecuteSqlQuery(fout
, blobQry
->data
, PGRES_TUPLES_OK
);
3413 i_oid
= PQfnumber(res
, "oid");
3414 i_lomowner
= PQfnumber(res
, "rolname");
3415 i_lomacl
= PQfnumber(res
, "lomacl");
3416 i_rlomacl
= PQfnumber(res
, "rlomacl");
3417 i_initlomacl
= PQfnumber(res
, "initlomacl");
3418 i_initrlomacl
= PQfnumber(res
, "initrlomacl");
3420 ntups
= PQntuples(res
);
3423 * Each large object has its own BLOB archive entry.
3425 binfo
= (BlobInfo
*) pg_malloc(ntups
* sizeof(BlobInfo
));
3427 for (i
= 0; i
< ntups
; i
++)
3429 binfo
[i
].dobj
.objType
= DO_BLOB
;
3430 binfo
[i
].dobj
.catId
.tableoid
= LargeObjectRelationId
;
3431 binfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
3432 AssignDumpId(&binfo
[i
].dobj
);
3434 binfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_oid
));
3435 binfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_lomowner
));
3436 binfo
[i
].blobacl
= pg_strdup(PQgetvalue(res
, i
, i_lomacl
));
3437 binfo
[i
].rblobacl
= pg_strdup(PQgetvalue(res
, i
, i_rlomacl
));
3438 binfo
[i
].initblobacl
= pg_strdup(PQgetvalue(res
, i
, i_initlomacl
));
3439 binfo
[i
].initrblobacl
= pg_strdup(PQgetvalue(res
, i
, i_initrlomacl
));
3441 if (PQgetisnull(res
, i
, i_lomacl
) &&
3442 PQgetisnull(res
, i
, i_rlomacl
) &&
3443 PQgetisnull(res
, i
, i_initlomacl
) &&
3444 PQgetisnull(res
, i
, i_initrlomacl
))
3445 binfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
3448 * In binary-upgrade mode for blobs, we do *not* dump out the blob
3449 * data, as it will be copied by pg_upgrade, which simply copies the
3450 * pg_largeobject table. We *do* however dump out anything but the
3451 * data, as pg_upgrade copies just pg_largeobject, but not
3452 * pg_largeobject_metadata, after the dump is restored.
3454 if (dopt
->binary_upgrade
)
3455 binfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_DATA
;
3459 * If we have any large objects, a "BLOBS" archive entry is needed. This
3460 * is just a placeholder for sorting; it carries no data now.
3464 bdata
= (DumpableObject
*) pg_malloc(sizeof(DumpableObject
));
3465 bdata
->objType
= DO_BLOB_DATA
;
3466 bdata
->catId
= nilCatalogId
;
3467 AssignDumpId(bdata
);
3468 bdata
->name
= pg_strdup("BLOBS");
3472 destroyPQExpBuffer(blobQry
);
3478 * dump the definition (metadata) of the given large object
3481 dumpBlob(Archive
*fout
, BlobInfo
*binfo
)
3483 PQExpBuffer cquery
= createPQExpBuffer();
3484 PQExpBuffer dquery
= createPQExpBuffer();
3486 appendPQExpBuffer(cquery
,
3487 "SELECT pg_catalog.lo_create('%s');\n",
3490 appendPQExpBuffer(dquery
,
3491 "SELECT pg_catalog.lo_unlink('%s');\n",
3494 if (binfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
3495 ArchiveEntry(fout
, binfo
->dobj
.catId
, binfo
->dobj
.dumpId
,
3496 ARCHIVE_OPTS(.tag
= binfo
->dobj
.name
,
3497 .owner
= binfo
->rolname
,
3498 .description
= "BLOB",
3499 .section
= SECTION_PRE_DATA
,
3500 .createStmt
= cquery
->data
,
3501 .dropStmt
= dquery
->data
));
3503 /* Dump comment if any */
3504 if (binfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
3505 dumpComment(fout
, "LARGE OBJECT", binfo
->dobj
.name
,
3506 NULL
, binfo
->rolname
,
3507 binfo
->dobj
.catId
, 0, binfo
->dobj
.dumpId
);
3509 /* Dump security label if any */
3510 if (binfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
3511 dumpSecLabel(fout
, "LARGE OBJECT", binfo
->dobj
.name
,
3512 NULL
, binfo
->rolname
,
3513 binfo
->dobj
.catId
, 0, binfo
->dobj
.dumpId
);
3515 /* Dump ACL if any */
3516 if (binfo
->blobacl
&& (binfo
->dobj
.dump
& DUMP_COMPONENT_ACL
))
3517 dumpACL(fout
, binfo
->dobj
.dumpId
, InvalidDumpId
, "LARGE OBJECT",
3518 binfo
->dobj
.name
, NULL
,
3519 NULL
, binfo
->rolname
, binfo
->blobacl
, binfo
->rblobacl
,
3520 binfo
->initblobacl
, binfo
->initrblobacl
);
3522 destroyPQExpBuffer(cquery
);
3523 destroyPQExpBuffer(dquery
);
3528 * dump the data contents of all large objects
3531 dumpBlobs(Archive
*fout
, void *arg
)
3533 const char *blobQry
;
3534 const char *blobFetchQry
;
3535 PGconn
*conn
= GetConnection(fout
);
3537 char buf
[LOBBUFSIZE
];
3542 pg_log_info("saving large objects");
3545 * Currently, we re-fetch all BLOB OIDs using a cursor. Consider scanning
3546 * the already-in-memory dumpable objects instead...
3548 if (fout
->remoteVersion
>= 90000)
3550 "DECLARE bloboid CURSOR FOR "
3551 "SELECT oid FROM pg_largeobject_metadata ORDER BY 1";
3554 "DECLARE bloboid CURSOR FOR "
3555 "SELECT DISTINCT loid FROM pg_largeobject ORDER BY 1";
3557 ExecuteSqlStatement(fout
, blobQry
);
3559 /* Command to fetch from cursor */
3560 blobFetchQry
= "FETCH 1000 IN bloboid";
3565 res
= ExecuteSqlQuery(fout
, blobFetchQry
, PGRES_TUPLES_OK
);
3567 /* Process the tuples, if any */
3568 ntups
= PQntuples(res
);
3569 for (i
= 0; i
< ntups
; i
++)
3574 blobOid
= atooid(PQgetvalue(res
, i
, 0));
3576 loFd
= lo_open(conn
, blobOid
, INV_READ
);
3578 fatal("could not open large object %u: %s",
3579 blobOid
, PQerrorMessage(conn
));
3581 StartBlob(fout
, blobOid
);
3583 /* Now read it in chunks, sending data to archive */
3586 cnt
= lo_read(conn
, loFd
, buf
, LOBBUFSIZE
);
3588 fatal("error reading large object %u: %s",
3589 blobOid
, PQerrorMessage(conn
));
3591 WriteData(fout
, buf
, cnt
);
3594 lo_close(conn
, loFd
);
3596 EndBlob(fout
, blobOid
);
3600 } while (ntups
> 0);
3607 * get information about all RLS policies on dumpable tables.
3610 getPolicies(Archive
*fout
, TableInfo tblinfo
[], int numTables
)
3613 PQExpBuffer tbloids
;
3615 PolicyInfo
*polinfo
;
3621 int i_polpermissive
;
3629 /* No policies before 9.5 */
3630 if (fout
->remoteVersion
< 90500)
3633 query
= createPQExpBuffer();
3634 tbloids
= createPQExpBuffer();
3637 * Identify tables of interest, and check which ones have RLS enabled.
3639 appendPQExpBufferChar(tbloids
, '{');
3640 for (i
= 0; i
< numTables
; i
++)
3642 TableInfo
*tbinfo
= &tblinfo
[i
];
3644 /* Ignore row security on tables not to be dumped */
3645 if (!(tbinfo
->dobj
.dump
& DUMP_COMPONENT_POLICY
))
3648 /* It can't have RLS or policies if it's not a table */
3649 if (tbinfo
->relkind
!= RELKIND_RELATION
&&
3650 tbinfo
->relkind
!= RELKIND_PARTITIONED_TABLE
)
3653 /* Add it to the list of table OIDs to be probed below */
3654 if (tbloids
->len
> 1) /* do we have more than the '{'? */
3655 appendPQExpBufferChar(tbloids
, ',');
3656 appendPQExpBuffer(tbloids
, "%u", tbinfo
->dobj
.catId
.oid
);
3658 /* Is RLS enabled? (That's separate from whether it has policies) */
3662 * We represent RLS being enabled on a table by creating a
3663 * PolicyInfo object with null polname.
3665 * Note: use tableoid 0 so that this object won't be mistaken for
3666 * something that pg_depend entries apply to.
3668 polinfo
= pg_malloc(sizeof(PolicyInfo
));
3669 polinfo
->dobj
.objType
= DO_POLICY
;
3670 polinfo
->dobj
.catId
.tableoid
= 0;
3671 polinfo
->dobj
.catId
.oid
= tbinfo
->dobj
.catId
.oid
;
3672 AssignDumpId(&polinfo
->dobj
);
3673 polinfo
->dobj
.namespace = tbinfo
->dobj
.namespace;
3674 polinfo
->dobj
.name
= pg_strdup(tbinfo
->dobj
.name
);
3675 polinfo
->poltable
= tbinfo
;
3676 polinfo
->polname
= NULL
;
3677 polinfo
->polcmd
= '\0';
3678 polinfo
->polpermissive
= 0;
3679 polinfo
->polroles
= NULL
;
3680 polinfo
->polqual
= NULL
;
3681 polinfo
->polwithcheck
= NULL
;
3684 appendPQExpBufferChar(tbloids
, '}');
3687 * Now, read all RLS policies belonging to the tables of interest, and
3688 * create PolicyInfo objects for them. (Note that we must filter the
3689 * results server-side not locally, because we dare not apply pg_get_expr
3690 * to tables we don't have lock on.)
3692 pg_log_info("reading row-level security policies");
3694 printfPQExpBuffer(query
,
3695 "SELECT pol.oid, pol.tableoid, pol.polrelid, pol.polname, pol.polcmd, ");
3696 if (fout
->remoteVersion
>= 100000)
3697 appendPQExpBuffer(query
, "pol.polpermissive, ");
3699 appendPQExpBuffer(query
, "'t' as polpermissive, ");
3700 appendPQExpBuffer(query
,
3701 "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
3702 " pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(rolname) from pg_catalog.pg_roles WHERE oid = ANY(pol.polroles)), ', ') END AS polroles, "
3703 "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
3704 "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
3705 "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
3706 "JOIN pg_catalog.pg_policy pol ON (src.tbloid = pol.polrelid)",
3709 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
3711 ntups
= PQntuples(res
);
3714 i_oid
= PQfnumber(res
, "oid");
3715 i_tableoid
= PQfnumber(res
, "tableoid");
3716 i_polrelid
= PQfnumber(res
, "polrelid");
3717 i_polname
= PQfnumber(res
, "polname");
3718 i_polcmd
= PQfnumber(res
, "polcmd");
3719 i_polpermissive
= PQfnumber(res
, "polpermissive");
3720 i_polroles
= PQfnumber(res
, "polroles");
3721 i_polqual
= PQfnumber(res
, "polqual");
3722 i_polwithcheck
= PQfnumber(res
, "polwithcheck");
3724 polinfo
= pg_malloc(ntups
* sizeof(PolicyInfo
));
3726 for (j
= 0; j
< ntups
; j
++)
3728 Oid polrelid
= atooid(PQgetvalue(res
, j
, i_polrelid
));
3729 TableInfo
*tbinfo
= findTableByOid(polrelid
);
3731 polinfo
[j
].dobj
.objType
= DO_POLICY
;
3732 polinfo
[j
].dobj
.catId
.tableoid
=
3733 atooid(PQgetvalue(res
, j
, i_tableoid
));
3734 polinfo
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, i_oid
));
3735 AssignDumpId(&polinfo
[j
].dobj
);
3736 polinfo
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
3737 polinfo
[j
].poltable
= tbinfo
;
3738 polinfo
[j
].polname
= pg_strdup(PQgetvalue(res
, j
, i_polname
));
3739 polinfo
[j
].dobj
.name
= pg_strdup(polinfo
[j
].polname
);
3741 polinfo
[j
].polcmd
= *(PQgetvalue(res
, j
, i_polcmd
));
3742 polinfo
[j
].polpermissive
= *(PQgetvalue(res
, j
, i_polpermissive
)) == 't';
3744 if (PQgetisnull(res
, j
, i_polroles
))
3745 polinfo
[j
].polroles
= NULL
;
3747 polinfo
[j
].polroles
= pg_strdup(PQgetvalue(res
, j
, i_polroles
));
3749 if (PQgetisnull(res
, j
, i_polqual
))
3750 polinfo
[j
].polqual
= NULL
;
3752 polinfo
[j
].polqual
= pg_strdup(PQgetvalue(res
, j
, i_polqual
));
3754 if (PQgetisnull(res
, j
, i_polwithcheck
))
3755 polinfo
[j
].polwithcheck
= NULL
;
3757 polinfo
[j
].polwithcheck
3758 = pg_strdup(PQgetvalue(res
, j
, i_polwithcheck
));
3764 destroyPQExpBuffer(query
);
3765 destroyPQExpBuffer(tbloids
);
3770 * dump the definition of the given policy
3773 dumpPolicy(Archive
*fout
, PolicyInfo
*polinfo
)
3775 DumpOptions
*dopt
= fout
->dopt
;
3776 TableInfo
*tbinfo
= polinfo
->poltable
;
3779 PQExpBuffer polprefix
;
3788 * If polname is NULL, then this record is just indicating that ROW LEVEL
3789 * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
3790 * ROW LEVEL SECURITY.
3792 if (polinfo
->polname
== NULL
)
3794 query
= createPQExpBuffer();
3796 appendPQExpBuffer(query
, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
3797 fmtQualifiedDumpable(tbinfo
));
3800 * We must emit the ROW SECURITY object's dependency on its table
3801 * explicitly, because it will not match anything in pg_depend (unlike
3802 * the case for other PolicyInfo objects).
3804 if (polinfo
->dobj
.dump
& DUMP_COMPONENT_POLICY
)
3805 ArchiveEntry(fout
, polinfo
->dobj
.catId
, polinfo
->dobj
.dumpId
,
3806 ARCHIVE_OPTS(.tag
= polinfo
->dobj
.name
,
3807 .namespace = polinfo
->dobj
.namespace->dobj
.name
,
3808 .owner
= tbinfo
->rolname
,
3809 .description
= "ROW SECURITY",
3810 .section
= SECTION_POST_DATA
,
3811 .createStmt
= query
->data
,
3812 .deps
= &(tbinfo
->dobj
.dumpId
),
3815 destroyPQExpBuffer(query
);
3819 if (polinfo
->polcmd
== '*')
3821 else if (polinfo
->polcmd
== 'r')
3822 cmd
= " FOR SELECT";
3823 else if (polinfo
->polcmd
== 'a')
3824 cmd
= " FOR INSERT";
3825 else if (polinfo
->polcmd
== 'w')
3826 cmd
= " FOR UPDATE";
3827 else if (polinfo
->polcmd
== 'd')
3828 cmd
= " FOR DELETE";
3831 pg_log_error("unexpected policy command type: %c",
3836 query
= createPQExpBuffer();
3837 delqry
= createPQExpBuffer();
3838 polprefix
= createPQExpBuffer();
3840 qtabname
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
3842 appendPQExpBuffer(query
, "CREATE POLICY %s", fmtId(polinfo
->polname
));
3844 appendPQExpBuffer(query
, " ON %s%s%s", fmtQualifiedDumpable(tbinfo
),
3845 !polinfo
->polpermissive
? " AS RESTRICTIVE" : "", cmd
);
3847 if (polinfo
->polroles
!= NULL
)
3848 appendPQExpBuffer(query
, " TO %s", polinfo
->polroles
);
3850 if (polinfo
->polqual
!= NULL
)
3851 appendPQExpBuffer(query
, " USING (%s)", polinfo
->polqual
);
3853 if (polinfo
->polwithcheck
!= NULL
)
3854 appendPQExpBuffer(query
, " WITH CHECK (%s)", polinfo
->polwithcheck
);
3856 appendPQExpBuffer(query
, ";\n");
3858 appendPQExpBuffer(delqry
, "DROP POLICY %s", fmtId(polinfo
->polname
));
3859 appendPQExpBuffer(delqry
, " ON %s;\n", fmtQualifiedDumpable(tbinfo
));
3861 appendPQExpBuffer(polprefix
, "POLICY %s ON",
3862 fmtId(polinfo
->polname
));
3864 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, polinfo
->dobj
.name
);
3866 if (polinfo
->dobj
.dump
& DUMP_COMPONENT_POLICY
)
3867 ArchiveEntry(fout
, polinfo
->dobj
.catId
, polinfo
->dobj
.dumpId
,
3868 ARCHIVE_OPTS(.tag
= tag
,
3869 .namespace = polinfo
->dobj
.namespace->dobj
.name
,
3870 .owner
= tbinfo
->rolname
,
3871 .description
= "POLICY",
3872 .section
= SECTION_POST_DATA
,
3873 .createStmt
= query
->data
,
3874 .dropStmt
= delqry
->data
));
3876 if (polinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
3877 dumpComment(fout
, polprefix
->data
, qtabname
,
3878 tbinfo
->dobj
.namespace->dobj
.name
, tbinfo
->rolname
,
3879 polinfo
->dobj
.catId
, 0, polinfo
->dobj
.dumpId
);
3882 destroyPQExpBuffer(query
);
3883 destroyPQExpBuffer(delqry
);
3884 destroyPQExpBuffer(polprefix
);
3890 * get information about publications
3893 getPublications(Archive
*fout
, int *numPublications
)
3895 DumpOptions
*dopt
= fout
->dopt
;
3898 PublicationInfo
*pubinfo
;
3911 if (dopt
->no_publications
|| fout
->remoteVersion
< 100000)
3913 *numPublications
= 0;
3917 query
= createPQExpBuffer();
3919 resetPQExpBuffer(query
);
3921 /* Get the publications. */
3922 if (fout
->remoteVersion
>= 110000)
3923 appendPQExpBuffer(query
,
3924 "SELECT p.tableoid, p.oid, p.pubname, "
3925 "(%s p.pubowner) AS rolname, "
3926 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, p.pubtruncate "
3927 "FROM pg_publication p",
3930 appendPQExpBuffer(query
,
3931 "SELECT p.tableoid, p.oid, p.pubname, "
3932 "(%s p.pubowner) AS rolname, "
3933 "p.puballtables, p.pubinsert, p.pubupdate, p.pubdelete, false AS pubtruncate "
3934 "FROM pg_publication p",
3937 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
3939 ntups
= PQntuples(res
);
3941 i_tableoid
= PQfnumber(res
, "tableoid");
3942 i_oid
= PQfnumber(res
, "oid");
3943 i_pubname
= PQfnumber(res
, "pubname");
3944 i_rolname
= PQfnumber(res
, "rolname");
3945 i_puballtables
= PQfnumber(res
, "puballtables");
3946 i_pubinsert
= PQfnumber(res
, "pubinsert");
3947 i_pubupdate
= PQfnumber(res
, "pubupdate");
3948 i_pubdelete
= PQfnumber(res
, "pubdelete");
3949 i_pubtruncate
= PQfnumber(res
, "pubtruncate");
3951 pubinfo
= pg_malloc(ntups
* sizeof(PublicationInfo
));
3953 for (i
= 0; i
< ntups
; i
++)
3955 pubinfo
[i
].dobj
.objType
= DO_PUBLICATION
;
3956 pubinfo
[i
].dobj
.catId
.tableoid
=
3957 atooid(PQgetvalue(res
, i
, i_tableoid
));
3958 pubinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
3959 AssignDumpId(&pubinfo
[i
].dobj
);
3960 pubinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_pubname
));
3961 pubinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
3962 pubinfo
[i
].puballtables
=
3963 (strcmp(PQgetvalue(res
, i
, i_puballtables
), "t") == 0);
3964 pubinfo
[i
].pubinsert
=
3965 (strcmp(PQgetvalue(res
, i
, i_pubinsert
), "t") == 0);
3966 pubinfo
[i
].pubupdate
=
3967 (strcmp(PQgetvalue(res
, i
, i_pubupdate
), "t") == 0);
3968 pubinfo
[i
].pubdelete
=
3969 (strcmp(PQgetvalue(res
, i
, i_pubdelete
), "t") == 0);
3970 pubinfo
[i
].pubtruncate
=
3971 (strcmp(PQgetvalue(res
, i
, i_pubtruncate
), "t") == 0);
3973 if (strlen(pubinfo
[i
].rolname
) == 0)
3974 pg_log_warning("owner of publication \"%s\" appears to be invalid",
3975 pubinfo
[i
].dobj
.name
);
3977 /* Decide whether we want to dump it */
3978 selectDumpableObject(&(pubinfo
[i
].dobj
), fout
);
3982 destroyPQExpBuffer(query
);
3984 *numPublications
= ntups
;
3990 * dump the definition of the given publication
3993 dumpPublication(Archive
*fout
, PublicationInfo
*pubinfo
)
4000 if (!(pubinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
4003 delq
= createPQExpBuffer();
4004 query
= createPQExpBuffer();
4006 qpubname
= pg_strdup(fmtId(pubinfo
->dobj
.name
));
4008 appendPQExpBuffer(delq
, "DROP PUBLICATION %s;\n",
4011 appendPQExpBuffer(query
, "CREATE PUBLICATION %s",
4014 if (pubinfo
->puballtables
)
4015 appendPQExpBufferStr(query
, " FOR ALL TABLES");
4017 appendPQExpBufferStr(query
, " WITH (publish = '");
4018 if (pubinfo
->pubinsert
)
4020 appendPQExpBufferStr(query
, "insert");
4024 if (pubinfo
->pubupdate
)
4027 appendPQExpBufferStr(query
, ", ");
4029 appendPQExpBufferStr(query
, "update");
4033 if (pubinfo
->pubdelete
)
4036 appendPQExpBufferStr(query
, ", ");
4038 appendPQExpBufferStr(query
, "delete");
4042 if (pubinfo
->pubtruncate
)
4045 appendPQExpBufferStr(query
, ", ");
4047 appendPQExpBufferStr(query
, "truncate");
4051 appendPQExpBufferStr(query
, "');\n");
4053 ArchiveEntry(fout
, pubinfo
->dobj
.catId
, pubinfo
->dobj
.dumpId
,
4054 ARCHIVE_OPTS(.tag
= pubinfo
->dobj
.name
,
4055 .owner
= pubinfo
->rolname
,
4056 .description
= "PUBLICATION",
4057 .section
= SECTION_POST_DATA
,
4058 .createStmt
= query
->data
,
4059 .dropStmt
= delq
->data
));
4061 if (pubinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
4062 dumpComment(fout
, "PUBLICATION", qpubname
,
4063 NULL
, pubinfo
->rolname
,
4064 pubinfo
->dobj
.catId
, 0, pubinfo
->dobj
.dumpId
);
4066 if (pubinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
4067 dumpSecLabel(fout
, "PUBLICATION", qpubname
,
4068 NULL
, pubinfo
->rolname
,
4069 pubinfo
->dobj
.catId
, 0, pubinfo
->dobj
.dumpId
);
4071 destroyPQExpBuffer(delq
);
4072 destroyPQExpBuffer(query
);
4077 * getPublicationTables
4078 * get information about publication membership for dumpable tables.
4081 getPublicationTables(Archive
*fout
, TableInfo tblinfo
[], int numTables
)
4085 PublicationRelInfo
*pubrinfo
;
4086 DumpOptions
*dopt
= fout
->dopt
;
4095 if (dopt
->no_publications
|| fout
->remoteVersion
< 100000)
4098 query
= createPQExpBuffer();
4100 /* Collect all publication membership info. */
4101 appendPQExpBufferStr(query
,
4102 "SELECT tableoid, oid, prpubid, prrelid "
4103 "FROM pg_catalog.pg_publication_rel");
4104 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
4106 ntups
= PQntuples(res
);
4108 i_tableoid
= PQfnumber(res
, "tableoid");
4109 i_oid
= PQfnumber(res
, "oid");
4110 i_prpubid
= PQfnumber(res
, "prpubid");
4111 i_prrelid
= PQfnumber(res
, "prrelid");
4113 /* this allocation may be more than we need */
4114 pubrinfo
= pg_malloc(ntups
* sizeof(PublicationRelInfo
));
4117 for (i
= 0; i
< ntups
; i
++)
4119 Oid prpubid
= atooid(PQgetvalue(res
, i
, i_prpubid
));
4120 Oid prrelid
= atooid(PQgetvalue(res
, i
, i_prrelid
));
4121 PublicationInfo
*pubinfo
;
4125 * Ignore any entries for which we aren't interested in either the
4126 * publication or the rel.
4128 pubinfo
= findPublicationByOid(prpubid
);
4129 if (pubinfo
== NULL
)
4131 tbinfo
= findTableByOid(prrelid
);
4136 * Ignore publication membership of tables whose definitions are not
4139 if (!(tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
4142 /* OK, make a DumpableObject for this relationship */
4143 pubrinfo
[j
].dobj
.objType
= DO_PUBLICATION_REL
;
4144 pubrinfo
[j
].dobj
.catId
.tableoid
=
4145 atooid(PQgetvalue(res
, i
, i_tableoid
));
4146 pubrinfo
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
4147 AssignDumpId(&pubrinfo
[j
].dobj
);
4148 pubrinfo
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
4149 pubrinfo
[j
].dobj
.name
= tbinfo
->dobj
.name
;
4150 pubrinfo
[j
].publication
= pubinfo
;
4151 pubrinfo
[j
].pubtable
= tbinfo
;
4153 /* Decide whether we want to dump it */
4154 selectDumpablePublicationTable(&(pubrinfo
[j
].dobj
), fout
);
4160 destroyPQExpBuffer(query
);
4164 * dumpPublicationTable
4165 * dump the definition of the given publication table mapping
4168 dumpPublicationTable(Archive
*fout
, PublicationRelInfo
*pubrinfo
)
4170 PublicationInfo
*pubinfo
= pubrinfo
->publication
;
4171 TableInfo
*tbinfo
= pubrinfo
->pubtable
;
4175 if (!(pubrinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
4178 tag
= psprintf("%s %s", pubinfo
->dobj
.name
, tbinfo
->dobj
.name
);
4180 query
= createPQExpBuffer();
4182 appendPQExpBuffer(query
, "ALTER PUBLICATION %s ADD TABLE ONLY",
4183 fmtId(pubinfo
->dobj
.name
));
4184 appendPQExpBuffer(query
, " %s;\n",
4185 fmtQualifiedDumpable(tbinfo
));
4188 * There is no point in creating a drop query as the drop is done by table
4189 * drop. (If you think to change this, see also _printTocEntry().)
4190 * Although this object doesn't really have ownership as such, set the
4191 * owner field anyway to ensure that the command is run by the correct
4192 * role at restore time.
4194 ArchiveEntry(fout
, pubrinfo
->dobj
.catId
, pubrinfo
->dobj
.dumpId
,
4195 ARCHIVE_OPTS(.tag
= tag
,
4196 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
4197 .owner
= pubinfo
->rolname
,
4198 .description
= "PUBLICATION TABLE",
4199 .section
= SECTION_POST_DATA
,
4200 .createStmt
= query
->data
));
4203 destroyPQExpBuffer(query
);
4207 * Is the currently connected user a superuser?
4210 is_superuser(Archive
*fout
)
4212 ArchiveHandle
*AH
= (ArchiveHandle
*) fout
;
4215 val
= PQparameterStatus(AH
->connection
, "is_superuser");
4217 if (val
&& strcmp(val
, "on") == 0)
4225 * get information about subscriptions
4228 getSubscriptions(Archive
*fout
)
4230 DumpOptions
*dopt
= fout
->dopt
;
4233 SubscriptionInfo
*subinfo
;
4240 int i_subsynccommit
;
4241 int i_subpublications
;
4245 if (dopt
->no_subscriptions
|| fout
->remoteVersion
< 100000)
4248 if (!is_superuser(fout
))
4252 res
= ExecuteSqlQuery(fout
,
4253 "SELECT count(*) FROM pg_subscription "
4254 "WHERE subdbid = (SELECT oid FROM pg_database"
4255 " WHERE datname = current_database())",
4257 n
= atoi(PQgetvalue(res
, 0, 0));
4259 pg_log_warning("subscriptions not dumped because current user is not a superuser");
4264 query
= createPQExpBuffer();
4266 resetPQExpBuffer(query
);
4268 /* Get the subscriptions in current database. */
4269 appendPQExpBuffer(query
,
4270 "SELECT s.tableoid, s.oid, s.subname,"
4271 "(%s s.subowner) AS rolname, "
4272 " s.subconninfo, s.subslotname, s.subsynccommit, "
4273 " s.subpublications "
4274 "FROM pg_subscription s "
4275 "WHERE s.subdbid = (SELECT oid FROM pg_database"
4276 " WHERE datname = current_database())",
4278 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
4280 ntups
= PQntuples(res
);
4282 i_tableoid
= PQfnumber(res
, "tableoid");
4283 i_oid
= PQfnumber(res
, "oid");
4284 i_subname
= PQfnumber(res
, "subname");
4285 i_rolname
= PQfnumber(res
, "rolname");
4286 i_subconninfo
= PQfnumber(res
, "subconninfo");
4287 i_subslotname
= PQfnumber(res
, "subslotname");
4288 i_subsynccommit
= PQfnumber(res
, "subsynccommit");
4289 i_subpublications
= PQfnumber(res
, "subpublications");
4291 subinfo
= pg_malloc(ntups
* sizeof(SubscriptionInfo
));
4293 for (i
= 0; i
< ntups
; i
++)
4295 subinfo
[i
].dobj
.objType
= DO_SUBSCRIPTION
;
4296 subinfo
[i
].dobj
.catId
.tableoid
=
4297 atooid(PQgetvalue(res
, i
, i_tableoid
));
4298 subinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
4299 AssignDumpId(&subinfo
[i
].dobj
);
4300 subinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_subname
));
4301 subinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
4302 subinfo
[i
].subconninfo
= pg_strdup(PQgetvalue(res
, i
, i_subconninfo
));
4303 if (PQgetisnull(res
, i
, i_subslotname
))
4304 subinfo
[i
].subslotname
= NULL
;
4306 subinfo
[i
].subslotname
= pg_strdup(PQgetvalue(res
, i
, i_subslotname
));
4307 subinfo
[i
].subsynccommit
=
4308 pg_strdup(PQgetvalue(res
, i
, i_subsynccommit
));
4309 subinfo
[i
].subpublications
=
4310 pg_strdup(PQgetvalue(res
, i
, i_subpublications
));
4312 if (strlen(subinfo
[i
].rolname
) == 0)
4313 pg_log_warning("owner of subscription \"%s\" appears to be invalid",
4314 subinfo
[i
].dobj
.name
);
4316 /* Decide whether we want to dump it */
4317 selectDumpableObject(&(subinfo
[i
].dobj
), fout
);
4321 destroyPQExpBuffer(query
);
4326 * dump the definition of the given subscription
4329 dumpSubscription(Archive
*fout
, SubscriptionInfo
*subinfo
)
4333 PQExpBuffer publications
;
4335 char **pubnames
= NULL
;
4339 if (!(subinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
4342 delq
= createPQExpBuffer();
4343 query
= createPQExpBuffer();
4345 qsubname
= pg_strdup(fmtId(subinfo
->dobj
.name
));
4347 appendPQExpBuffer(delq
, "DROP SUBSCRIPTION %s;\n",
4350 appendPQExpBuffer(query
, "CREATE SUBSCRIPTION %s CONNECTION ",
4352 appendStringLiteralAH(query
, subinfo
->subconninfo
, fout
);
4354 /* Build list of quoted publications and append them to query. */
4355 if (!parsePGArray(subinfo
->subpublications
, &pubnames
, &npubnames
))
4357 pg_log_warning("could not parse subpublications array");
4364 publications
= createPQExpBuffer();
4365 for (i
= 0; i
< npubnames
; i
++)
4368 appendPQExpBufferStr(publications
, ", ");
4370 appendPQExpBufferStr(publications
, fmtId(pubnames
[i
]));
4373 appendPQExpBuffer(query
, " PUBLICATION %s WITH (connect = false, slot_name = ", publications
->data
);
4374 if (subinfo
->subslotname
)
4375 appendStringLiteralAH(query
, subinfo
->subslotname
, fout
);
4377 appendPQExpBufferStr(query
, "NONE");
4379 if (strcmp(subinfo
->subsynccommit
, "off") != 0)
4380 appendPQExpBuffer(query
, ", synchronous_commit = %s", fmtId(subinfo
->subsynccommit
));
4382 appendPQExpBufferStr(query
, ");\n");
4384 ArchiveEntry(fout
, subinfo
->dobj
.catId
, subinfo
->dobj
.dumpId
,
4385 ARCHIVE_OPTS(.tag
= subinfo
->dobj
.name
,
4386 .owner
= subinfo
->rolname
,
4387 .description
= "SUBSCRIPTION",
4388 .section
= SECTION_POST_DATA
,
4389 .createStmt
= query
->data
,
4390 .dropStmt
= delq
->data
));
4392 if (subinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
4393 dumpComment(fout
, "SUBSCRIPTION", qsubname
,
4394 NULL
, subinfo
->rolname
,
4395 subinfo
->dobj
.catId
, 0, subinfo
->dobj
.dumpId
);
4397 if (subinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
4398 dumpSecLabel(fout
, "SUBSCRIPTION", qsubname
,
4399 NULL
, subinfo
->rolname
,
4400 subinfo
->dobj
.catId
, 0, subinfo
->dobj
.dumpId
);
4402 destroyPQExpBuffer(publications
);
4406 destroyPQExpBuffer(delq
);
4407 destroyPQExpBuffer(query
);
4412 * Given a "create query", append as many ALTER ... DEPENDS ON EXTENSION as
4416 append_depends_on_extension(Archive
*fout
,
4418 DumpableObject
*dobj
,
4419 const char *catalog
,
4420 const char *keyword
,
4421 const char *objname
)
4423 if (dobj
->depends_on_ext
)
4432 /* dodge fmtId() non-reentrancy */
4433 nm
= pg_strdup(objname
);
4435 query
= createPQExpBuffer();
4436 appendPQExpBuffer(query
,
4438 "FROM pg_catalog.pg_depend d, pg_catalog.pg_extension e "
4439 "WHERE d.refobjid = e.oid AND classid = '%s'::pg_catalog.regclass "
4440 "AND objid = '%u'::pg_catalog.oid AND deptype = 'x' "
4441 "AND refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass",
4444 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
4445 ntups
= PQntuples(res
);
4446 i_extname
= PQfnumber(res
, "extname");
4447 for (i
= 0; i
< ntups
; i
++)
4449 appendPQExpBuffer(create
, "ALTER %s %s DEPENDS ON EXTENSION %s;\n",
4451 fmtId(PQgetvalue(res
, i
, i_extname
)));
4455 destroyPQExpBuffer(query
);
4462 binary_upgrade_set_type_oids_by_type_oid(Archive
*fout
,
4463 PQExpBuffer upgrade_buffer
,
4465 bool force_array_type
)
4467 PQExpBuffer upgrade_query
= createPQExpBuffer();
4469 Oid pg_type_array_oid
;
4471 appendPQExpBufferStr(upgrade_buffer
, "\n-- For binary upgrade, must preserve pg_type oid\n");
4472 appendPQExpBuffer(upgrade_buffer
,
4473 "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4476 /* we only support old >= 8.3 for binary upgrades */
4477 appendPQExpBuffer(upgrade_query
,
4479 "FROM pg_catalog.pg_type "
4480 "WHERE oid = '%u'::pg_catalog.oid;",
4483 res
= ExecuteSqlQueryForSingleRow(fout
, upgrade_query
->data
);
4485 pg_type_array_oid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typarray")));
4489 if (!OidIsValid(pg_type_array_oid
) && force_array_type
)
4492 * If the old version didn't assign an array type, but the new version
4493 * does, we must select an unused type OID to assign. This currently
4494 * only happens for domains, when upgrading pre-v11 to v11 and up.
4496 * Note: local state here is kind of ugly, but we must have some,
4497 * since we mustn't choose the same unused OID more than once.
4499 static Oid next_possible_free_oid
= FirstNormalObjectId
;
4504 ++next_possible_free_oid
;
4505 printfPQExpBuffer(upgrade_query
,
4506 "SELECT EXISTS(SELECT 1 "
4507 "FROM pg_catalog.pg_type "
4508 "WHERE oid = '%u'::pg_catalog.oid);",
4509 next_possible_free_oid
);
4510 res
= ExecuteSqlQueryForSingleRow(fout
, upgrade_query
->data
);
4511 is_dup
= (PQgetvalue(res
, 0, 0)[0] == 't');
4515 pg_type_array_oid
= next_possible_free_oid
;
4518 if (OidIsValid(pg_type_array_oid
))
4520 appendPQExpBufferStr(upgrade_buffer
,
4521 "\n-- For binary upgrade, must preserve pg_type array oid\n");
4522 appendPQExpBuffer(upgrade_buffer
,
4523 "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4527 destroyPQExpBuffer(upgrade_query
);
4531 binary_upgrade_set_type_oids_by_rel_oid(Archive
*fout
,
4532 PQExpBuffer upgrade_buffer
,
4535 PQExpBuffer upgrade_query
= createPQExpBuffer();
4536 PGresult
*upgrade_res
;
4538 bool toast_set
= false;
4541 * We only support old >= 8.3 for binary upgrades.
4543 * We purposefully ignore toast OIDs for partitioned tables; the reason is
4544 * that versions 10 and 11 have them, but 12 does not, so emitting them
4545 * causes the upgrade to fail.
4547 appendPQExpBuffer(upgrade_query
,
4548 "SELECT c.reltype AS crel, t.reltype AS trel "
4549 "FROM pg_catalog.pg_class c "
4550 "LEFT JOIN pg_catalog.pg_class t ON "
4551 " (c.reltoastrelid = t.oid AND c.relkind <> '%c') "
4552 "WHERE c.oid = '%u'::pg_catalog.oid;",
4553 RELKIND_PARTITIONED_TABLE
, pg_rel_oid
);
4555 upgrade_res
= ExecuteSqlQueryForSingleRow(fout
, upgrade_query
->data
);
4557 pg_type_oid
= atooid(PQgetvalue(upgrade_res
, 0, PQfnumber(upgrade_res
, "crel")));
4559 binary_upgrade_set_type_oids_by_type_oid(fout
, upgrade_buffer
,
4560 pg_type_oid
, false);
4562 if (!PQgetisnull(upgrade_res
, 0, PQfnumber(upgrade_res
, "trel")))
4564 /* Toast tables do not have pg_type array rows */
4565 Oid pg_type_toast_oid
= atooid(PQgetvalue(upgrade_res
, 0,
4566 PQfnumber(upgrade_res
, "trel")));
4568 appendPQExpBufferStr(upgrade_buffer
, "\n-- For binary upgrade, must preserve pg_type toast oid\n");
4569 appendPQExpBuffer(upgrade_buffer
,
4570 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_type_oid('%u'::pg_catalog.oid);\n\n",
4576 PQclear(upgrade_res
);
4577 destroyPQExpBuffer(upgrade_query
);
4583 binary_upgrade_set_pg_class_oids(Archive
*fout
,
4584 PQExpBuffer upgrade_buffer
, Oid pg_class_oid
,
4587 PQExpBuffer upgrade_query
= createPQExpBuffer();
4588 PGresult
*upgrade_res
;
4589 Oid pg_class_reltoastrelid
;
4590 Oid pg_index_indexrelid
;
4592 appendPQExpBuffer(upgrade_query
,
4593 "SELECT c.reltoastrelid, i.indexrelid "
4594 "FROM pg_catalog.pg_class c LEFT JOIN "
4595 "pg_catalog.pg_index i ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
4596 "WHERE c.oid = '%u'::pg_catalog.oid;",
4599 upgrade_res
= ExecuteSqlQueryForSingleRow(fout
, upgrade_query
->data
);
4601 pg_class_reltoastrelid
= atooid(PQgetvalue(upgrade_res
, 0, PQfnumber(upgrade_res
, "reltoastrelid")));
4602 pg_index_indexrelid
= atooid(PQgetvalue(upgrade_res
, 0, PQfnumber(upgrade_res
, "indexrelid")));
4604 appendPQExpBufferStr(upgrade_buffer
,
4605 "\n-- For binary upgrade, must preserve pg_class oids\n");
4609 appendPQExpBuffer(upgrade_buffer
,
4610 "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
4612 /* only tables have toast tables, not indexes */
4613 if (OidIsValid(pg_class_reltoastrelid
))
4616 * One complexity is that the table definition might not require
4617 * the creation of a TOAST table, and the TOAST table might have
4618 * been created long after table creation, when the table was
4619 * loaded with wide data. By setting the TOAST oid we force
4620 * creation of the TOAST heap and TOAST index by the backend so we
4621 * can cleanly copy the files during binary upgrade.
4624 appendPQExpBuffer(upgrade_buffer
,
4625 "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
4626 pg_class_reltoastrelid
);
4628 /* every toast table has an index */
4629 appendPQExpBuffer(upgrade_buffer
,
4630 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4631 pg_index_indexrelid
);
4635 appendPQExpBuffer(upgrade_buffer
,
4636 "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
4639 appendPQExpBufferChar(upgrade_buffer
, '\n');
4641 PQclear(upgrade_res
);
4642 destroyPQExpBuffer(upgrade_query
);
4646 * If the DumpableObject is a member of an extension, add a suitable
4647 * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
4649 * For somewhat historical reasons, objname should already be quoted,
4650 * but not objnamespace (if any).
4653 binary_upgrade_extension_member(PQExpBuffer upgrade_buffer
,
4654 DumpableObject
*dobj
,
4655 const char *objtype
,
4656 const char *objname
,
4657 const char *objnamespace
)
4659 DumpableObject
*extobj
= NULL
;
4662 if (!dobj
->ext_member
)
4666 * Find the parent extension. We could avoid this search if we wanted to
4667 * add a link field to DumpableObject, but the space costs of that would
4668 * be considerable. We assume that member objects could only have a
4669 * direct dependency on their own extension, not any others.
4671 for (i
= 0; i
< dobj
->nDeps
; i
++)
4673 extobj
= findObjectByDumpId(dobj
->dependencies
[i
]);
4674 if (extobj
&& extobj
->objType
== DO_EXTENSION
)
4679 fatal("could not find parent extension for %s %s",
4682 appendPQExpBufferStr(upgrade_buffer
,
4683 "\n-- For binary upgrade, handle extension membership the hard way\n");
4684 appendPQExpBuffer(upgrade_buffer
, "ALTER EXTENSION %s ADD %s ",
4685 fmtId(extobj
->name
),
4687 if (objnamespace
&& *objnamespace
)
4688 appendPQExpBuffer(upgrade_buffer
, "%s.", fmtId(objnamespace
));
4689 appendPQExpBuffer(upgrade_buffer
, "%s;\n", objname
);
4694 * read all namespaces in the system catalogs and return them in the
4695 * NamespaceInfo* structure
4697 * numNamespaces is set to the number of namespaces read in
4700 getNamespaces(Archive
*fout
, int *numNamespaces
)
4702 DumpOptions
*dopt
= fout
->dopt
;
4707 NamespaceInfo
*nsinfo
;
4717 query
= createPQExpBuffer();
4720 * we fetch all namespaces including system ones, so that every object we
4721 * read in can be linked to a containing namespace.
4723 if (fout
->remoteVersion
>= 90600)
4725 PQExpBuffer acl_subquery
= createPQExpBuffer();
4726 PQExpBuffer racl_subquery
= createPQExpBuffer();
4727 PQExpBuffer init_acl_subquery
= createPQExpBuffer();
4728 PQExpBuffer init_racl_subquery
= createPQExpBuffer();
4730 buildACLQueries(acl_subquery
, racl_subquery
, init_acl_subquery
,
4731 init_racl_subquery
, "n.nspacl", "n.nspowner", "'n'",
4732 dopt
->binary_upgrade
);
4734 appendPQExpBuffer(query
, "SELECT n.tableoid, n.oid, n.nspname, "
4735 "(%s nspowner) AS rolname, "
4738 "%s as initnspacl, "
4739 "%s as initrnspacl "
4740 "FROM pg_namespace n "
4741 "LEFT JOIN pg_init_privs pip "
4742 "ON (n.oid = pip.objoid "
4743 "AND pip.classoid = 'pg_namespace'::regclass "
4744 "AND pip.objsubid = 0",
4747 racl_subquery
->data
,
4748 init_acl_subquery
->data
,
4749 init_racl_subquery
->data
);
4751 appendPQExpBuffer(query
, ") ");
4753 destroyPQExpBuffer(acl_subquery
);
4754 destroyPQExpBuffer(racl_subquery
);
4755 destroyPQExpBuffer(init_acl_subquery
);
4756 destroyPQExpBuffer(init_racl_subquery
);
4759 appendPQExpBuffer(query
, "SELECT tableoid, oid, nspname, "
4760 "(%s nspowner) AS rolname, "
4761 "nspacl, NULL as rnspacl, "
4762 "NULL AS initnspacl, NULL as initrnspacl "
4763 "FROM pg_namespace",
4766 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
4768 ntups
= PQntuples(res
);
4770 nsinfo
= (NamespaceInfo
*) pg_malloc(ntups
* sizeof(NamespaceInfo
));
4772 i_tableoid
= PQfnumber(res
, "tableoid");
4773 i_oid
= PQfnumber(res
, "oid");
4774 i_nspname
= PQfnumber(res
, "nspname");
4775 i_rolname
= PQfnumber(res
, "rolname");
4776 i_nspacl
= PQfnumber(res
, "nspacl");
4777 i_rnspacl
= PQfnumber(res
, "rnspacl");
4778 i_initnspacl
= PQfnumber(res
, "initnspacl");
4779 i_initrnspacl
= PQfnumber(res
, "initrnspacl");
4781 for (i
= 0; i
< ntups
; i
++)
4783 nsinfo
[i
].dobj
.objType
= DO_NAMESPACE
;
4784 nsinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
4785 nsinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
4786 AssignDumpId(&nsinfo
[i
].dobj
);
4787 nsinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_nspname
));
4788 nsinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
4789 nsinfo
[i
].nspacl
= pg_strdup(PQgetvalue(res
, i
, i_nspacl
));
4790 nsinfo
[i
].rnspacl
= pg_strdup(PQgetvalue(res
, i
, i_rnspacl
));
4791 nsinfo
[i
].initnspacl
= pg_strdup(PQgetvalue(res
, i
, i_initnspacl
));
4792 nsinfo
[i
].initrnspacl
= pg_strdup(PQgetvalue(res
, i
, i_initrnspacl
));
4794 /* Decide whether to dump this namespace */
4795 selectDumpableNamespace(&nsinfo
[i
], fout
);
4798 * Do not try to dump ACL if the ACL is empty or the default.
4800 * This is useful because, for some schemas/objects, the only
4801 * component we are going to try and dump is the ACL and if we can
4802 * remove that then 'dump' goes to zero/false and we don't consider
4803 * this object for dumping at all later on.
4805 if (PQgetisnull(res
, i
, i_nspacl
) && PQgetisnull(res
, i
, i_rnspacl
) &&
4806 PQgetisnull(res
, i
, i_initnspacl
) &&
4807 PQgetisnull(res
, i
, i_initrnspacl
))
4808 nsinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
4810 if (strlen(nsinfo
[i
].rolname
) == 0)
4811 pg_log_warning("owner of schema \"%s\" appears to be invalid",
4812 nsinfo
[i
].dobj
.name
);
4816 destroyPQExpBuffer(query
);
4818 *numNamespaces
= ntups
;
4825 * given a namespace OID, look up the info read by getNamespaces
4827 static NamespaceInfo
*
4828 findNamespace(Archive
*fout
, Oid nsoid
)
4830 NamespaceInfo
*nsinfo
;
4832 nsinfo
= findNamespaceByOid(nsoid
);
4834 fatal("schema with OID %u does not exist", nsoid
);
4840 * read all extensions in the system catalogs and return them in the
4841 * ExtensionInfo* structure
4843 * numExtensions is set to the number of extensions read in
4846 getExtensions(Archive
*fout
, int *numExtensions
)
4848 DumpOptions
*dopt
= fout
->dopt
;
4853 ExtensionInfo
*extinfo
;
4858 int i_extrelocatable
;
4864 * Before 9.1, there are no extensions.
4866 if (fout
->remoteVersion
< 90100)
4872 query
= createPQExpBuffer();
4874 appendPQExpBufferStr(query
, "SELECT x.tableoid, x.oid, "
4875 "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
4876 "FROM pg_extension x "
4877 "JOIN pg_namespace n ON n.oid = x.extnamespace");
4879 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
4881 ntups
= PQntuples(res
);
4883 extinfo
= (ExtensionInfo
*) pg_malloc(ntups
* sizeof(ExtensionInfo
));
4885 i_tableoid
= PQfnumber(res
, "tableoid");
4886 i_oid
= PQfnumber(res
, "oid");
4887 i_extname
= PQfnumber(res
, "extname");
4888 i_nspname
= PQfnumber(res
, "nspname");
4889 i_extrelocatable
= PQfnumber(res
, "extrelocatable");
4890 i_extversion
= PQfnumber(res
, "extversion");
4891 i_extconfig
= PQfnumber(res
, "extconfig");
4892 i_extcondition
= PQfnumber(res
, "extcondition");
4894 for (i
= 0; i
< ntups
; i
++)
4896 extinfo
[i
].dobj
.objType
= DO_EXTENSION
;
4897 extinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
4898 extinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
4899 AssignDumpId(&extinfo
[i
].dobj
);
4900 extinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_extname
));
4901 extinfo
[i
].namespace = pg_strdup(PQgetvalue(res
, i
, i_nspname
));
4902 extinfo
[i
].relocatable
= *(PQgetvalue(res
, i
, i_extrelocatable
)) == 't';
4903 extinfo
[i
].extversion
= pg_strdup(PQgetvalue(res
, i
, i_extversion
));
4904 extinfo
[i
].extconfig
= pg_strdup(PQgetvalue(res
, i
, i_extconfig
));
4905 extinfo
[i
].extcondition
= pg_strdup(PQgetvalue(res
, i
, i_extcondition
));
4907 /* Decide whether we want to dump it */
4908 selectDumpableExtension(&(extinfo
[i
]), dopt
);
4912 destroyPQExpBuffer(query
);
4914 *numExtensions
= ntups
;
4921 * read all types in the system catalogs and return them in the
4922 * TypeInfo* structure
4924 * numTypes is set to the number of types read in
4926 * NB: this must run after getFuncs() because we assume we can do
4930 getTypes(Archive
*fout
, int *numTypes
)
4932 DumpOptions
*dopt
= fout
->dopt
;
4936 PQExpBuffer query
= createPQExpBuffer();
4938 ShellTypeInfo
*stinfo
;
4956 * we include even the built-in types because those may be used as array
4957 * elements by user-defined types
4959 * we filter out the built-in types when we dump out the types
4961 * same approach for undefined (shell) types and array types
4963 * Note: as of 8.3 we can reliably detect whether a type is an
4964 * auto-generated array type by checking the element type's typarray.
4965 * (Before that the test is capable of generating false positives.) We
4966 * still check for name beginning with '_', though, so as to avoid the
4967 * cost of the subselect probe for all standard types. This would have to
4968 * be revisited if the backend ever allows renaming of array types.
4971 if (fout
->remoteVersion
>= 90600)
4973 PQExpBuffer acl_subquery
= createPQExpBuffer();
4974 PQExpBuffer racl_subquery
= createPQExpBuffer();
4975 PQExpBuffer initacl_subquery
= createPQExpBuffer();
4976 PQExpBuffer initracl_subquery
= createPQExpBuffer();
4978 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
4979 initracl_subquery
, "t.typacl", "t.typowner", "'T'",
4980 dopt
->binary_upgrade
);
4982 appendPQExpBuffer(query
, "SELECT t.tableoid, t.oid, t.typname, "
4986 "%s AS inittypacl, "
4987 "%s AS initrtypacl, "
4988 "(%s t.typowner) AS rolname, "
4989 "t.typelem, t.typrelid, "
4990 "CASE WHEN t.typrelid = 0 THEN ' '::\"char\" "
4991 "ELSE (SELECT relkind FROM pg_class WHERE oid = t.typrelid) END AS typrelkind, "
4992 "t.typtype, t.typisdefined, "
4993 "t.typname[0] = '_' AND t.typelem != 0 AND "
4994 "(SELECT typarray FROM pg_type te WHERE oid = t.typelem) = t.oid AS isarray "
4996 "LEFT JOIN pg_init_privs pip ON "
4997 "(t.oid = pip.objoid "
4998 "AND pip.classoid = 'pg_type'::regclass "
4999 "AND pip.objsubid = 0) ",
5001 racl_subquery
->data
,
5002 initacl_subquery
->data
,
5003 initracl_subquery
->data
,
5006 destroyPQExpBuffer(acl_subquery
);
5007 destroyPQExpBuffer(racl_subquery
);
5008 destroyPQExpBuffer(initacl_subquery
);
5009 destroyPQExpBuffer(initracl_subquery
);
5011 else if (fout
->remoteVersion
>= 90200)
5013 appendPQExpBuffer(query
, "SELECT tableoid, oid, typname, "
5014 "typnamespace, typacl, NULL as rtypacl, "
5015 "NULL AS inittypacl, NULL AS initrtypacl, "
5016 "(%s typowner) AS rolname, "
5017 "typelem, typrelid, "
5018 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5019 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5020 "typtype, typisdefined, "
5021 "typname[0] = '_' AND typelem != 0 AND "
5022 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
5026 else if (fout
->remoteVersion
>= 80300)
5028 appendPQExpBuffer(query
, "SELECT tableoid, oid, typname, "
5029 "typnamespace, NULL AS typacl, NULL as rtypacl, "
5030 "NULL AS inittypacl, NULL AS initrtypacl, "
5031 "(%s typowner) AS rolname, "
5032 "typelem, typrelid, "
5033 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5034 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5035 "typtype, typisdefined, "
5036 "typname[0] = '_' AND typelem != 0 AND "
5037 "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
5043 appendPQExpBuffer(query
, "SELECT tableoid, oid, typname, "
5044 "typnamespace, NULL AS typacl, NULL as rtypacl, "
5045 "NULL AS inittypacl, NULL AS initrtypacl, "
5046 "(%s typowner) AS rolname, "
5047 "typelem, typrelid, "
5048 "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5049 "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5050 "typtype, typisdefined, "
5051 "typname[0] = '_' AND typelem != 0 AS isarray "
5056 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5058 ntups
= PQntuples(res
);
5060 tyinfo
= (TypeInfo
*) pg_malloc(ntups
* sizeof(TypeInfo
));
5062 i_tableoid
= PQfnumber(res
, "tableoid");
5063 i_oid
= PQfnumber(res
, "oid");
5064 i_typname
= PQfnumber(res
, "typname");
5065 i_typnamespace
= PQfnumber(res
, "typnamespace");
5066 i_typacl
= PQfnumber(res
, "typacl");
5067 i_rtypacl
= PQfnumber(res
, "rtypacl");
5068 i_inittypacl
= PQfnumber(res
, "inittypacl");
5069 i_initrtypacl
= PQfnumber(res
, "initrtypacl");
5070 i_rolname
= PQfnumber(res
, "rolname");
5071 i_typelem
= PQfnumber(res
, "typelem");
5072 i_typrelid
= PQfnumber(res
, "typrelid");
5073 i_typrelkind
= PQfnumber(res
, "typrelkind");
5074 i_typtype
= PQfnumber(res
, "typtype");
5075 i_typisdefined
= PQfnumber(res
, "typisdefined");
5076 i_isarray
= PQfnumber(res
, "isarray");
5078 for (i
= 0; i
< ntups
; i
++)
5080 tyinfo
[i
].dobj
.objType
= DO_TYPE
;
5081 tyinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5082 tyinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5083 AssignDumpId(&tyinfo
[i
].dobj
);
5084 tyinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_typname
));
5085 tyinfo
[i
].dobj
.namespace =
5087 atooid(PQgetvalue(res
, i
, i_typnamespace
)));
5088 tyinfo
[i
].ftypname
= NULL
; /* may get filled later */
5089 tyinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5090 tyinfo
[i
].typacl
= pg_strdup(PQgetvalue(res
, i
, i_typacl
));
5091 tyinfo
[i
].rtypacl
= pg_strdup(PQgetvalue(res
, i
, i_rtypacl
));
5092 tyinfo
[i
].inittypacl
= pg_strdup(PQgetvalue(res
, i
, i_inittypacl
));
5093 tyinfo
[i
].initrtypacl
= pg_strdup(PQgetvalue(res
, i
, i_initrtypacl
));
5094 tyinfo
[i
].typelem
= atooid(PQgetvalue(res
, i
, i_typelem
));
5095 tyinfo
[i
].typrelid
= atooid(PQgetvalue(res
, i
, i_typrelid
));
5096 tyinfo
[i
].typrelkind
= *PQgetvalue(res
, i
, i_typrelkind
);
5097 tyinfo
[i
].typtype
= *PQgetvalue(res
, i
, i_typtype
);
5098 tyinfo
[i
].shellType
= NULL
;
5100 if (strcmp(PQgetvalue(res
, i
, i_typisdefined
), "t") == 0)
5101 tyinfo
[i
].isDefined
= true;
5103 tyinfo
[i
].isDefined
= false;
5105 if (strcmp(PQgetvalue(res
, i
, i_isarray
), "t") == 0)
5106 tyinfo
[i
].isArray
= true;
5108 tyinfo
[i
].isArray
= false;
5110 /* Decide whether we want to dump it */
5111 selectDumpableType(&tyinfo
[i
], fout
);
5113 /* Do not try to dump ACL if no ACL exists. */
5114 if (PQgetisnull(res
, i
, i_typacl
) && PQgetisnull(res
, i
, i_rtypacl
) &&
5115 PQgetisnull(res
, i
, i_inittypacl
) &&
5116 PQgetisnull(res
, i
, i_initrtypacl
))
5117 tyinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5120 * If it's a domain, fetch info about its constraints, if any
5122 tyinfo
[i
].nDomChecks
= 0;
5123 tyinfo
[i
].domChecks
= NULL
;
5124 if ((tyinfo
[i
].dobj
.dump
& DUMP_COMPONENT_DEFINITION
) &&
5125 tyinfo
[i
].typtype
== TYPTYPE_DOMAIN
)
5126 getDomainConstraints(fout
, &(tyinfo
[i
]));
5129 * If it's a base type, make a DumpableObject representing a shell
5130 * definition of the type. We will need to dump that ahead of the I/O
5131 * functions for the type. Similarly, range types need a shell
5132 * definition in case they have a canonicalize function.
5134 * Note: the shell type doesn't have a catId. You might think it
5135 * should copy the base type's catId, but then it might capture the
5136 * pg_depend entries for the type, which we don't want.
5138 if ((tyinfo
[i
].dobj
.dump
& DUMP_COMPONENT_DEFINITION
) &&
5139 (tyinfo
[i
].typtype
== TYPTYPE_BASE
||
5140 tyinfo
[i
].typtype
== TYPTYPE_RANGE
))
5142 stinfo
= (ShellTypeInfo
*) pg_malloc(sizeof(ShellTypeInfo
));
5143 stinfo
->dobj
.objType
= DO_SHELL_TYPE
;
5144 stinfo
->dobj
.catId
= nilCatalogId
;
5145 AssignDumpId(&stinfo
->dobj
);
5146 stinfo
->dobj
.name
= pg_strdup(tyinfo
[i
].dobj
.name
);
5147 stinfo
->dobj
.namespace = tyinfo
[i
].dobj
.namespace;
5148 stinfo
->baseType
= &(tyinfo
[i
]);
5149 tyinfo
[i
].shellType
= stinfo
;
5152 * Initially mark the shell type as not to be dumped. We'll only
5153 * dump it if the I/O or canonicalize functions need to be dumped;
5154 * this is taken care of while sorting dependencies.
5156 stinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
5159 if (strlen(tyinfo
[i
].rolname
) == 0)
5160 pg_log_warning("owner of data type \"%s\" appears to be invalid",
5161 tyinfo
[i
].dobj
.name
);
5168 destroyPQExpBuffer(query
);
5175 * read all operators in the system catalogs and return them in the
5176 * OprInfo* structure
5178 * numOprs is set to the number of operators read in
5181 getOperators(Archive
*fout
, int *numOprs
)
5186 PQExpBuffer query
= createPQExpBuffer();
5197 * find all operators, including builtin operators; we filter out
5198 * system-defined operators at dump-out time.
5201 appendPQExpBuffer(query
, "SELECT tableoid, oid, oprname, "
5203 "(%s oprowner) AS rolname, "
5205 "oprcode::oid AS oprcode "
5209 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5211 ntups
= PQntuples(res
);
5214 oprinfo
= (OprInfo
*) pg_malloc(ntups
* sizeof(OprInfo
));
5216 i_tableoid
= PQfnumber(res
, "tableoid");
5217 i_oid
= PQfnumber(res
, "oid");
5218 i_oprname
= PQfnumber(res
, "oprname");
5219 i_oprnamespace
= PQfnumber(res
, "oprnamespace");
5220 i_rolname
= PQfnumber(res
, "rolname");
5221 i_oprkind
= PQfnumber(res
, "oprkind");
5222 i_oprcode
= PQfnumber(res
, "oprcode");
5224 for (i
= 0; i
< ntups
; i
++)
5226 oprinfo
[i
].dobj
.objType
= DO_OPERATOR
;
5227 oprinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5228 oprinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5229 AssignDumpId(&oprinfo
[i
].dobj
);
5230 oprinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_oprname
));
5231 oprinfo
[i
].dobj
.namespace =
5233 atooid(PQgetvalue(res
, i
, i_oprnamespace
)));
5234 oprinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5235 oprinfo
[i
].oprkind
= (PQgetvalue(res
, i
, i_oprkind
))[0];
5236 oprinfo
[i
].oprcode
= atooid(PQgetvalue(res
, i
, i_oprcode
));
5238 /* Decide whether we want to dump it */
5239 selectDumpableObject(&(oprinfo
[i
].dobj
), fout
);
5241 /* Operators do not currently have ACLs. */
5242 oprinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5244 if (strlen(oprinfo
[i
].rolname
) == 0)
5245 pg_log_warning("owner of operator \"%s\" appears to be invalid",
5246 oprinfo
[i
].dobj
.name
);
5251 destroyPQExpBuffer(query
);
5258 * read all collations in the system catalogs and return them in the
5259 * CollInfo* structure
5261 * numCollations is set to the number of collations read in
5264 getCollations(Archive
*fout
, int *numCollations
)
5274 int i_collnamespace
;
5277 /* Collations didn't exist pre-9.1 */
5278 if (fout
->remoteVersion
< 90100)
5284 query
= createPQExpBuffer();
5287 * find all collations, including builtin collations; we filter out
5288 * system-defined collations at dump-out time.
5291 appendPQExpBuffer(query
, "SELECT tableoid, oid, collname, "
5293 "(%s collowner) AS rolname "
5294 "FROM pg_collation",
5297 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5299 ntups
= PQntuples(res
);
5300 *numCollations
= ntups
;
5302 collinfo
= (CollInfo
*) pg_malloc(ntups
* sizeof(CollInfo
));
5304 i_tableoid
= PQfnumber(res
, "tableoid");
5305 i_oid
= PQfnumber(res
, "oid");
5306 i_collname
= PQfnumber(res
, "collname");
5307 i_collnamespace
= PQfnumber(res
, "collnamespace");
5308 i_rolname
= PQfnumber(res
, "rolname");
5310 for (i
= 0; i
< ntups
; i
++)
5312 collinfo
[i
].dobj
.objType
= DO_COLLATION
;
5313 collinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5314 collinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5315 AssignDumpId(&collinfo
[i
].dobj
);
5316 collinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_collname
));
5317 collinfo
[i
].dobj
.namespace =
5319 atooid(PQgetvalue(res
, i
, i_collnamespace
)));
5320 collinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5322 /* Decide whether we want to dump it */
5323 selectDumpableObject(&(collinfo
[i
].dobj
), fout
);
5325 /* Collations do not currently have ACLs. */
5326 collinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5331 destroyPQExpBuffer(query
);
5338 * read all conversions in the system catalogs and return them in the
5339 * ConvInfo* structure
5341 * numConversions is set to the number of conversions read in
5344 getConversions(Archive
*fout
, int *numConversions
)
5357 query
= createPQExpBuffer();
5360 * find all conversions, including builtin conversions; we filter out
5361 * system-defined conversions at dump-out time.
5364 appendPQExpBuffer(query
, "SELECT tableoid, oid, conname, "
5366 "(%s conowner) AS rolname "
5367 "FROM pg_conversion",
5370 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5372 ntups
= PQntuples(res
);
5373 *numConversions
= ntups
;
5375 convinfo
= (ConvInfo
*) pg_malloc(ntups
* sizeof(ConvInfo
));
5377 i_tableoid
= PQfnumber(res
, "tableoid");
5378 i_oid
= PQfnumber(res
, "oid");
5379 i_conname
= PQfnumber(res
, "conname");
5380 i_connamespace
= PQfnumber(res
, "connamespace");
5381 i_rolname
= PQfnumber(res
, "rolname");
5383 for (i
= 0; i
< ntups
; i
++)
5385 convinfo
[i
].dobj
.objType
= DO_CONVERSION
;
5386 convinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5387 convinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5388 AssignDumpId(&convinfo
[i
].dobj
);
5389 convinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_conname
));
5390 convinfo
[i
].dobj
.namespace =
5392 atooid(PQgetvalue(res
, i
, i_connamespace
)));
5393 convinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5395 /* Decide whether we want to dump it */
5396 selectDumpableObject(&(convinfo
[i
].dobj
), fout
);
5398 /* Conversions do not currently have ACLs. */
5399 convinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5404 destroyPQExpBuffer(query
);
5411 * read all user-defined access methods in the system catalogs and return
5412 * them in the AccessMethodInfo* structure
5414 * numAccessMethods is set to the number of access methods read in
5417 getAccessMethods(Archive
*fout
, int *numAccessMethods
)
5423 AccessMethodInfo
*aminfo
;
5430 /* Before 9.6, there are no user-defined access methods */
5431 if (fout
->remoteVersion
< 90600)
5433 *numAccessMethods
= 0;
5437 query
= createPQExpBuffer();
5439 /* Select all access methods from pg_am table */
5440 appendPQExpBuffer(query
, "SELECT tableoid, oid, amname, amtype, "
5441 "amhandler::pg_catalog.regproc AS amhandler "
5444 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5446 ntups
= PQntuples(res
);
5447 *numAccessMethods
= ntups
;
5449 aminfo
= (AccessMethodInfo
*) pg_malloc(ntups
* sizeof(AccessMethodInfo
));
5451 i_tableoid
= PQfnumber(res
, "tableoid");
5452 i_oid
= PQfnumber(res
, "oid");
5453 i_amname
= PQfnumber(res
, "amname");
5454 i_amhandler
= PQfnumber(res
, "amhandler");
5455 i_amtype
= PQfnumber(res
, "amtype");
5457 for (i
= 0; i
< ntups
; i
++)
5459 aminfo
[i
].dobj
.objType
= DO_ACCESS_METHOD
;
5460 aminfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5461 aminfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5462 AssignDumpId(&aminfo
[i
].dobj
);
5463 aminfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_amname
));
5464 aminfo
[i
].dobj
.namespace = NULL
;
5465 aminfo
[i
].amhandler
= pg_strdup(PQgetvalue(res
, i
, i_amhandler
));
5466 aminfo
[i
].amtype
= *(PQgetvalue(res
, i
, i_amtype
));
5468 /* Decide whether we want to dump it */
5469 selectDumpableAccessMethod(&(aminfo
[i
]), fout
);
5471 /* Access methods do not currently have ACLs. */
5472 aminfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5477 destroyPQExpBuffer(query
);
5485 * read all opclasses in the system catalogs and return them in the
5486 * OpclassInfo* structure
5488 * numOpclasses is set to the number of opclasses read in
5491 getOpclasses(Archive
*fout
, int *numOpclasses
)
5496 PQExpBuffer query
= createPQExpBuffer();
5497 OpclassInfo
*opcinfo
;
5505 * find all opclasses, including builtin opclasses; we filter out
5506 * system-defined opclasses at dump-out time.
5509 appendPQExpBuffer(query
, "SELECT tableoid, oid, opcname, "
5511 "(%s opcowner) AS rolname "
5515 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5517 ntups
= PQntuples(res
);
5518 *numOpclasses
= ntups
;
5520 opcinfo
= (OpclassInfo
*) pg_malloc(ntups
* sizeof(OpclassInfo
));
5522 i_tableoid
= PQfnumber(res
, "tableoid");
5523 i_oid
= PQfnumber(res
, "oid");
5524 i_opcname
= PQfnumber(res
, "opcname");
5525 i_opcnamespace
= PQfnumber(res
, "opcnamespace");
5526 i_rolname
= PQfnumber(res
, "rolname");
5528 for (i
= 0; i
< ntups
; i
++)
5530 opcinfo
[i
].dobj
.objType
= DO_OPCLASS
;
5531 opcinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5532 opcinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5533 AssignDumpId(&opcinfo
[i
].dobj
);
5534 opcinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_opcname
));
5535 opcinfo
[i
].dobj
.namespace =
5537 atooid(PQgetvalue(res
, i
, i_opcnamespace
)));
5538 opcinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5540 /* Decide whether we want to dump it */
5541 selectDumpableObject(&(opcinfo
[i
].dobj
), fout
);
5543 /* Op Classes do not currently have ACLs. */
5544 opcinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5546 if (strlen(opcinfo
[i
].rolname
) == 0)
5547 pg_log_warning("owner of operator class \"%s\" appears to be invalid",
5548 opcinfo
[i
].dobj
.name
);
5553 destroyPQExpBuffer(query
);
5560 * read all opfamilies in the system catalogs and return them in the
5561 * OpfamilyInfo* structure
5563 * numOpfamilies is set to the number of opfamilies read in
5566 getOpfamilies(Archive
*fout
, int *numOpfamilies
)
5572 OpfamilyInfo
*opfinfo
;
5579 /* Before 8.3, there is no separate concept of opfamilies */
5580 if (fout
->remoteVersion
< 80300)
5586 query
= createPQExpBuffer();
5589 * find all opfamilies, including builtin opfamilies; we filter out
5590 * system-defined opfamilies at dump-out time.
5593 appendPQExpBuffer(query
, "SELECT tableoid, oid, opfname, "
5595 "(%s opfowner) AS rolname "
5599 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5601 ntups
= PQntuples(res
);
5602 *numOpfamilies
= ntups
;
5604 opfinfo
= (OpfamilyInfo
*) pg_malloc(ntups
* sizeof(OpfamilyInfo
));
5606 i_tableoid
= PQfnumber(res
, "tableoid");
5607 i_oid
= PQfnumber(res
, "oid");
5608 i_opfname
= PQfnumber(res
, "opfname");
5609 i_opfnamespace
= PQfnumber(res
, "opfnamespace");
5610 i_rolname
= PQfnumber(res
, "rolname");
5612 for (i
= 0; i
< ntups
; i
++)
5614 opfinfo
[i
].dobj
.objType
= DO_OPFAMILY
;
5615 opfinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5616 opfinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5617 AssignDumpId(&opfinfo
[i
].dobj
);
5618 opfinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_opfname
));
5619 opfinfo
[i
].dobj
.namespace =
5621 atooid(PQgetvalue(res
, i
, i_opfnamespace
)));
5622 opfinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5624 /* Decide whether we want to dump it */
5625 selectDumpableObject(&(opfinfo
[i
].dobj
), fout
);
5627 /* Extensions do not currently have ACLs. */
5628 opfinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5630 if (strlen(opfinfo
[i
].rolname
) == 0)
5631 pg_log_warning("owner of operator family \"%s\" appears to be invalid",
5632 opfinfo
[i
].dobj
.name
);
5637 destroyPQExpBuffer(query
);
5644 * read all the user-defined aggregates in the system catalogs and
5645 * return them in the AggInfo* structure
5647 * numAggs is set to the number of aggregates read in
5650 getAggregates(Archive
*fout
, int *numAggs
)
5652 DumpOptions
*dopt
= fout
->dopt
;
5656 PQExpBuffer query
= createPQExpBuffer();
5671 * Find all interesting aggregates. See comment in getFuncs() for the
5672 * rationale behind the filtering logic.
5674 if (fout
->remoteVersion
>= 90600)
5676 PQExpBuffer acl_subquery
= createPQExpBuffer();
5677 PQExpBuffer racl_subquery
= createPQExpBuffer();
5678 PQExpBuffer initacl_subquery
= createPQExpBuffer();
5679 PQExpBuffer initracl_subquery
= createPQExpBuffer();
5680 const char *agg_check
;
5682 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
5683 initracl_subquery
, "p.proacl", "p.proowner", "'f'",
5684 dopt
->binary_upgrade
);
5686 agg_check
= (fout
->remoteVersion
>= 110000 ? "p.prokind = 'a'"
5689 appendPQExpBuffer(query
, "SELECT p.tableoid, p.oid, "
5690 "p.proname AS aggname, "
5691 "p.pronamespace AS aggnamespace, "
5692 "p.pronargs, p.proargtypes, "
5693 "(%s p.proowner) AS rolname, "
5696 "%s AS initaggacl, "
5697 "%s AS initraggacl "
5699 "LEFT JOIN pg_init_privs pip ON "
5700 "(p.oid = pip.objoid "
5701 "AND pip.classoid = 'pg_proc'::regclass "
5702 "AND pip.objsubid = 0) "
5704 "p.pronamespace != "
5705 "(SELECT oid FROM pg_namespace "
5706 "WHERE nspname = 'pg_catalog') OR "
5707 "p.proacl IS DISTINCT FROM pip.initprivs",
5710 racl_subquery
->data
,
5711 initacl_subquery
->data
,
5712 initracl_subquery
->data
,
5714 if (dopt
->binary_upgrade
)
5715 appendPQExpBufferStr(query
,
5716 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5717 "classid = 'pg_proc'::regclass AND "
5718 "objid = p.oid AND "
5719 "refclassid = 'pg_extension'::regclass AND "
5721 appendPQExpBufferChar(query
, ')');
5723 destroyPQExpBuffer(acl_subquery
);
5724 destroyPQExpBuffer(racl_subquery
);
5725 destroyPQExpBuffer(initacl_subquery
);
5726 destroyPQExpBuffer(initracl_subquery
);
5728 else if (fout
->remoteVersion
>= 80200)
5730 appendPQExpBuffer(query
, "SELECT tableoid, oid, proname AS aggname, "
5731 "pronamespace AS aggnamespace, "
5732 "pronargs, proargtypes, "
5733 "(%s proowner) AS rolname, "
5734 "proacl AS aggacl, "
5736 "NULL AS initaggacl, NULL AS initraggacl "
5738 "WHERE proisagg AND ("
5740 "(SELECT oid FROM pg_namespace "
5741 "WHERE nspname = 'pg_catalog')",
5743 if (dopt
->binary_upgrade
&& fout
->remoteVersion
>= 90100)
5744 appendPQExpBufferStr(query
,
5745 " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5746 "classid = 'pg_proc'::regclass AND "
5747 "objid = p.oid AND "
5748 "refclassid = 'pg_extension'::regclass AND "
5750 appendPQExpBufferChar(query
, ')');
5754 appendPQExpBuffer(query
, "SELECT tableoid, oid, proname AS aggname, "
5755 "pronamespace AS aggnamespace, "
5756 "CASE WHEN proargtypes[0] = 'pg_catalog.\"any\"'::pg_catalog.regtype THEN 0 ELSE 1 END AS pronargs, "
5758 "(%s proowner) AS rolname, "
5759 "proacl AS aggacl, "
5761 "NULL AS initaggacl, NULL AS initraggacl "
5764 "AND pronamespace != "
5765 "(SELECT oid FROM pg_namespace WHERE nspname = 'pg_catalog')",
5769 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
5771 ntups
= PQntuples(res
);
5774 agginfo
= (AggInfo
*) pg_malloc(ntups
* sizeof(AggInfo
));
5776 i_tableoid
= PQfnumber(res
, "tableoid");
5777 i_oid
= PQfnumber(res
, "oid");
5778 i_aggname
= PQfnumber(res
, "aggname");
5779 i_aggnamespace
= PQfnumber(res
, "aggnamespace");
5780 i_pronargs
= PQfnumber(res
, "pronargs");
5781 i_proargtypes
= PQfnumber(res
, "proargtypes");
5782 i_rolname
= PQfnumber(res
, "rolname");
5783 i_aggacl
= PQfnumber(res
, "aggacl");
5784 i_raggacl
= PQfnumber(res
, "raggacl");
5785 i_initaggacl
= PQfnumber(res
, "initaggacl");
5786 i_initraggacl
= PQfnumber(res
, "initraggacl");
5788 for (i
= 0; i
< ntups
; i
++)
5790 agginfo
[i
].aggfn
.dobj
.objType
= DO_AGG
;
5791 agginfo
[i
].aggfn
.dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
5792 agginfo
[i
].aggfn
.dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
5793 AssignDumpId(&agginfo
[i
].aggfn
.dobj
);
5794 agginfo
[i
].aggfn
.dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_aggname
));
5795 agginfo
[i
].aggfn
.dobj
.namespace =
5797 atooid(PQgetvalue(res
, i
, i_aggnamespace
)));
5798 agginfo
[i
].aggfn
.rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
5799 if (strlen(agginfo
[i
].aggfn
.rolname
) == 0)
5800 pg_log_warning("owner of aggregate function \"%s\" appears to be invalid",
5801 agginfo
[i
].aggfn
.dobj
.name
);
5802 agginfo
[i
].aggfn
.lang
= InvalidOid
; /* not currently interesting */
5803 agginfo
[i
].aggfn
.prorettype
= InvalidOid
; /* not saved */
5804 agginfo
[i
].aggfn
.proacl
= pg_strdup(PQgetvalue(res
, i
, i_aggacl
));
5805 agginfo
[i
].aggfn
.rproacl
= pg_strdup(PQgetvalue(res
, i
, i_raggacl
));
5806 agginfo
[i
].aggfn
.initproacl
= pg_strdup(PQgetvalue(res
, i
, i_initaggacl
));
5807 agginfo
[i
].aggfn
.initrproacl
= pg_strdup(PQgetvalue(res
, i
, i_initraggacl
));
5808 agginfo
[i
].aggfn
.nargs
= atoi(PQgetvalue(res
, i
, i_pronargs
));
5809 if (agginfo
[i
].aggfn
.nargs
== 0)
5810 agginfo
[i
].aggfn
.argtypes
= NULL
;
5813 agginfo
[i
].aggfn
.argtypes
= (Oid
*) pg_malloc(agginfo
[i
].aggfn
.nargs
* sizeof(Oid
));
5814 parseOidArray(PQgetvalue(res
, i
, i_proargtypes
),
5815 agginfo
[i
].aggfn
.argtypes
,
5816 agginfo
[i
].aggfn
.nargs
);
5819 /* Decide whether we want to dump it */
5820 selectDumpableObject(&(agginfo
[i
].aggfn
.dobj
), fout
);
5822 /* Do not try to dump ACL if no ACL exists. */
5823 if (PQgetisnull(res
, i
, i_aggacl
) && PQgetisnull(res
, i
, i_raggacl
) &&
5824 PQgetisnull(res
, i
, i_initaggacl
) &&
5825 PQgetisnull(res
, i
, i_initraggacl
))
5826 agginfo
[i
].aggfn
.dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
5831 destroyPQExpBuffer(query
);
5838 * read all the user-defined functions in the system catalogs and
5839 * return them in the FuncInfo* structure
5841 * numFuncs is set to the number of functions read in
5844 getFuncs(Archive
*fout
, int *numFuncs
)
5846 DumpOptions
*dopt
= fout
->dopt
;
5850 PQExpBuffer query
= createPQExpBuffer();
5867 * Find all interesting functions. This is a bit complicated:
5869 * 1. Always exclude aggregates; those are handled elsewhere.
5871 * 2. Always exclude functions that are internally dependent on something
5872 * else, since presumably those will be created as a result of creating
5873 * the something else. This currently acts only to suppress constructor
5874 * functions for range types (so we only need it in 9.2 and up). Note
5875 * this is OK only because the constructors don't have any dependencies
5876 * the range type doesn't have; otherwise we might not get creation
5879 * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
5880 * they're members of extensions and we are in binary-upgrade mode then
5881 * include them, since we want to dump extension members individually in
5882 * that mode. Also, if they are used by casts or transforms then we need
5883 * to gather the information about them, though they won't be dumped if
5884 * they are built-in. Also, in 9.6 and up, include functions in
5885 * pg_catalog if they have an ACL different from what's shown in
5888 if (fout
->remoteVersion
>= 90600)
5890 PQExpBuffer acl_subquery
= createPQExpBuffer();
5891 PQExpBuffer racl_subquery
= createPQExpBuffer();
5892 PQExpBuffer initacl_subquery
= createPQExpBuffer();
5893 PQExpBuffer initracl_subquery
= createPQExpBuffer();
5894 const char *not_agg_check
;
5896 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
5897 initracl_subquery
, "p.proacl", "p.proowner", "'f'",
5898 dopt
->binary_upgrade
);
5900 not_agg_check
= (fout
->remoteVersion
>= 110000 ? "p.prokind <> 'a'"
5901 : "NOT p.proisagg");
5903 appendPQExpBuffer(query
,
5904 "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
5905 "p.pronargs, p.proargtypes, p.prorettype, "
5908 "%s AS initproacl, "
5909 "%s AS initrproacl, "
5911 "(%s p.proowner) AS rolname "
5913 "LEFT JOIN pg_init_privs pip ON "
5914 "(p.oid = pip.objoid "
5915 "AND pip.classoid = 'pg_proc'::regclass "
5916 "AND pip.objsubid = 0) "
5918 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5919 "WHERE classid = 'pg_proc'::regclass AND "
5920 "objid = p.oid AND deptype = 'i')"
5922 "\n pronamespace != "
5923 "(SELECT oid FROM pg_namespace "
5924 "WHERE nspname = 'pg_catalog')"
5925 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5926 "\n WHERE pg_cast.oid > %u "
5927 "\n AND p.oid = pg_cast.castfunc)"
5928 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5929 "\n WHERE pg_transform.oid > %u AND "
5930 "\n (p.oid = pg_transform.trffromsql"
5931 "\n OR p.oid = pg_transform.trftosql))",
5933 racl_subquery
->data
,
5934 initacl_subquery
->data
,
5935 initracl_subquery
->data
,
5939 g_last_builtin_oid
);
5940 if (dopt
->binary_upgrade
)
5941 appendPQExpBufferStr(query
,
5942 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5943 "classid = 'pg_proc'::regclass AND "
5944 "objid = p.oid AND "
5945 "refclassid = 'pg_extension'::regclass AND "
5947 appendPQExpBufferStr(query
,
5948 "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
5949 appendPQExpBufferChar(query
, ')');
5951 destroyPQExpBuffer(acl_subquery
);
5952 destroyPQExpBuffer(racl_subquery
);
5953 destroyPQExpBuffer(initacl_subquery
);
5954 destroyPQExpBuffer(initracl_subquery
);
5958 appendPQExpBuffer(query
,
5959 "SELECT tableoid, oid, proname, prolang, "
5960 "pronargs, proargtypes, prorettype, proacl, "
5962 "NULL as initproacl, NULL AS initrproacl, "
5964 "(%s proowner) AS rolname "
5966 "WHERE NOT proisagg",
5968 if (fout
->remoteVersion
>= 90200)
5969 appendPQExpBufferStr(query
,
5970 "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
5971 "WHERE classid = 'pg_proc'::regclass AND "
5972 "objid = p.oid AND deptype = 'i')");
5973 appendPQExpBuffer(query
,
5975 "\n pronamespace != "
5976 "(SELECT oid FROM pg_namespace "
5977 "WHERE nspname = 'pg_catalog')"
5978 "\n OR EXISTS (SELECT 1 FROM pg_cast"
5979 "\n WHERE pg_cast.oid > '%u'::oid"
5980 "\n AND p.oid = pg_cast.castfunc)",
5981 g_last_builtin_oid
);
5983 if (fout
->remoteVersion
>= 90500)
5984 appendPQExpBuffer(query
,
5985 "\n OR EXISTS (SELECT 1 FROM pg_transform"
5986 "\n WHERE pg_transform.oid > '%u'::oid"
5987 "\n AND (p.oid = pg_transform.trffromsql"
5988 "\n OR p.oid = pg_transform.trftosql))",
5989 g_last_builtin_oid
);
5991 if (dopt
->binary_upgrade
&& fout
->remoteVersion
>= 90100)
5992 appendPQExpBufferStr(query
,
5993 "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
5994 "classid = 'pg_proc'::regclass AND "
5995 "objid = p.oid AND "
5996 "refclassid = 'pg_extension'::regclass AND "
5998 appendPQExpBufferChar(query
, ')');
6001 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
6003 ntups
= PQntuples(res
);
6007 finfo
= (FuncInfo
*) pg_malloc0(ntups
* sizeof(FuncInfo
));
6009 i_tableoid
= PQfnumber(res
, "tableoid");
6010 i_oid
= PQfnumber(res
, "oid");
6011 i_proname
= PQfnumber(res
, "proname");
6012 i_pronamespace
= PQfnumber(res
, "pronamespace");
6013 i_rolname
= PQfnumber(res
, "rolname");
6014 i_prolang
= PQfnumber(res
, "prolang");
6015 i_pronargs
= PQfnumber(res
, "pronargs");
6016 i_proargtypes
= PQfnumber(res
, "proargtypes");
6017 i_prorettype
= PQfnumber(res
, "prorettype");
6018 i_proacl
= PQfnumber(res
, "proacl");
6019 i_rproacl
= PQfnumber(res
, "rproacl");
6020 i_initproacl
= PQfnumber(res
, "initproacl");
6021 i_initrproacl
= PQfnumber(res
, "initrproacl");
6023 for (i
= 0; i
< ntups
; i
++)
6025 finfo
[i
].dobj
.objType
= DO_FUNC
;
6026 finfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
6027 finfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
6028 AssignDumpId(&finfo
[i
].dobj
);
6029 finfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_proname
));
6030 finfo
[i
].dobj
.namespace =
6032 atooid(PQgetvalue(res
, i
, i_pronamespace
)));
6033 finfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
6034 finfo
[i
].lang
= atooid(PQgetvalue(res
, i
, i_prolang
));
6035 finfo
[i
].prorettype
= atooid(PQgetvalue(res
, i
, i_prorettype
));
6036 finfo
[i
].proacl
= pg_strdup(PQgetvalue(res
, i
, i_proacl
));
6037 finfo
[i
].rproacl
= pg_strdup(PQgetvalue(res
, i
, i_rproacl
));
6038 finfo
[i
].initproacl
= pg_strdup(PQgetvalue(res
, i
, i_initproacl
));
6039 finfo
[i
].initrproacl
= pg_strdup(PQgetvalue(res
, i
, i_initrproacl
));
6040 finfo
[i
].nargs
= atoi(PQgetvalue(res
, i
, i_pronargs
));
6041 if (finfo
[i
].nargs
== 0)
6042 finfo
[i
].argtypes
= NULL
;
6045 finfo
[i
].argtypes
= (Oid
*) pg_malloc(finfo
[i
].nargs
* sizeof(Oid
));
6046 parseOidArray(PQgetvalue(res
, i
, i_proargtypes
),
6047 finfo
[i
].argtypes
, finfo
[i
].nargs
);
6050 /* Decide whether we want to dump it */
6051 selectDumpableObject(&(finfo
[i
].dobj
), fout
);
6053 /* Do not try to dump ACL if no ACL exists. */
6054 if (PQgetisnull(res
, i
, i_proacl
) && PQgetisnull(res
, i
, i_rproacl
) &&
6055 PQgetisnull(res
, i
, i_initproacl
) &&
6056 PQgetisnull(res
, i
, i_initrproacl
))
6057 finfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
6059 if (strlen(finfo
[i
].rolname
) == 0)
6060 pg_log_warning("owner of function \"%s\" appears to be invalid",
6061 finfo
[i
].dobj
.name
);
6066 destroyPQExpBuffer(query
);
6073 * read all the tables (no indexes)
6074 * in the system catalogs return them in the TableInfo* structure
6076 * numTables is set to the number of tables read in
6079 getTables(Archive
*fout
, int *numTables
)
6081 DumpOptions
*dopt
= fout
->dopt
;
6085 PQExpBuffer query
= createPQExpBuffer();
6098 int i_relhastriggers
;
6102 int i_relforcerowsec
;
6107 int i_toastfrozenxid
;
6109 int i_relpersistence
;
6110 int i_relispopulated
;
6114 int i_reltablespace
;
6117 int i_toastreloptions
;
6120 int i_is_identity_sequence
;
6126 * Find all the tables and table-like objects.
6128 * We must fetch all tables in this phase because otherwise we cannot
6129 * correctly identify inherited columns, owned sequences, etc.
6131 * We include system catalogs, so that we can work if a user table is
6132 * defined to inherit from a system catalog (pretty weird, but...)
6134 * We ignore relations that are not ordinary tables, sequences, views,
6135 * materialized views, composite types, or foreign tables.
6137 * Composite-type table entries won't be dumped as such, but we have to
6138 * make a DumpableObject for them so that we can track dependencies of the
6139 * composite type (pg_depend entries for columns of the composite type
6140 * link to the pg_class entry not the pg_type entry).
6142 * Note: in this phase we should collect only a minimal amount of
6143 * information about each table, basically just enough to decide if it is
6144 * interesting. In particular, since we do not yet have lock on any user
6145 * table, we MUST NOT invoke any server-side data collection functions
6146 * (for instance, pg_get_partkeydef()). Those are likely to fail or give
6147 * wrong answers if any concurrent DDL is happening.
6149 * We purposefully ignore toast OIDs for partitioned tables; the reason is
6150 * that versions 10 and 11 have them, but 12 does not, so emitting them
6151 * causes the upgrade to fail.
6154 if (fout
->remoteVersion
>= 90600)
6156 char *ispartition
= "false";
6157 char *relhasoids
= "c.relhasoids";
6159 PQExpBuffer acl_subquery
= createPQExpBuffer();
6160 PQExpBuffer racl_subquery
= createPQExpBuffer();
6161 PQExpBuffer initacl_subquery
= createPQExpBuffer();
6162 PQExpBuffer initracl_subquery
= createPQExpBuffer();
6164 PQExpBuffer attacl_subquery
= createPQExpBuffer();
6165 PQExpBuffer attracl_subquery
= createPQExpBuffer();
6166 PQExpBuffer attinitacl_subquery
= createPQExpBuffer();
6167 PQExpBuffer attinitracl_subquery
= createPQExpBuffer();
6170 * Collect the information about any partitioned tables, which were
6173 if (fout
->remoteVersion
>= 100000)
6174 ispartition
= "c.relispartition";
6176 /* In PG12 upwards WITH OIDS does not exist anymore. */
6177 if (fout
->remoteVersion
>= 120000)
6178 relhasoids
= "'f'::bool";
6181 * Left join to pick up dependency info linking sequences to their
6182 * owning column, if any (note this dependency is AUTO as of 8.2)
6184 * Left join to detect if any privileges are still as-set-at-init, in
6185 * which case we won't dump out ACL commands for those.
6188 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
6189 initracl_subquery
, "c.relacl", "c.relowner",
6190 "CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE
)
6191 " THEN 's' ELSE 'r' END::\"char\"",
6192 dopt
->binary_upgrade
);
6194 buildACLQueries(attacl_subquery
, attracl_subquery
, attinitacl_subquery
,
6195 attinitracl_subquery
, "at.attacl", "c.relowner", "'c'",
6196 dopt
->binary_upgrade
);
6198 appendPQExpBuffer(query
,
6199 "SELECT c.tableoid, c.oid, c.relname, "
6200 "%s AS relacl, %s as rrelacl, "
6201 "%s AS initrelacl, %s as initrrelacl, "
6202 "c.relkind, c.relnamespace, "
6203 "(%s c.relowner) AS rolname, "
6204 "c.relchecks, c.relhastriggers, "
6205 "c.relhasindex, c.relhasrules, %s AS relhasoids, "
6206 "c.relrowsecurity, c.relforcerowsecurity, "
6207 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6208 "tc.relfrozenxid AS tfrozenxid, "
6209 "tc.relminmxid AS tminmxid, "
6210 "c.relpersistence, c.relispopulated, "
6211 "c.relreplident, c.relpages, am.amname, "
6213 "d.refobjid AS owning_tab, "
6214 "d.refobjsubid AS owning_col, "
6215 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6216 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6217 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6218 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6219 "tc.reloptions AS toast_reloptions, "
6220 "c.relkind = '%c' AND EXISTS (SELECT 1 FROM pg_depend WHERE classid = 'pg_class'::regclass AND objid = c.oid AND objsubid = 0 AND refclassid = 'pg_class'::regclass AND deptype = 'i') AS is_identity_sequence, "
6221 "EXISTS (SELECT 1 FROM pg_attribute at LEFT JOIN pg_init_privs pip ON "
6222 "(c.oid = pip.objoid "
6223 "AND pip.classoid = 'pg_class'::regclass "
6224 "AND pip.objsubid = at.attnum)"
6225 "WHERE at.attrelid = c.oid AND ("
6227 "OR %s IS NOT NULL "
6228 "OR %s IS NOT NULL "
6232 "%s AS ispartition "
6234 "LEFT JOIN pg_depend d ON "
6235 "(c.relkind = '%c' AND "
6236 "d.classid = c.tableoid AND d.objid = c.oid AND "
6237 "d.objsubid = 0 AND "
6238 "d.refclassid = c.tableoid AND d.deptype IN ('a', 'i')) "
6239 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid AND c.relkind <> '%c') "
6240 "LEFT JOIN pg_am am ON (c.relam = am.oid) "
6241 "LEFT JOIN pg_init_privs pip ON "
6242 "(c.oid = pip.objoid "
6243 "AND pip.classoid = 'pg_class'::regclass "
6244 "AND pip.objsubid = 0) "
6245 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c', '%c') "
6248 racl_subquery
->data
,
6249 initacl_subquery
->data
,
6250 initracl_subquery
->data
,
6254 attacl_subquery
->data
,
6255 attracl_subquery
->data
,
6256 attinitacl_subquery
->data
,
6257 attinitracl_subquery
->data
,
6260 RELKIND_PARTITIONED_TABLE
,
6261 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6262 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
,
6263 RELKIND_MATVIEW
, RELKIND_FOREIGN_TABLE
,
6264 RELKIND_PARTITIONED_TABLE
);
6266 destroyPQExpBuffer(acl_subquery
);
6267 destroyPQExpBuffer(racl_subquery
);
6268 destroyPQExpBuffer(initacl_subquery
);
6269 destroyPQExpBuffer(initracl_subquery
);
6271 destroyPQExpBuffer(attacl_subquery
);
6272 destroyPQExpBuffer(attracl_subquery
);
6273 destroyPQExpBuffer(attinitacl_subquery
);
6274 destroyPQExpBuffer(attinitracl_subquery
);
6276 else if (fout
->remoteVersion
>= 90500)
6279 * Left join to pick up dependency info linking sequences to their
6280 * owning column, if any (note this dependency is AUTO as of 8.2)
6282 appendPQExpBuffer(query
,
6283 "SELECT c.tableoid, c.oid, c.relname, "
6284 "c.relacl, NULL as rrelacl, "
6285 "NULL AS initrelacl, NULL AS initrrelacl, "
6288 "(%s c.relowner) AS rolname, "
6289 "c.relchecks, c.relhastriggers, "
6290 "c.relhasindex, c.relhasrules, c.relhasoids, "
6291 "c.relrowsecurity, c.relforcerowsecurity, "
6292 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6293 "tc.relfrozenxid AS tfrozenxid, "
6294 "tc.relminmxid AS tminmxid, "
6295 "c.relpersistence, c.relispopulated, "
6296 "c.relreplident, c.relpages, "
6299 "d.refobjid AS owning_tab, "
6300 "d.refobjsubid AS owning_col, "
6301 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6302 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6303 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6304 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6305 "tc.reloptions AS toast_reloptions, "
6306 "NULL AS changed_acl, "
6307 "false AS ispartition "
6309 "LEFT JOIN pg_depend d ON "
6310 "(c.relkind = '%c' AND "
6311 "d.classid = c.tableoid AND d.objid = c.oid AND "
6312 "d.objsubid = 0 AND "
6313 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6314 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6315 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6319 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6320 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
,
6321 RELKIND_MATVIEW
, RELKIND_FOREIGN_TABLE
);
6323 else if (fout
->remoteVersion
>= 90400)
6326 * Left join to pick up dependency info linking sequences to their
6327 * owning column, if any (note this dependency is AUTO as of 8.2)
6329 appendPQExpBuffer(query
,
6330 "SELECT c.tableoid, c.oid, c.relname, "
6331 "c.relacl, NULL as rrelacl, "
6332 "NULL AS initrelacl, NULL AS initrrelacl, "
6335 "(%s c.relowner) AS rolname, "
6336 "c.relchecks, c.relhastriggers, "
6337 "c.relhasindex, c.relhasrules, c.relhasoids, "
6338 "'f'::bool AS relrowsecurity, "
6339 "'f'::bool AS relforcerowsecurity, "
6340 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6341 "tc.relfrozenxid AS tfrozenxid, "
6342 "tc.relminmxid AS tminmxid, "
6343 "c.relpersistence, c.relispopulated, "
6344 "c.relreplident, c.relpages, "
6347 "d.refobjid AS owning_tab, "
6348 "d.refobjsubid AS owning_col, "
6349 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6350 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6351 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6352 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6353 "tc.reloptions AS toast_reloptions, "
6354 "NULL AS changed_acl, "
6355 "false AS ispartition "
6357 "LEFT JOIN pg_depend d ON "
6358 "(c.relkind = '%c' AND "
6359 "d.classid = c.tableoid AND d.objid = c.oid AND "
6360 "d.objsubid = 0 AND "
6361 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6362 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6363 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6367 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6368 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
,
6369 RELKIND_MATVIEW
, RELKIND_FOREIGN_TABLE
);
6371 else if (fout
->remoteVersion
>= 90300)
6374 * Left join to pick up dependency info linking sequences to their
6375 * owning column, if any (note this dependency is AUTO as of 8.2)
6377 appendPQExpBuffer(query
,
6378 "SELECT c.tableoid, c.oid, c.relname, "
6379 "c.relacl, NULL as rrelacl, "
6380 "NULL AS initrelacl, NULL AS initrrelacl, "
6383 "(%s c.relowner) AS rolname, "
6384 "c.relchecks, c.relhastriggers, "
6385 "c.relhasindex, c.relhasrules, c.relhasoids, "
6386 "'f'::bool AS relrowsecurity, "
6387 "'f'::bool AS relforcerowsecurity, "
6388 "c.relfrozenxid, c.relminmxid, tc.oid AS toid, "
6389 "tc.relfrozenxid AS tfrozenxid, "
6390 "tc.relminmxid AS tminmxid, "
6391 "c.relpersistence, c.relispopulated, "
6392 "'d' AS relreplident, c.relpages, "
6395 "d.refobjid AS owning_tab, "
6396 "d.refobjsubid AS owning_col, "
6397 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6398 "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6399 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6400 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, "
6401 "tc.reloptions AS toast_reloptions, "
6402 "NULL AS changed_acl, "
6403 "false AS ispartition "
6405 "LEFT JOIN pg_depend d ON "
6406 "(c.relkind = '%c' AND "
6407 "d.classid = c.tableoid AND d.objid = c.oid AND "
6408 "d.objsubid = 0 AND "
6409 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6410 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6411 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6415 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6416 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
,
6417 RELKIND_MATVIEW
, RELKIND_FOREIGN_TABLE
);
6419 else if (fout
->remoteVersion
>= 90100)
6422 * Left join to pick up dependency info linking sequences to their
6423 * owning column, if any (note this dependency is AUTO as of 8.2)
6425 appendPQExpBuffer(query
,
6426 "SELECT c.tableoid, c.oid, c.relname, "
6427 "c.relacl, NULL as rrelacl, "
6428 "NULL AS initrelacl, NULL AS initrrelacl, "
6431 "(%s c.relowner) AS rolname, "
6432 "c.relchecks, c.relhastriggers, "
6433 "c.relhasindex, c.relhasrules, c.relhasoids, "
6434 "'f'::bool AS relrowsecurity, "
6435 "'f'::bool AS relforcerowsecurity, "
6436 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6437 "tc.relfrozenxid AS tfrozenxid, "
6439 "c.relpersistence, 't' as relispopulated, "
6440 "'d' AS relreplident, c.relpages, "
6443 "d.refobjid AS owning_tab, "
6444 "d.refobjsubid AS owning_col, "
6445 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6446 "c.reloptions AS reloptions, "
6447 "tc.reloptions AS toast_reloptions, "
6448 "NULL AS changed_acl, "
6449 "false AS ispartition "
6451 "LEFT JOIN pg_depend d ON "
6452 "(c.relkind = '%c' AND "
6453 "d.classid = c.tableoid AND d.objid = c.oid AND "
6454 "d.objsubid = 0 AND "
6455 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6456 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6457 "WHERE c.relkind in ('%c', '%c', '%c', '%c', '%c', '%c') "
6461 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6462 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
,
6463 RELKIND_MATVIEW
, RELKIND_FOREIGN_TABLE
);
6465 else if (fout
->remoteVersion
>= 90000)
6468 * Left join to pick up dependency info linking sequences to their
6469 * owning column, if any (note this dependency is AUTO as of 8.2)
6471 appendPQExpBuffer(query
,
6472 "SELECT c.tableoid, c.oid, c.relname, "
6473 "c.relacl, NULL as rrelacl, "
6474 "NULL AS initrelacl, NULL AS initrrelacl, "
6477 "(%s c.relowner) AS rolname, "
6478 "c.relchecks, c.relhastriggers, "
6479 "c.relhasindex, c.relhasrules, c.relhasoids, "
6480 "'f'::bool AS relrowsecurity, "
6481 "'f'::bool AS relforcerowsecurity, "
6482 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6483 "tc.relfrozenxid AS tfrozenxid, "
6485 "'p' AS relpersistence, 't' as relispopulated, "
6486 "'d' AS relreplident, c.relpages, "
6489 "d.refobjid AS owning_tab, "
6490 "d.refobjsubid AS owning_col, "
6491 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6492 "c.reloptions AS reloptions, "
6493 "tc.reloptions AS toast_reloptions, "
6494 "NULL AS changed_acl, "
6495 "false AS ispartition "
6497 "LEFT JOIN pg_depend d ON "
6498 "(c.relkind = '%c' AND "
6499 "d.classid = c.tableoid AND d.objid = c.oid AND "
6500 "d.objsubid = 0 AND "
6501 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6502 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6503 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6507 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6508 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
);
6510 else if (fout
->remoteVersion
>= 80400)
6513 * Left join to pick up dependency info linking sequences to their
6514 * owning column, if any (note this dependency is AUTO as of 8.2)
6516 appendPQExpBuffer(query
,
6517 "SELECT c.tableoid, c.oid, c.relname, "
6518 "c.relacl, NULL as rrelacl, "
6519 "NULL AS initrelacl, NULL AS initrrelacl, "
6522 "(%s c.relowner) AS rolname, "
6523 "c.relchecks, c.relhastriggers, "
6524 "c.relhasindex, c.relhasrules, c.relhasoids, "
6525 "'f'::bool AS relrowsecurity, "
6526 "'f'::bool AS relforcerowsecurity, "
6527 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6528 "tc.relfrozenxid AS tfrozenxid, "
6530 "'p' AS relpersistence, 't' as relispopulated, "
6531 "'d' AS relreplident, c.relpages, "
6534 "d.refobjid AS owning_tab, "
6535 "d.refobjsubid AS owning_col, "
6536 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6537 "c.reloptions AS reloptions, "
6538 "tc.reloptions AS toast_reloptions, "
6539 "NULL AS changed_acl, "
6540 "false AS ispartition "
6542 "LEFT JOIN pg_depend d ON "
6543 "(c.relkind = '%c' AND "
6544 "d.classid = c.tableoid AND d.objid = c.oid AND "
6545 "d.objsubid = 0 AND "
6546 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6547 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6548 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6552 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6553 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
);
6555 else if (fout
->remoteVersion
>= 80200)
6558 * Left join to pick up dependency info linking sequences to their
6559 * owning column, if any (note this dependency is AUTO as of 8.2)
6561 appendPQExpBuffer(query
,
6562 "SELECT c.tableoid, c.oid, c.relname, "
6563 "c.relacl, NULL as rrelacl, "
6564 "NULL AS initrelacl, NULL AS initrrelacl, "
6567 "(%s c.relowner) AS rolname, "
6568 "c.relchecks, (c.reltriggers <> 0) AS relhastriggers, "
6569 "c.relhasindex, c.relhasrules, c.relhasoids, "
6570 "'f'::bool AS relrowsecurity, "
6571 "'f'::bool AS relforcerowsecurity, "
6572 "c.relfrozenxid, 0 AS relminmxid, tc.oid AS toid, "
6573 "tc.relfrozenxid AS tfrozenxid, "
6575 "'p' AS relpersistence, 't' as relispopulated, "
6576 "'d' AS relreplident, c.relpages, "
6579 "d.refobjid AS owning_tab, "
6580 "d.refobjsubid AS owning_col, "
6581 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6582 "c.reloptions AS reloptions, "
6583 "NULL AS toast_reloptions, "
6584 "NULL AS changed_acl, "
6585 "false AS ispartition "
6587 "LEFT JOIN pg_depend d ON "
6588 "(c.relkind = '%c' AND "
6589 "d.classid = c.tableoid AND d.objid = c.oid AND "
6590 "d.objsubid = 0 AND "
6591 "d.refclassid = c.tableoid AND d.deptype = 'a') "
6592 "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid) "
6593 "WHERE c.relkind in ('%c', '%c', '%c', '%c') "
6597 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6598 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
);
6603 * Left join to pick up dependency info linking sequences to their
6604 * owning column, if any
6606 appendPQExpBuffer(query
,
6607 "SELECT c.tableoid, c.oid, relname, "
6608 "relacl, NULL as rrelacl, "
6609 "NULL AS initrelacl, NULL AS initrrelacl, "
6610 "relkind, relnamespace, "
6611 "(%s relowner) AS rolname, "
6612 "relchecks, (reltriggers <> 0) AS relhastriggers, "
6613 "relhasindex, relhasrules, relhasoids, "
6614 "'f'::bool AS relrowsecurity, "
6615 "'f'::bool AS relforcerowsecurity, "
6616 "0 AS relfrozenxid, 0 AS relminmxid,"
6618 "0 AS tfrozenxid, 0 AS tminmxid,"
6619 "'p' AS relpersistence, 't' as relispopulated, "
6620 "'d' AS relreplident, relpages, "
6623 "d.refobjid AS owning_tab, "
6624 "d.refobjsubid AS owning_col, "
6625 "(SELECT spcname FROM pg_tablespace t WHERE t.oid = c.reltablespace) AS reltablespace, "
6626 "NULL AS reloptions, "
6627 "NULL AS toast_reloptions, "
6628 "NULL AS changed_acl, "
6629 "false AS ispartition "
6631 "LEFT JOIN pg_depend d ON "
6632 "(c.relkind = '%c' AND "
6633 "d.classid = c.tableoid AND d.objid = c.oid AND "
6634 "d.objsubid = 0 AND "
6635 "d.refclassid = c.tableoid AND d.deptype = 'i') "
6636 "WHERE relkind in ('%c', '%c', '%c', '%c') "
6640 RELKIND_RELATION
, RELKIND_SEQUENCE
,
6641 RELKIND_VIEW
, RELKIND_COMPOSITE_TYPE
);
6644 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
6646 ntups
= PQntuples(res
);
6651 * Extract data from result and lock dumpable tables. We do the locking
6652 * before anything else, to minimize the window wherein a table could
6653 * disappear under us.
6655 * Note that we have to save info about all tables here, even when dumping
6656 * only one, because we don't yet know which tables might be inheritance
6657 * ancestors of the target table.
6659 tblinfo
= (TableInfo
*) pg_malloc0(ntups
* sizeof(TableInfo
));
6661 i_reltableoid
= PQfnumber(res
, "tableoid");
6662 i_reloid
= PQfnumber(res
, "oid");
6663 i_relname
= PQfnumber(res
, "relname");
6664 i_relnamespace
= PQfnumber(res
, "relnamespace");
6665 i_relacl
= PQfnumber(res
, "relacl");
6666 i_rrelacl
= PQfnumber(res
, "rrelacl");
6667 i_initrelacl
= PQfnumber(res
, "initrelacl");
6668 i_initrrelacl
= PQfnumber(res
, "initrrelacl");
6669 i_relkind
= PQfnumber(res
, "relkind");
6670 i_rolname
= PQfnumber(res
, "rolname");
6671 i_relchecks
= PQfnumber(res
, "relchecks");
6672 i_relhastriggers
= PQfnumber(res
, "relhastriggers");
6673 i_relhasindex
= PQfnumber(res
, "relhasindex");
6674 i_relhasrules
= PQfnumber(res
, "relhasrules");
6675 i_relrowsec
= PQfnumber(res
, "relrowsecurity");
6676 i_relforcerowsec
= PQfnumber(res
, "relforcerowsecurity");
6677 i_relhasoids
= PQfnumber(res
, "relhasoids");
6678 i_relfrozenxid
= PQfnumber(res
, "relfrozenxid");
6679 i_relminmxid
= PQfnumber(res
, "relminmxid");
6680 i_toastoid
= PQfnumber(res
, "toid");
6681 i_toastfrozenxid
= PQfnumber(res
, "tfrozenxid");
6682 i_toastminmxid
= PQfnumber(res
, "tminmxid");
6683 i_relpersistence
= PQfnumber(res
, "relpersistence");
6684 i_relispopulated
= PQfnumber(res
, "relispopulated");
6685 i_relreplident
= PQfnumber(res
, "relreplident");
6686 i_relpages
= PQfnumber(res
, "relpages");
6687 i_owning_tab
= PQfnumber(res
, "owning_tab");
6688 i_owning_col
= PQfnumber(res
, "owning_col");
6689 i_reltablespace
= PQfnumber(res
, "reltablespace");
6690 i_reloptions
= PQfnumber(res
, "reloptions");
6691 i_checkoption
= PQfnumber(res
, "checkoption");
6692 i_toastreloptions
= PQfnumber(res
, "toast_reloptions");
6693 i_reloftype
= PQfnumber(res
, "reloftype");
6694 i_is_identity_sequence
= PQfnumber(res
, "is_identity_sequence");
6695 i_changed_acl
= PQfnumber(res
, "changed_acl");
6696 i_ispartition
= PQfnumber(res
, "ispartition");
6697 i_amname
= PQfnumber(res
, "amname");
6699 if (dopt
->lockWaitTimeout
)
6702 * Arrange to fail instead of waiting forever for a table lock.
6704 * NB: this coding assumes that the only queries issued within the
6705 * following loop are LOCK TABLEs; else the timeout may be undesirably
6706 * applied to other things too.
6708 resetPQExpBuffer(query
);
6709 appendPQExpBufferStr(query
, "SET statement_timeout = ");
6710 appendStringLiteralConn(query
, dopt
->lockWaitTimeout
, GetConnection(fout
));
6711 ExecuteSqlStatement(fout
, query
->data
);
6714 for (i
= 0; i
< ntups
; i
++)
6716 tblinfo
[i
].dobj
.objType
= DO_TABLE
;
6717 tblinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_reltableoid
));
6718 tblinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_reloid
));
6719 AssignDumpId(&tblinfo
[i
].dobj
);
6720 tblinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_relname
));
6721 tblinfo
[i
].dobj
.namespace =
6723 atooid(PQgetvalue(res
, i
, i_relnamespace
)));
6724 tblinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
6725 tblinfo
[i
].relacl
= pg_strdup(PQgetvalue(res
, i
, i_relacl
));
6726 tblinfo
[i
].rrelacl
= pg_strdup(PQgetvalue(res
, i
, i_rrelacl
));
6727 tblinfo
[i
].initrelacl
= pg_strdup(PQgetvalue(res
, i
, i_initrelacl
));
6728 tblinfo
[i
].initrrelacl
= pg_strdup(PQgetvalue(res
, i
, i_initrrelacl
));
6729 tblinfo
[i
].relkind
= *(PQgetvalue(res
, i
, i_relkind
));
6730 tblinfo
[i
].relpersistence
= *(PQgetvalue(res
, i
, i_relpersistence
));
6731 tblinfo
[i
].hasindex
= (strcmp(PQgetvalue(res
, i
, i_relhasindex
), "t") == 0);
6732 tblinfo
[i
].hasrules
= (strcmp(PQgetvalue(res
, i
, i_relhasrules
), "t") == 0);
6733 tblinfo
[i
].hastriggers
= (strcmp(PQgetvalue(res
, i
, i_relhastriggers
), "t") == 0);
6734 tblinfo
[i
].rowsec
= (strcmp(PQgetvalue(res
, i
, i_relrowsec
), "t") == 0);
6735 tblinfo
[i
].forcerowsec
= (strcmp(PQgetvalue(res
, i
, i_relforcerowsec
), "t") == 0);
6736 tblinfo
[i
].hasoids
= (strcmp(PQgetvalue(res
, i
, i_relhasoids
), "t") == 0);
6737 tblinfo
[i
].relispopulated
= (strcmp(PQgetvalue(res
, i
, i_relispopulated
), "t") == 0);
6738 tblinfo
[i
].relreplident
= *(PQgetvalue(res
, i
, i_relreplident
));
6739 tblinfo
[i
].relpages
= atoi(PQgetvalue(res
, i
, i_relpages
));
6740 tblinfo
[i
].frozenxid
= atooid(PQgetvalue(res
, i
, i_relfrozenxid
));
6741 tblinfo
[i
].minmxid
= atooid(PQgetvalue(res
, i
, i_relminmxid
));
6742 tblinfo
[i
].toast_oid
= atooid(PQgetvalue(res
, i
, i_toastoid
));
6743 tblinfo
[i
].toast_frozenxid
= atooid(PQgetvalue(res
, i
, i_toastfrozenxid
));
6744 tblinfo
[i
].toast_minmxid
= atooid(PQgetvalue(res
, i
, i_toastminmxid
));
6745 tblinfo
[i
].reloftype
= atooid(PQgetvalue(res
, i
, i_reloftype
));
6746 tblinfo
[i
].ncheck
= atoi(PQgetvalue(res
, i
, i_relchecks
));
6747 if (PQgetisnull(res
, i
, i_owning_tab
))
6749 tblinfo
[i
].owning_tab
= InvalidOid
;
6750 tblinfo
[i
].owning_col
= 0;
6754 tblinfo
[i
].owning_tab
= atooid(PQgetvalue(res
, i
, i_owning_tab
));
6755 tblinfo
[i
].owning_col
= atoi(PQgetvalue(res
, i
, i_owning_col
));
6757 tblinfo
[i
].reltablespace
= pg_strdup(PQgetvalue(res
, i
, i_reltablespace
));
6758 tblinfo
[i
].reloptions
= pg_strdup(PQgetvalue(res
, i
, i_reloptions
));
6759 if (i_checkoption
== -1 || PQgetisnull(res
, i
, i_checkoption
))
6760 tblinfo
[i
].checkoption
= NULL
;
6762 tblinfo
[i
].checkoption
= pg_strdup(PQgetvalue(res
, i
, i_checkoption
));
6763 tblinfo
[i
].toast_reloptions
= pg_strdup(PQgetvalue(res
, i
, i_toastreloptions
));
6764 if (PQgetisnull(res
, i
, i_amname
))
6765 tblinfo
[i
].amname
= NULL
;
6767 tblinfo
[i
].amname
= pg_strdup(PQgetvalue(res
, i
, i_amname
));
6769 /* other fields were zeroed above */
6772 * Decide whether we want to dump this table.
6774 if (tblinfo
[i
].relkind
== RELKIND_COMPOSITE_TYPE
)
6775 tblinfo
[i
].dobj
.dump
= DUMP_COMPONENT_NONE
;
6777 selectDumpableTable(&tblinfo
[i
], fout
);
6780 * If the table-level and all column-level ACLs for this table are
6781 * unchanged, then we don't need to worry about including the ACLs for
6782 * this table. If any column-level ACLs have been changed, the
6783 * 'changed_acl' column from the query will indicate that.
6785 * This can result in a significant performance improvement in cases
6786 * where we are only looking to dump out the ACL (eg: pg_catalog).
6788 if (PQgetisnull(res
, i
, i_relacl
) && PQgetisnull(res
, i
, i_rrelacl
) &&
6789 PQgetisnull(res
, i
, i_initrelacl
) &&
6790 PQgetisnull(res
, i
, i_initrrelacl
) &&
6791 strcmp(PQgetvalue(res
, i
, i_changed_acl
), "f") == 0)
6792 tblinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
6794 tblinfo
[i
].interesting
= tblinfo
[i
].dobj
.dump
? true : false;
6795 tblinfo
[i
].dummy_view
= false; /* might get set during sort */
6796 tblinfo
[i
].postponed_def
= false; /* might get set during sort */
6798 tblinfo
[i
].is_identity_sequence
= (i_is_identity_sequence
>= 0 &&
6799 strcmp(PQgetvalue(res
, i
, i_is_identity_sequence
), "t") == 0);
6802 tblinfo
[i
].ispartition
= (strcmp(PQgetvalue(res
, i
, i_ispartition
), "t") == 0);
6805 * Read-lock target tables to make sure they aren't DROPPED or altered
6806 * in schema before we get around to dumping them.
6808 * Note that we don't explicitly lock parents of the target tables; we
6809 * assume our lock on the child is enough to prevent schema
6810 * alterations to parent tables.
6812 * NOTE: it'd be kinda nice to lock other relations too, not only
6813 * plain or partitioned tables, but the backend doesn't presently
6816 * We only need to lock the table for certain components; see
6819 if (tblinfo
[i
].dobj
.dump
&&
6820 (tblinfo
[i
].relkind
== RELKIND_RELATION
||
6821 tblinfo
[i
].relkind
== RELKIND_PARTITIONED_TABLE
) &&
6822 (tblinfo
[i
].dobj
.dump
& DUMP_COMPONENTS_REQUIRING_LOCK
))
6824 resetPQExpBuffer(query
);
6825 appendPQExpBuffer(query
,
6826 "LOCK TABLE %s IN ACCESS SHARE MODE",
6827 fmtQualifiedDumpable(&tblinfo
[i
]));
6828 ExecuteSqlStatement(fout
, query
->data
);
6831 /* Emit notice if join for owner failed */
6832 if (strlen(tblinfo
[i
].rolname
) == 0)
6833 pg_log_warning("owner of table \"%s\" appears to be invalid",
6834 tblinfo
[i
].dobj
.name
);
6837 if (dopt
->lockWaitTimeout
)
6839 ExecuteSqlStatement(fout
, "SET statement_timeout = 0");
6844 destroyPQExpBuffer(query
);
6851 * identify owned sequences and mark them as dumpable if owning table is
6853 * We used to do this in getTables(), but it's better to do it after the
6854 * index used by findTableByOid() has been set up.
6857 getOwnedSeqs(Archive
*fout
, TableInfo tblinfo
[], int numTables
)
6862 * Force sequences that are "owned" by table columns to be dumped whenever
6863 * their owning table is being dumped.
6865 for (i
= 0; i
< numTables
; i
++)
6867 TableInfo
*seqinfo
= &tblinfo
[i
];
6868 TableInfo
*owning_tab
;
6870 if (!OidIsValid(seqinfo
->owning_tab
))
6871 continue; /* not an owned sequence */
6873 owning_tab
= findTableByOid(seqinfo
->owning_tab
);
6874 if (owning_tab
== NULL
)
6875 fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
6876 seqinfo
->owning_tab
, seqinfo
->dobj
.catId
.oid
);
6879 * Only dump identity sequences if we're going to dump the table that
6882 if (owning_tab
->dobj
.dump
== DUMP_COMPONENT_NONE
&&
6883 seqinfo
->is_identity_sequence
)
6885 seqinfo
->dobj
.dump
= DUMP_COMPONENT_NONE
;
6890 * Otherwise we need to dump the components that are being dumped for
6891 * the table and any components which the sequence is explicitly
6894 * We can't simply use the set of components which are being dumped
6895 * for the table as the table might be in an extension (and only the
6896 * non-extension components, eg: ACLs if changed, security labels, and
6897 * policies, are being dumped) while the sequence is not (and
6898 * therefore the definition and other components should also be
6901 * If the sequence is part of the extension then it should be properly
6902 * marked by checkExtensionMembership() and this will be a no-op as
6903 * the table will be equivalently marked.
6905 seqinfo
->dobj
.dump
= seqinfo
->dobj
.dump
| owning_tab
->dobj
.dump
;
6907 if (seqinfo
->dobj
.dump
!= DUMP_COMPONENT_NONE
)
6908 seqinfo
->interesting
= true;
6914 * read all the inheritance information
6915 * from the system catalogs return them in the InhInfo* structure
6917 * numInherits is set to the number of pairs read in
6920 getInherits(Archive
*fout
, int *numInherits
)
6925 PQExpBuffer query
= createPQExpBuffer();
6932 * Find all the inheritance information, excluding implicit inheritance
6933 * via partitioning. We handle that case using getPartitions(), because
6934 * we want more information about partitions than just the parent-child
6937 appendPQExpBufferStr(query
, "SELECT inhrelid, inhparent FROM pg_inherits");
6939 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
6941 ntups
= PQntuples(res
);
6943 *numInherits
= ntups
;
6945 inhinfo
= (InhInfo
*) pg_malloc(ntups
* sizeof(InhInfo
));
6947 i_inhrelid
= PQfnumber(res
, "inhrelid");
6948 i_inhparent
= PQfnumber(res
, "inhparent");
6950 for (i
= 0; i
< ntups
; i
++)
6952 inhinfo
[i
].inhrelid
= atooid(PQgetvalue(res
, i
, i_inhrelid
));
6953 inhinfo
[i
].inhparent
= atooid(PQgetvalue(res
, i
, i_inhparent
));
6958 destroyPQExpBuffer(query
);
6964 * getPartitioningInfo
6965 * get information about partitioning
6967 * For the most part, we only collect partitioning info about tables we
6968 * intend to dump. However, this function has to consider all partitioned
6969 * tables in the database, because we need to know about parents of partitions
6970 * we are going to dump even if the parents themselves won't be dumped.
6972 * Specifically, what we need to know is whether each partitioned table
6973 * has an "unsafe" partitioning scheme that requires us to force
6974 * load-via-partition-root mode for its children. Currently the only case
6975 * for which we force that is hash partitioning on enum columns, since the
6976 * hash codes depend on enum value OIDs which won't be replicated across
6977 * dump-and-reload. There are other cases in which load-via-partition-root
6978 * might be necessary, but we expect users to cope with them.
6981 getPartitioningInfo(Archive
*fout
)
6987 /* hash partitioning didn't exist before v11 */
6988 if (fout
->remoteVersion
< 110000)
6990 /* needn't bother if schema-only dump */
6991 if (fout
->dopt
->schemaOnly
)
6994 query
= createPQExpBuffer();
6997 * Unsafe partitioning schemes are exactly those for which hash enum_ops
6998 * appears among the partition opclasses. We needn't check partstrat.
7000 * Note that this query may well retrieve info about tables we aren't
7001 * going to dump and hence have no lock on. That's okay since we need not
7002 * invoke any unsafe server-side functions.
7004 appendPQExpBufferStr(query
,
7005 "SELECT partrelid FROM pg_partitioned_table WHERE\n"
7006 "(SELECT c.oid FROM pg_opclass c JOIN pg_am a "
7007 "ON c.opcmethod = a.oid\n"
7008 "WHERE opcname = 'enum_ops' "
7009 "AND opcnamespace = 'pg_catalog'::regnamespace "
7010 "AND amname = 'hash') = ANY(partclass)");
7012 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7014 ntups
= PQntuples(res
);
7016 for (int i
= 0; i
< ntups
; i
++)
7018 Oid tabrelid
= atooid(PQgetvalue(res
, i
, 0));
7021 tbinfo
= findTableByOid(tabrelid
);
7023 fatal("failed sanity check, table OID %u appearing in pg_partitioned_table not found",
7025 tbinfo
->unsafe_partitions
= true;
7030 destroyPQExpBuffer(query
);
7035 * get information about every index on a dumpable table
7037 * Note: index data is not returned directly to the caller, but it
7038 * does get entered into the DumpableObject tables.
7041 getIndexes(Archive
*fout
, TableInfo tblinfo
[], int numTables
)
7045 PQExpBuffer query
= createPQExpBuffer();
7048 ConstraintInfo
*constrinfo
;
7072 for (i
= 0; i
< numTables
; i
++)
7074 TableInfo
*tbinfo
= &tblinfo
[i
];
7076 if (!tbinfo
->hasindex
)
7080 * Ignore indexes of tables whose definitions are not to be dumped.
7082 * We also need indexes on partitioned tables which have partitions to
7083 * be dumped, in order to dump the indexes on the partitions.
7085 if (!(tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
) &&
7086 !tbinfo
->interesting
)
7089 pg_log_info("reading indexes for table \"%s.%s\"",
7090 tbinfo
->dobj
.namespace->dobj
.name
,
7094 * The point of the messy-looking outer join is to find a constraint
7095 * that is related by an internal dependency link to the index. If we
7096 * find one, create a CONSTRAINT entry linked to the INDEX entry. We
7097 * assume an index won't have more than one internal dependency.
7099 * As of 9.0 we don't need to look at pg_depend but can check for a
7100 * match to pg_constraint.conindid. The check on conrelid is
7101 * redundant but useful because that column is indexed while conindid
7104 resetPQExpBuffer(query
);
7105 if (fout
->remoteVersion
>= 110000)
7107 appendPQExpBuffer(query
,
7108 "SELECT t.tableoid, t.oid, "
7109 "t.relname AS indexname, "
7110 "inh.inhparent AS parentidx, "
7111 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7112 "i.indnkeyatts AS indnkeyatts, "
7113 "i.indnatts AS indnatts, "
7114 "i.indkey, i.indisclustered, "
7115 "i.indisreplident, "
7116 "c.contype, c.conname, "
7117 "c.condeferrable, c.condeferred, "
7118 "c.tableoid AS contableoid, "
7120 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7121 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7122 "t.reloptions AS indreloptions, "
7123 "(SELECT pg_catalog.array_agg(attnum ORDER BY attnum) "
7124 " FROM pg_catalog.pg_attribute "
7125 " WHERE attrelid = i.indexrelid AND "
7126 " attstattarget >= 0) AS indstatcols,"
7127 "(SELECT pg_catalog.array_agg(attstattarget ORDER BY attnum) "
7128 " FROM pg_catalog.pg_attribute "
7129 " WHERE attrelid = i.indexrelid AND "
7130 " attstattarget >= 0) AS indstatvals "
7131 "FROM pg_catalog.pg_index i "
7132 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7133 "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
7134 "LEFT JOIN pg_catalog.pg_constraint c "
7135 "ON (i.indrelid = c.conrelid AND "
7136 "i.indexrelid = c.conindid AND "
7137 "c.contype IN ('p','u','x')) "
7138 "LEFT JOIN pg_catalog.pg_inherits inh "
7139 "ON (inh.inhrelid = indexrelid) "
7140 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7141 "AND (i.indisvalid OR t2.relkind = 'p') "
7143 "ORDER BY indexname",
7144 tbinfo
->dobj
.catId
.oid
);
7146 else if (fout
->remoteVersion
>= 90400)
7149 * the test on indisready is necessary in 9.2, and harmless in
7150 * earlier/later versions
7152 appendPQExpBuffer(query
,
7153 "SELECT t.tableoid, t.oid, "
7154 "t.relname AS indexname, "
7156 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7157 "i.indnatts AS indnkeyatts, "
7158 "i.indnatts AS indnatts, "
7159 "i.indkey, i.indisclustered, "
7160 "i.indisreplident, "
7161 "c.contype, c.conname, "
7162 "c.condeferrable, c.condeferred, "
7163 "c.tableoid AS contableoid, "
7165 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7166 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7167 "t.reloptions AS indreloptions, "
7168 "'' AS indstatcols, "
7169 "'' AS indstatvals "
7170 "FROM pg_catalog.pg_index i "
7171 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7172 "LEFT JOIN pg_catalog.pg_constraint c "
7173 "ON (i.indrelid = c.conrelid AND "
7174 "i.indexrelid = c.conindid AND "
7175 "c.contype IN ('p','u','x')) "
7176 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7177 "AND i.indisvalid AND i.indisready "
7178 "ORDER BY indexname",
7179 tbinfo
->dobj
.catId
.oid
);
7181 else if (fout
->remoteVersion
>= 90000)
7184 * the test on indisready is necessary in 9.2, and harmless in
7185 * earlier/later versions
7187 appendPQExpBuffer(query
,
7188 "SELECT t.tableoid, t.oid, "
7189 "t.relname AS indexname, "
7191 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7192 "i.indnatts AS indnkeyatts, "
7193 "i.indnatts AS indnatts, "
7194 "i.indkey, i.indisclustered, "
7195 "false AS indisreplident, "
7196 "c.contype, c.conname, "
7197 "c.condeferrable, c.condeferred, "
7198 "c.tableoid AS contableoid, "
7200 "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7201 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7202 "t.reloptions AS indreloptions, "
7203 "'' AS indstatcols, "
7204 "'' AS indstatvals "
7205 "FROM pg_catalog.pg_index i "
7206 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7207 "LEFT JOIN pg_catalog.pg_constraint c "
7208 "ON (i.indrelid = c.conrelid AND "
7209 "i.indexrelid = c.conindid AND "
7210 "c.contype IN ('p','u','x')) "
7211 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7212 "AND i.indisvalid AND i.indisready "
7213 "ORDER BY indexname",
7214 tbinfo
->dobj
.catId
.oid
);
7216 else if (fout
->remoteVersion
>= 80200)
7218 appendPQExpBuffer(query
,
7219 "SELECT t.tableoid, t.oid, "
7220 "t.relname AS indexname, "
7222 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7223 "i.indnatts AS indnkeyatts, "
7224 "i.indnatts AS indnatts, "
7225 "i.indkey, i.indisclustered, "
7226 "false AS indisreplident, "
7227 "c.contype, c.conname, "
7228 "c.condeferrable, c.condeferred, "
7229 "c.tableoid AS contableoid, "
7232 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7233 "t.reloptions AS indreloptions, "
7234 "'' AS indstatcols, "
7235 "'' AS indstatvals "
7236 "FROM pg_catalog.pg_index i "
7237 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7238 "LEFT JOIN pg_catalog.pg_depend d "
7239 "ON (d.classid = t.tableoid "
7240 "AND d.objid = t.oid "
7241 "AND d.deptype = 'i') "
7242 "LEFT JOIN pg_catalog.pg_constraint c "
7243 "ON (d.refclassid = c.tableoid "
7244 "AND d.refobjid = c.oid) "
7245 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7247 "ORDER BY indexname",
7248 tbinfo
->dobj
.catId
.oid
);
7252 appendPQExpBuffer(query
,
7253 "SELECT t.tableoid, t.oid, "
7254 "t.relname AS indexname, "
7256 "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7257 "t.relnatts AS indnkeyatts, "
7258 "t.relnatts AS indnatts, "
7259 "i.indkey, i.indisclustered, "
7260 "false AS indisreplident, "
7261 "c.contype, c.conname, "
7262 "c.condeferrable, c.condeferred, "
7263 "c.tableoid AS contableoid, "
7266 "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7267 "null AS indreloptions, "
7268 "'' AS indstatcols, "
7269 "'' AS indstatvals "
7270 "FROM pg_catalog.pg_index i "
7271 "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7272 "LEFT JOIN pg_catalog.pg_depend d "
7273 "ON (d.classid = t.tableoid "
7274 "AND d.objid = t.oid "
7275 "AND d.deptype = 'i') "
7276 "LEFT JOIN pg_catalog.pg_constraint c "
7277 "ON (d.refclassid = c.tableoid "
7278 "AND d.refobjid = c.oid) "
7279 "WHERE i.indrelid = '%u'::pg_catalog.oid "
7280 "ORDER BY indexname",
7281 tbinfo
->dobj
.catId
.oid
);
7284 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7286 ntups
= PQntuples(res
);
7288 i_tableoid
= PQfnumber(res
, "tableoid");
7289 i_oid
= PQfnumber(res
, "oid");
7290 i_indexname
= PQfnumber(res
, "indexname");
7291 i_parentidx
= PQfnumber(res
, "parentidx");
7292 i_indexdef
= PQfnumber(res
, "indexdef");
7293 i_indnkeyatts
= PQfnumber(res
, "indnkeyatts");
7294 i_indnatts
= PQfnumber(res
, "indnatts");
7295 i_indkey
= PQfnumber(res
, "indkey");
7296 i_indisclustered
= PQfnumber(res
, "indisclustered");
7297 i_indisreplident
= PQfnumber(res
, "indisreplident");
7298 i_contype
= PQfnumber(res
, "contype");
7299 i_conname
= PQfnumber(res
, "conname");
7300 i_condeferrable
= PQfnumber(res
, "condeferrable");
7301 i_condeferred
= PQfnumber(res
, "condeferred");
7302 i_contableoid
= PQfnumber(res
, "contableoid");
7303 i_conoid
= PQfnumber(res
, "conoid");
7304 i_condef
= PQfnumber(res
, "condef");
7305 i_tablespace
= PQfnumber(res
, "tablespace");
7306 i_indreloptions
= PQfnumber(res
, "indreloptions");
7307 i_indstatcols
= PQfnumber(res
, "indstatcols");
7308 i_indstatvals
= PQfnumber(res
, "indstatvals");
7310 tbinfo
->indexes
= indxinfo
=
7311 (IndxInfo
*) pg_malloc(ntups
* sizeof(IndxInfo
));
7312 constrinfo
= (ConstraintInfo
*) pg_malloc(ntups
* sizeof(ConstraintInfo
));
7313 tbinfo
->numIndexes
= ntups
;
7315 for (j
= 0; j
< ntups
; j
++)
7319 indxinfo
[j
].dobj
.objType
= DO_INDEX
;
7320 indxinfo
[j
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, j
, i_tableoid
));
7321 indxinfo
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, i_oid
));
7322 AssignDumpId(&indxinfo
[j
].dobj
);
7323 indxinfo
[j
].dobj
.dump
= tbinfo
->dobj
.dump
;
7324 indxinfo
[j
].dobj
.name
= pg_strdup(PQgetvalue(res
, j
, i_indexname
));
7325 indxinfo
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
7326 indxinfo
[j
].indextable
= tbinfo
;
7327 indxinfo
[j
].indexdef
= pg_strdup(PQgetvalue(res
, j
, i_indexdef
));
7328 indxinfo
[j
].indnkeyattrs
= atoi(PQgetvalue(res
, j
, i_indnkeyatts
));
7329 indxinfo
[j
].indnattrs
= atoi(PQgetvalue(res
, j
, i_indnatts
));
7330 indxinfo
[j
].tablespace
= pg_strdup(PQgetvalue(res
, j
, i_tablespace
));
7331 indxinfo
[j
].indreloptions
= pg_strdup(PQgetvalue(res
, j
, i_indreloptions
));
7332 indxinfo
[j
].indstatcols
= pg_strdup(PQgetvalue(res
, j
, i_indstatcols
));
7333 indxinfo
[j
].indstatvals
= pg_strdup(PQgetvalue(res
, j
, i_indstatvals
));
7334 indxinfo
[j
].indkeys
= (Oid
*) pg_malloc(indxinfo
[j
].indnattrs
* sizeof(Oid
));
7335 parseOidArray(PQgetvalue(res
, j
, i_indkey
),
7336 indxinfo
[j
].indkeys
, indxinfo
[j
].indnattrs
);
7337 indxinfo
[j
].indisclustered
= (PQgetvalue(res
, j
, i_indisclustered
)[0] == 't');
7338 indxinfo
[j
].indisreplident
= (PQgetvalue(res
, j
, i_indisreplident
)[0] == 't');
7339 indxinfo
[j
].parentidx
= atooid(PQgetvalue(res
, j
, i_parentidx
));
7340 indxinfo
[j
].partattaches
= (SimplePtrList
) { NULL
, NULL
};
7341 contype
= *(PQgetvalue(res
, j
, i_contype
));
7343 if (contype
== 'p' || contype
== 'u' || contype
== 'x')
7346 * If we found a constraint matching the index, create an
7349 constrinfo
[j
].dobj
.objType
= DO_CONSTRAINT
;
7350 constrinfo
[j
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, j
, i_contableoid
));
7351 constrinfo
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, i_conoid
));
7352 AssignDumpId(&constrinfo
[j
].dobj
);
7353 constrinfo
[j
].dobj
.dump
= tbinfo
->dobj
.dump
;
7354 constrinfo
[j
].dobj
.name
= pg_strdup(PQgetvalue(res
, j
, i_conname
));
7355 constrinfo
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
7356 constrinfo
[j
].contable
= tbinfo
;
7357 constrinfo
[j
].condomain
= NULL
;
7358 constrinfo
[j
].contype
= contype
;
7360 constrinfo
[j
].condef
= pg_strdup(PQgetvalue(res
, j
, i_condef
));
7362 constrinfo
[j
].condef
= NULL
;
7363 constrinfo
[j
].confrelid
= InvalidOid
;
7364 constrinfo
[j
].conindex
= indxinfo
[j
].dobj
.dumpId
;
7365 constrinfo
[j
].condeferrable
= *(PQgetvalue(res
, j
, i_condeferrable
)) == 't';
7366 constrinfo
[j
].condeferred
= *(PQgetvalue(res
, j
, i_condeferred
)) == 't';
7367 constrinfo
[j
].conislocal
= true;
7368 constrinfo
[j
].separate
= true;
7370 indxinfo
[j
].indexconstraint
= constrinfo
[j
].dobj
.dumpId
;
7374 /* Plain secondary index */
7375 indxinfo
[j
].indexconstraint
= 0;
7382 destroyPQExpBuffer(query
);
7386 * getExtendedStatistics
7387 * get information about extended-statistics objects.
7389 * Note: extended statistics data is not returned directly to the caller, but
7390 * it does get entered into the DumpableObject tables.
7393 getExtendedStatistics(Archive
*fout
)
7397 StatsExtInfo
*statsextinfo
;
7407 /* Extended statistics were new in v10 */
7408 if (fout
->remoteVersion
< 100000)
7411 query
= createPQExpBuffer();
7413 appendPQExpBuffer(query
, "SELECT tableoid, oid, stxname, "
7414 "stxnamespace, (%s stxowner) AS rolname, stxrelid "
7415 "FROM pg_catalog.pg_statistic_ext",
7418 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7420 ntups
= PQntuples(res
);
7422 i_tableoid
= PQfnumber(res
, "tableoid");
7423 i_oid
= PQfnumber(res
, "oid");
7424 i_stxname
= PQfnumber(res
, "stxname");
7425 i_stxnamespace
= PQfnumber(res
, "stxnamespace");
7426 i_rolname
= PQfnumber(res
, "rolname");
7427 i_stxrelid
= PQfnumber(res
, "stxrelid");
7429 statsextinfo
= (StatsExtInfo
*) pg_malloc(ntups
* sizeof(StatsExtInfo
));
7431 for (i
= 0; i
< ntups
; i
++)
7433 statsextinfo
[i
].dobj
.objType
= DO_STATSEXT
;
7434 statsextinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
7435 statsextinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
7436 AssignDumpId(&statsextinfo
[i
].dobj
);
7437 statsextinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_stxname
));
7438 statsextinfo
[i
].dobj
.namespace =
7440 atooid(PQgetvalue(res
, i
, i_stxnamespace
)));
7441 statsextinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
7442 statsextinfo
[i
].stattable
=
7443 findTableByOid(atooid(PQgetvalue(res
, i
, i_stxrelid
)));
7445 /* Decide whether we want to dump it */
7446 selectDumpableStatisticsObject(&(statsextinfo
[i
]), fout
);
7448 /* Stats objects do not currently have ACLs. */
7449 statsextinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
7453 destroyPQExpBuffer(query
);
7459 * Get info about constraints on dumpable tables.
7461 * Currently handles foreign keys only.
7462 * Unique and primary key constraints are handled with indexes,
7463 * while check constraints are processed in getTableAttrs().
7466 getConstraints(Archive
*fout
, TableInfo tblinfo
[], int numTables
)
7470 ConstraintInfo
*constrinfo
;
7481 query
= createPQExpBuffer();
7483 for (i
= 0; i
< numTables
; i
++)
7485 TableInfo
*tbinfo
= &tblinfo
[i
];
7488 * For partitioned tables, foreign keys have no triggers so they must
7489 * be included anyway in case some foreign keys are defined.
7491 if ((!tbinfo
->hastriggers
&&
7492 tbinfo
->relkind
!= RELKIND_PARTITIONED_TABLE
) ||
7493 !(tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
7496 pg_log_info("reading foreign key constraints for table \"%s.%s\"",
7497 tbinfo
->dobj
.namespace->dobj
.name
,
7500 resetPQExpBuffer(query
);
7501 if (fout
->remoteVersion
>= 110000)
7502 appendPQExpBuffer(query
,
7503 "SELECT tableoid, oid, conname, confrelid, conindid, "
7504 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7505 "FROM pg_catalog.pg_constraint "
7506 "WHERE conrelid = '%u'::pg_catalog.oid "
7507 "AND conparentid = 0 "
7508 "AND contype = 'f'",
7509 tbinfo
->dobj
.catId
.oid
);
7511 appendPQExpBuffer(query
,
7512 "SELECT tableoid, oid, conname, confrelid, 0 as conindid, "
7513 "pg_catalog.pg_get_constraintdef(oid) AS condef "
7514 "FROM pg_catalog.pg_constraint "
7515 "WHERE conrelid = '%u'::pg_catalog.oid "
7516 "AND contype = 'f'",
7517 tbinfo
->dobj
.catId
.oid
);
7518 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7520 ntups
= PQntuples(res
);
7522 i_contableoid
= PQfnumber(res
, "tableoid");
7523 i_conoid
= PQfnumber(res
, "oid");
7524 i_conname
= PQfnumber(res
, "conname");
7525 i_confrelid
= PQfnumber(res
, "confrelid");
7526 i_conindid
= PQfnumber(res
, "conindid");
7527 i_condef
= PQfnumber(res
, "condef");
7529 constrinfo
= (ConstraintInfo
*) pg_malloc(ntups
* sizeof(ConstraintInfo
));
7531 for (j
= 0; j
< ntups
; j
++)
7533 TableInfo
*reftable
;
7535 constrinfo
[j
].dobj
.objType
= DO_FK_CONSTRAINT
;
7536 constrinfo
[j
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, j
, i_contableoid
));
7537 constrinfo
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, i_conoid
));
7538 AssignDumpId(&constrinfo
[j
].dobj
);
7539 constrinfo
[j
].dobj
.name
= pg_strdup(PQgetvalue(res
, j
, i_conname
));
7540 constrinfo
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
7541 constrinfo
[j
].contable
= tbinfo
;
7542 constrinfo
[j
].condomain
= NULL
;
7543 constrinfo
[j
].contype
= 'f';
7544 constrinfo
[j
].condef
= pg_strdup(PQgetvalue(res
, j
, i_condef
));
7545 constrinfo
[j
].confrelid
= atooid(PQgetvalue(res
, j
, i_confrelid
));
7546 constrinfo
[j
].conindex
= 0;
7547 constrinfo
[j
].condeferrable
= false;
7548 constrinfo
[j
].condeferred
= false;
7549 constrinfo
[j
].conislocal
= true;
7550 constrinfo
[j
].separate
= true;
7553 * Restoring an FK that points to a partitioned table requires
7554 * that all partition indexes have been attached beforehand.
7555 * Ensure that happens by making the constraint depend on each
7556 * index partition attach object.
7558 reftable
= findTableByOid(constrinfo
[j
].confrelid
);
7559 if (reftable
&& reftable
->relkind
== RELKIND_PARTITIONED_TABLE
)
7561 Oid indexOid
= atooid(PQgetvalue(res
, j
, i_conindid
));
7563 if (indexOid
!= InvalidOid
)
7565 for (int k
= 0; k
< reftable
->numIndexes
; k
++)
7569 /* not our index? */
7570 if (reftable
->indexes
[k
].dobj
.catId
.oid
!= indexOid
)
7573 refidx
= &reftable
->indexes
[k
];
7574 addConstrChildIdxDeps(&constrinfo
[j
].dobj
, refidx
);
7584 destroyPQExpBuffer(query
);
7588 * addConstrChildIdxDeps
7590 * Recursive subroutine for getConstraints
7592 * Given an object representing a foreign key constraint and an index on the
7593 * partitioned table it references, mark the constraint object as dependent
7594 * on each partition, recursing to children until all leaves are found.
7595 * This ensures that the FK is not restored until the index is fully marked
7599 addConstrChildIdxDeps(DumpableObject
*dobj
, IndxInfo
*refidx
)
7601 SimplePtrListCell
*cell
;
7603 Assert(dobj
->objType
== DO_FK_CONSTRAINT
);
7605 for (cell
= refidx
->partattaches
.head
; cell
; cell
= cell
->next
)
7607 DumpableObject
*childobj
= (DumpableObject
*) cell
->ptr
;
7608 IndexAttachInfo
*attach
;
7610 addObjectDependency(dobj
, childobj
->dumpId
);
7612 attach
= (IndexAttachInfo
*) childobj
;
7613 if (attach
->partitionIdx
->partattaches
.head
!= NULL
)
7614 addConstrChildIdxDeps(dobj
, attach
->partitionIdx
);
7619 * getDomainConstraints
7621 * Get info about constraints on a domain.
7624 getDomainConstraints(Archive
*fout
, TypeInfo
*tyinfo
)
7627 ConstraintInfo
*constrinfo
;
7636 query
= createPQExpBuffer();
7638 if (fout
->remoteVersion
>= 90100)
7639 appendPQExpBuffer(query
, "SELECT tableoid, oid, conname, "
7640 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7642 "FROM pg_catalog.pg_constraint "
7643 "WHERE contypid = '%u'::pg_catalog.oid "
7645 tyinfo
->dobj
.catId
.oid
);
7648 appendPQExpBuffer(query
, "SELECT tableoid, oid, conname, "
7649 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
7650 "true as convalidated "
7651 "FROM pg_catalog.pg_constraint "
7652 "WHERE contypid = '%u'::pg_catalog.oid "
7654 tyinfo
->dobj
.catId
.oid
);
7656 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7658 ntups
= PQntuples(res
);
7660 i_tableoid
= PQfnumber(res
, "tableoid");
7661 i_oid
= PQfnumber(res
, "oid");
7662 i_conname
= PQfnumber(res
, "conname");
7663 i_consrc
= PQfnumber(res
, "consrc");
7665 constrinfo
= (ConstraintInfo
*) pg_malloc(ntups
* sizeof(ConstraintInfo
));
7667 tyinfo
->nDomChecks
= ntups
;
7668 tyinfo
->domChecks
= constrinfo
;
7670 for (i
= 0; i
< ntups
; i
++)
7672 bool validated
= PQgetvalue(res
, i
, 4)[0] == 't';
7674 constrinfo
[i
].dobj
.objType
= DO_CONSTRAINT
;
7675 constrinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
7676 constrinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
7677 AssignDumpId(&constrinfo
[i
].dobj
);
7678 constrinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_conname
));
7679 constrinfo
[i
].dobj
.namespace = tyinfo
->dobj
.namespace;
7680 constrinfo
[i
].contable
= NULL
;
7681 constrinfo
[i
].condomain
= tyinfo
;
7682 constrinfo
[i
].contype
= 'c';
7683 constrinfo
[i
].condef
= pg_strdup(PQgetvalue(res
, i
, i_consrc
));
7684 constrinfo
[i
].confrelid
= InvalidOid
;
7685 constrinfo
[i
].conindex
= 0;
7686 constrinfo
[i
].condeferrable
= false;
7687 constrinfo
[i
].condeferred
= false;
7688 constrinfo
[i
].conislocal
= true;
7690 constrinfo
[i
].separate
= !validated
;
7693 * Make the domain depend on the constraint, ensuring it won't be
7694 * output till any constraint dependencies are OK. If the constraint
7695 * has not been validated, it's going to be dumped after the domain
7696 * anyway, so this doesn't matter.
7699 addObjectDependency(&tyinfo
->dobj
,
7700 constrinfo
[i
].dobj
.dumpId
);
7705 destroyPQExpBuffer(query
);
7710 * get basic information about every rule in the system
7712 * numRules is set to the number of rules read in
7715 getRules(Archive
*fout
, int *numRules
)
7720 PQExpBuffer query
= createPQExpBuffer();
7730 if (fout
->remoteVersion
>= 80300)
7732 appendPQExpBufferStr(query
, "SELECT "
7733 "tableoid, oid, rulename, "
7734 "ev_class AS ruletable, ev_type, is_instead, "
7741 appendPQExpBufferStr(query
, "SELECT "
7742 "tableoid, oid, rulename, "
7743 "ev_class AS ruletable, ev_type, is_instead, "
7744 "'O'::char AS ev_enabled "
7749 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7751 ntups
= PQntuples(res
);
7755 ruleinfo
= (RuleInfo
*) pg_malloc(ntups
* sizeof(RuleInfo
));
7757 i_tableoid
= PQfnumber(res
, "tableoid");
7758 i_oid
= PQfnumber(res
, "oid");
7759 i_rulename
= PQfnumber(res
, "rulename");
7760 i_ruletable
= PQfnumber(res
, "ruletable");
7761 i_ev_type
= PQfnumber(res
, "ev_type");
7762 i_is_instead
= PQfnumber(res
, "is_instead");
7763 i_ev_enabled
= PQfnumber(res
, "ev_enabled");
7765 for (i
= 0; i
< ntups
; i
++)
7769 ruleinfo
[i
].dobj
.objType
= DO_RULE
;
7770 ruleinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
7771 ruleinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
7772 AssignDumpId(&ruleinfo
[i
].dobj
);
7773 ruleinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_rulename
));
7774 ruletableoid
= atooid(PQgetvalue(res
, i
, i_ruletable
));
7775 ruleinfo
[i
].ruletable
= findTableByOid(ruletableoid
);
7776 if (ruleinfo
[i
].ruletable
== NULL
)
7777 fatal("failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found",
7778 ruletableoid
, ruleinfo
[i
].dobj
.catId
.oid
);
7779 ruleinfo
[i
].dobj
.namespace = ruleinfo
[i
].ruletable
->dobj
.namespace;
7780 ruleinfo
[i
].dobj
.dump
= ruleinfo
[i
].ruletable
->dobj
.dump
;
7781 ruleinfo
[i
].ev_type
= *(PQgetvalue(res
, i
, i_ev_type
));
7782 ruleinfo
[i
].is_instead
= *(PQgetvalue(res
, i
, i_is_instead
)) == 't';
7783 ruleinfo
[i
].ev_enabled
= *(PQgetvalue(res
, i
, i_ev_enabled
));
7784 if (ruleinfo
[i
].ruletable
)
7787 * If the table is a view or materialized view, force its ON
7788 * SELECT rule to be sorted before the view itself --- this
7789 * ensures that any dependencies for the rule affect the table's
7790 * positioning. Other rules are forced to appear after their
7793 if ((ruleinfo
[i
].ruletable
->relkind
== RELKIND_VIEW
||
7794 ruleinfo
[i
].ruletable
->relkind
== RELKIND_MATVIEW
) &&
7795 ruleinfo
[i
].ev_type
== '1' && ruleinfo
[i
].is_instead
)
7797 addObjectDependency(&ruleinfo
[i
].ruletable
->dobj
,
7798 ruleinfo
[i
].dobj
.dumpId
);
7799 /* We'll merge the rule into CREATE VIEW, if possible */
7800 ruleinfo
[i
].separate
= false;
7804 addObjectDependency(&ruleinfo
[i
].dobj
,
7805 ruleinfo
[i
].ruletable
->dobj
.dumpId
);
7806 ruleinfo
[i
].separate
= true;
7810 ruleinfo
[i
].separate
= true;
7815 destroyPQExpBuffer(query
);
7822 * get information about every trigger on a dumpable table
7824 * Note: trigger data is not returned directly to the caller, but it
7825 * does get entered into the DumpableObject tables.
7828 getTriggers(Archive
*fout
, TableInfo tblinfo
[], int numTables
)
7832 PQExpBuffer query
= createPQExpBuffer();
7834 TriggerInfo
*tginfo
;
7853 for (i
= 0; i
< numTables
; i
++)
7855 TableInfo
*tbinfo
= &tblinfo
[i
];
7857 if (!tbinfo
->hastriggers
||
7858 !(tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
7861 pg_log_info("reading triggers for table \"%s.%s\"",
7862 tbinfo
->dobj
.namespace->dobj
.name
,
7865 resetPQExpBuffer(query
);
7866 if (fout
->remoteVersion
>= 130000)
7869 * NB: think not to use pretty=true in pg_get_triggerdef. It
7870 * could result in non-forward-compatible dumps of WHEN clauses
7871 * due to under-parenthesization.
7873 * NB: We need to see tgisinternal triggers in partitions, in case
7874 * the tgenabled flag has been changed from the parent.
7876 appendPQExpBuffer(query
,
7878 "t.tgfoid::pg_catalog.regproc AS tgfname, "
7879 "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
7880 "t.tgenabled, t.tableoid, t.oid, t.tgisinternal "
7881 "FROM pg_catalog.pg_trigger t "
7882 "LEFT JOIN pg_catalog.pg_trigger u ON u.oid = t.tgparentid "
7883 "WHERE t.tgrelid = '%u'::pg_catalog.oid "
7884 "AND (NOT t.tgisinternal OR t.tgenabled != u.tgenabled)",
7885 tbinfo
->dobj
.catId
.oid
);
7887 else if (fout
->remoteVersion
>= 110000)
7890 * NB: We need to see tgisinternal triggers in partitions, in case
7891 * the tgenabled flag has been changed from the parent. No
7892 * tgparentid in version 11-12, so we have to match them via
7895 * See above about pretty=true in pg_get_triggerdef.
7897 appendPQExpBuffer(query
,
7899 "t.tgfoid::pg_catalog.regproc AS tgfname, "
7900 "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
7901 "t.tgenabled, t.tableoid, t.oid, t.tgisinternal "
7902 "FROM pg_catalog.pg_trigger t "
7903 "LEFT JOIN pg_catalog.pg_depend AS d ON "
7904 " d.classid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
7905 " d.refclassid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
7907 "LEFT JOIN pg_catalog.pg_trigger AS pt ON pt.oid = refobjid "
7908 "WHERE t.tgrelid = '%u'::pg_catalog.oid "
7909 "AND (NOT t.tgisinternal%s)",
7910 tbinfo
->dobj
.catId
.oid
,
7911 tbinfo
->ispartition
?
7912 " OR t.tgenabled != pt.tgenabled" : "");
7914 else if (fout
->remoteVersion
>= 90000)
7916 /* See above about pretty=true in pg_get_triggerdef */
7917 appendPQExpBuffer(query
,
7919 "t.tgfoid::pg_catalog.regproc AS tgfname, "
7920 "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
7921 "t.tgenabled, false as tgisinternal, "
7922 "t.tableoid, t.oid "
7923 "FROM pg_catalog.pg_trigger t "
7924 "WHERE tgrelid = '%u'::pg_catalog.oid "
7925 "AND NOT tgisinternal",
7926 tbinfo
->dobj
.catId
.oid
);
7928 else if (fout
->remoteVersion
>= 80300)
7931 * We ignore triggers that are tied to a foreign-key constraint
7933 appendPQExpBuffer(query
,
7935 "tgfoid::pg_catalog.regproc AS tgfname, "
7936 "tgtype, tgnargs, tgargs, tgenabled, "
7937 "false as tgisinternal, "
7938 "tgisconstraint, tgconstrname, tgdeferrable, "
7939 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7940 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7941 "FROM pg_catalog.pg_trigger t "
7942 "WHERE tgrelid = '%u'::pg_catalog.oid "
7943 "AND tgconstraint = 0",
7944 tbinfo
->dobj
.catId
.oid
);
7949 * We ignore triggers that are tied to a foreign-key constraint,
7950 * but in these versions we have to grovel through pg_constraint
7953 appendPQExpBuffer(query
,
7955 "tgfoid::pg_catalog.regproc AS tgfname, "
7956 "tgtype, tgnargs, tgargs, tgenabled, "
7957 "false as tgisinternal, "
7958 "tgisconstraint, tgconstrname, tgdeferrable, "
7959 "tgconstrrelid, tginitdeferred, tableoid, oid, "
7960 "tgconstrrelid::pg_catalog.regclass AS tgconstrrelname "
7961 "FROM pg_catalog.pg_trigger t "
7962 "WHERE tgrelid = '%u'::pg_catalog.oid "
7963 "AND (NOT tgisconstraint "
7965 " (SELECT 1 FROM pg_catalog.pg_depend d "
7966 " JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
7967 " WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))",
7968 tbinfo
->dobj
.catId
.oid
);
7971 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
7973 ntups
= PQntuples(res
);
7975 i_tableoid
= PQfnumber(res
, "tableoid");
7976 i_oid
= PQfnumber(res
, "oid");
7977 i_tgname
= PQfnumber(res
, "tgname");
7978 i_tgfname
= PQfnumber(res
, "tgfname");
7979 i_tgtype
= PQfnumber(res
, "tgtype");
7980 i_tgnargs
= PQfnumber(res
, "tgnargs");
7981 i_tgargs
= PQfnumber(res
, "tgargs");
7982 i_tgisconstraint
= PQfnumber(res
, "tgisconstraint");
7983 i_tgconstrname
= PQfnumber(res
, "tgconstrname");
7984 i_tgconstrrelid
= PQfnumber(res
, "tgconstrrelid");
7985 i_tgconstrrelname
= PQfnumber(res
, "tgconstrrelname");
7986 i_tgenabled
= PQfnumber(res
, "tgenabled");
7987 i_tgisinternal
= PQfnumber(res
, "tgisinternal");
7988 i_tgdeferrable
= PQfnumber(res
, "tgdeferrable");
7989 i_tginitdeferred
= PQfnumber(res
, "tginitdeferred");
7990 i_tgdef
= PQfnumber(res
, "tgdef");
7992 tginfo
= (TriggerInfo
*) pg_malloc(ntups
* sizeof(TriggerInfo
));
7994 tbinfo
->numTriggers
= ntups
;
7995 tbinfo
->triggers
= tginfo
;
7997 for (j
= 0; j
< ntups
; j
++)
7999 tginfo
[j
].dobj
.objType
= DO_TRIGGER
;
8000 tginfo
[j
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, j
, i_tableoid
));
8001 tginfo
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, i_oid
));
8002 AssignDumpId(&tginfo
[j
].dobj
);
8003 tginfo
[j
].dobj
.name
= pg_strdup(PQgetvalue(res
, j
, i_tgname
));
8004 tginfo
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
8005 tginfo
[j
].tgtable
= tbinfo
;
8006 tginfo
[j
].tgenabled
= *(PQgetvalue(res
, j
, i_tgenabled
));
8007 tginfo
[j
].tgisinternal
= *(PQgetvalue(res
, j
, i_tgisinternal
)) == 't';
8010 tginfo
[j
].tgdef
= pg_strdup(PQgetvalue(res
, j
, i_tgdef
));
8012 /* remaining fields are not valid if we have tgdef */
8013 tginfo
[j
].tgfname
= NULL
;
8014 tginfo
[j
].tgtype
= 0;
8015 tginfo
[j
].tgnargs
= 0;
8016 tginfo
[j
].tgargs
= NULL
;
8017 tginfo
[j
].tgisconstraint
= false;
8018 tginfo
[j
].tgdeferrable
= false;
8019 tginfo
[j
].tginitdeferred
= false;
8020 tginfo
[j
].tgconstrname
= NULL
;
8021 tginfo
[j
].tgconstrrelid
= InvalidOid
;
8022 tginfo
[j
].tgconstrrelname
= NULL
;
8026 tginfo
[j
].tgdef
= NULL
;
8028 tginfo
[j
].tgfname
= pg_strdup(PQgetvalue(res
, j
, i_tgfname
));
8029 tginfo
[j
].tgtype
= atoi(PQgetvalue(res
, j
, i_tgtype
));
8030 tginfo
[j
].tgnargs
= atoi(PQgetvalue(res
, j
, i_tgnargs
));
8031 tginfo
[j
].tgargs
= pg_strdup(PQgetvalue(res
, j
, i_tgargs
));
8032 tginfo
[j
].tgisconstraint
= *(PQgetvalue(res
, j
, i_tgisconstraint
)) == 't';
8033 tginfo
[j
].tgdeferrable
= *(PQgetvalue(res
, j
, i_tgdeferrable
)) == 't';
8034 tginfo
[j
].tginitdeferred
= *(PQgetvalue(res
, j
, i_tginitdeferred
)) == 't';
8036 if (tginfo
[j
].tgisconstraint
)
8038 tginfo
[j
].tgconstrname
= pg_strdup(PQgetvalue(res
, j
, i_tgconstrname
));
8039 tginfo
[j
].tgconstrrelid
= atooid(PQgetvalue(res
, j
, i_tgconstrrelid
));
8040 if (OidIsValid(tginfo
[j
].tgconstrrelid
))
8042 if (PQgetisnull(res
, j
, i_tgconstrrelname
))
8043 fatal("query produced null referenced table name for foreign key trigger \"%s\" on table \"%s\" (OID of table: %u)",
8044 tginfo
[j
].dobj
.name
,
8046 tginfo
[j
].tgconstrrelid
);
8047 tginfo
[j
].tgconstrrelname
= pg_strdup(PQgetvalue(res
, j
, i_tgconstrrelname
));
8050 tginfo
[j
].tgconstrrelname
= NULL
;
8054 tginfo
[j
].tgconstrname
= NULL
;
8055 tginfo
[j
].tgconstrrelid
= InvalidOid
;
8056 tginfo
[j
].tgconstrrelname
= NULL
;
8064 destroyPQExpBuffer(query
);
8069 * get information about event triggers
8072 getEventTriggers(Archive
*fout
, int *numEventTriggers
)
8077 EventTriggerInfo
*evtinfo
;
8088 /* Before 9.3, there are no event triggers */
8089 if (fout
->remoteVersion
< 90300)
8091 *numEventTriggers
= 0;
8095 query
= createPQExpBuffer();
8097 appendPQExpBuffer(query
,
8098 "SELECT e.tableoid, e.oid, evtname, evtenabled, "
8099 "evtevent, (%s evtowner) AS evtowner, "
8100 "array_to_string(array("
8101 "select quote_literal(x) "
8102 " from unnest(evttags) as t(x)), ', ') as evttags, "
8103 "e.evtfoid::regproc as evtfname "
8104 "FROM pg_event_trigger e "
8108 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
8110 ntups
= PQntuples(res
);
8112 *numEventTriggers
= ntups
;
8114 evtinfo
= (EventTriggerInfo
*) pg_malloc(ntups
* sizeof(EventTriggerInfo
));
8116 i_tableoid
= PQfnumber(res
, "tableoid");
8117 i_oid
= PQfnumber(res
, "oid");
8118 i_evtname
= PQfnumber(res
, "evtname");
8119 i_evtevent
= PQfnumber(res
, "evtevent");
8120 i_evtowner
= PQfnumber(res
, "evtowner");
8121 i_evttags
= PQfnumber(res
, "evttags");
8122 i_evtfname
= PQfnumber(res
, "evtfname");
8123 i_evtenabled
= PQfnumber(res
, "evtenabled");
8125 for (i
= 0; i
< ntups
; i
++)
8127 evtinfo
[i
].dobj
.objType
= DO_EVENT_TRIGGER
;
8128 evtinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
8129 evtinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
8130 AssignDumpId(&evtinfo
[i
].dobj
);
8131 evtinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_evtname
));
8132 evtinfo
[i
].evtname
= pg_strdup(PQgetvalue(res
, i
, i_evtname
));
8133 evtinfo
[i
].evtevent
= pg_strdup(PQgetvalue(res
, i
, i_evtevent
));
8134 evtinfo
[i
].evtowner
= pg_strdup(PQgetvalue(res
, i
, i_evtowner
));
8135 evtinfo
[i
].evttags
= pg_strdup(PQgetvalue(res
, i
, i_evttags
));
8136 evtinfo
[i
].evtfname
= pg_strdup(PQgetvalue(res
, i
, i_evtfname
));
8137 evtinfo
[i
].evtenabled
= *(PQgetvalue(res
, i
, i_evtenabled
));
8139 /* Decide whether we want to dump it */
8140 selectDumpableObject(&(evtinfo
[i
].dobj
), fout
);
8142 /* Event Triggers do not currently have ACLs. */
8143 evtinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
8148 destroyPQExpBuffer(query
);
8155 * get basic information about every procedural language in the system
8157 * numProcLangs is set to the number of langs read in
8159 * NB: this must run after getFuncs() because we assume we can do
8163 getProcLangs(Archive
*fout
, int *numProcLangs
)
8165 DumpOptions
*dopt
= fout
->dopt
;
8169 PQExpBuffer query
= createPQExpBuffer();
8170 ProcLangInfo
*planginfo
;
8175 int i_lanplcallfoid
;
8184 if (fout
->remoteVersion
>= 90600)
8186 PQExpBuffer acl_subquery
= createPQExpBuffer();
8187 PQExpBuffer racl_subquery
= createPQExpBuffer();
8188 PQExpBuffer initacl_subquery
= createPQExpBuffer();
8189 PQExpBuffer initracl_subquery
= createPQExpBuffer();
8191 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
8192 initracl_subquery
, "l.lanacl", "l.lanowner", "'l'",
8193 dopt
->binary_upgrade
);
8195 /* pg_language has a laninline column */
8196 appendPQExpBuffer(query
, "SELECT l.tableoid, l.oid, "
8197 "l.lanname, l.lanpltrusted, l.lanplcallfoid, "
8198 "l.laninline, l.lanvalidator, "
8201 "%s AS initlanacl, "
8202 "%s AS initrlanacl, "
8203 "(%s l.lanowner) AS lanowner "
8204 "FROM pg_language l "
8205 "LEFT JOIN pg_init_privs pip ON "
8206 "(l.oid = pip.objoid "
8207 "AND pip.classoid = 'pg_language'::regclass "
8208 "AND pip.objsubid = 0) "
8212 racl_subquery
->data
,
8213 initacl_subquery
->data
,
8214 initracl_subquery
->data
,
8217 destroyPQExpBuffer(acl_subquery
);
8218 destroyPQExpBuffer(racl_subquery
);
8219 destroyPQExpBuffer(initacl_subquery
);
8220 destroyPQExpBuffer(initracl_subquery
);
8222 else if (fout
->remoteVersion
>= 90000)
8224 /* pg_language has a laninline column */
8225 appendPQExpBuffer(query
, "SELECT tableoid, oid, "
8226 "lanname, lanpltrusted, lanplcallfoid, "
8227 "laninline, lanvalidator, lanacl, NULL AS rlanacl, "
8228 "NULL AS initlanacl, NULL AS initrlanacl, "
8229 "(%s lanowner) AS lanowner "
8235 else if (fout
->remoteVersion
>= 80300)
8237 /* pg_language has a lanowner column */
8238 appendPQExpBuffer(query
, "SELECT tableoid, oid, "
8239 "lanname, lanpltrusted, lanplcallfoid, "
8240 "0 AS laninline, lanvalidator, lanacl, "
8242 "NULL AS initlanacl, NULL AS initrlanacl, "
8243 "(%s lanowner) AS lanowner "
8249 else if (fout
->remoteVersion
>= 80100)
8251 /* Languages are owned by the bootstrap superuser, OID 10 */
8252 appendPQExpBuffer(query
, "SELECT tableoid, oid, "
8253 "lanname, lanpltrusted, lanplcallfoid, "
8254 "0 AS laninline, lanvalidator, lanacl, "
8256 "NULL AS initlanacl, NULL AS initrlanacl, "
8257 "(%s '10') AS lanowner "
8265 /* Languages are owned by the bootstrap superuser, sysid 1 */
8266 appendPQExpBuffer(query
, "SELECT tableoid, oid, "
8267 "lanname, lanpltrusted, lanplcallfoid, "
8268 "0 AS laninline, lanvalidator, lanacl, "
8270 "NULL AS initlanacl, NULL AS initrlanacl, "
8271 "(%s '1') AS lanowner "
8278 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
8280 ntups
= PQntuples(res
);
8282 *numProcLangs
= ntups
;
8284 planginfo
= (ProcLangInfo
*) pg_malloc(ntups
* sizeof(ProcLangInfo
));
8286 i_tableoid
= PQfnumber(res
, "tableoid");
8287 i_oid
= PQfnumber(res
, "oid");
8288 i_lanname
= PQfnumber(res
, "lanname");
8289 i_lanpltrusted
= PQfnumber(res
, "lanpltrusted");
8290 i_lanplcallfoid
= PQfnumber(res
, "lanplcallfoid");
8291 i_laninline
= PQfnumber(res
, "laninline");
8292 i_lanvalidator
= PQfnumber(res
, "lanvalidator");
8293 i_lanacl
= PQfnumber(res
, "lanacl");
8294 i_rlanacl
= PQfnumber(res
, "rlanacl");
8295 i_initlanacl
= PQfnumber(res
, "initlanacl");
8296 i_initrlanacl
= PQfnumber(res
, "initrlanacl");
8297 i_lanowner
= PQfnumber(res
, "lanowner");
8299 for (i
= 0; i
< ntups
; i
++)
8301 planginfo
[i
].dobj
.objType
= DO_PROCLANG
;
8302 planginfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
8303 planginfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
8304 AssignDumpId(&planginfo
[i
].dobj
);
8306 planginfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_lanname
));
8307 planginfo
[i
].lanpltrusted
= *(PQgetvalue(res
, i
, i_lanpltrusted
)) == 't';
8308 planginfo
[i
].lanplcallfoid
= atooid(PQgetvalue(res
, i
, i_lanplcallfoid
));
8309 planginfo
[i
].laninline
= atooid(PQgetvalue(res
, i
, i_laninline
));
8310 planginfo
[i
].lanvalidator
= atooid(PQgetvalue(res
, i
, i_lanvalidator
));
8311 planginfo
[i
].lanacl
= pg_strdup(PQgetvalue(res
, i
, i_lanacl
));
8312 planginfo
[i
].rlanacl
= pg_strdup(PQgetvalue(res
, i
, i_rlanacl
));
8313 planginfo
[i
].initlanacl
= pg_strdup(PQgetvalue(res
, i
, i_initlanacl
));
8314 planginfo
[i
].initrlanacl
= pg_strdup(PQgetvalue(res
, i
, i_initrlanacl
));
8315 planginfo
[i
].lanowner
= pg_strdup(PQgetvalue(res
, i
, i_lanowner
));
8317 /* Decide whether we want to dump it */
8318 selectDumpableProcLang(&(planginfo
[i
]), fout
);
8320 /* Do not try to dump ACL if no ACL exists. */
8321 if (PQgetisnull(res
, i
, i_lanacl
) && PQgetisnull(res
, i
, i_rlanacl
) &&
8322 PQgetisnull(res
, i
, i_initlanacl
) &&
8323 PQgetisnull(res
, i
, i_initrlanacl
))
8324 planginfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
8329 destroyPQExpBuffer(query
);
8336 * get basic information about every cast in the system
8338 * numCasts is set to the number of casts read in
8341 getCasts(Archive
*fout
, int *numCasts
)
8346 PQExpBuffer query
= createPQExpBuffer();
8356 if (fout
->remoteVersion
>= 80400)
8358 appendPQExpBufferStr(query
, "SELECT tableoid, oid, "
8359 "castsource, casttarget, castfunc, castcontext, "
8361 "FROM pg_cast ORDER BY 3,4");
8365 appendPQExpBufferStr(query
, "SELECT tableoid, oid, "
8366 "castsource, casttarget, castfunc, castcontext, "
8367 "CASE WHEN castfunc = 0 THEN 'b' ELSE 'f' END AS castmethod "
8368 "FROM pg_cast ORDER BY 3,4");
8371 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
8373 ntups
= PQntuples(res
);
8377 castinfo
= (CastInfo
*) pg_malloc(ntups
* sizeof(CastInfo
));
8379 i_tableoid
= PQfnumber(res
, "tableoid");
8380 i_oid
= PQfnumber(res
, "oid");
8381 i_castsource
= PQfnumber(res
, "castsource");
8382 i_casttarget
= PQfnumber(res
, "casttarget");
8383 i_castfunc
= PQfnumber(res
, "castfunc");
8384 i_castcontext
= PQfnumber(res
, "castcontext");
8385 i_castmethod
= PQfnumber(res
, "castmethod");
8387 for (i
= 0; i
< ntups
; i
++)
8389 PQExpBufferData namebuf
;
8390 TypeInfo
*sTypeInfo
;
8391 TypeInfo
*tTypeInfo
;
8393 castinfo
[i
].dobj
.objType
= DO_CAST
;
8394 castinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
8395 castinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
8396 AssignDumpId(&castinfo
[i
].dobj
);
8397 castinfo
[i
].castsource
= atooid(PQgetvalue(res
, i
, i_castsource
));
8398 castinfo
[i
].casttarget
= atooid(PQgetvalue(res
, i
, i_casttarget
));
8399 castinfo
[i
].castfunc
= atooid(PQgetvalue(res
, i
, i_castfunc
));
8400 castinfo
[i
].castcontext
= *(PQgetvalue(res
, i
, i_castcontext
));
8401 castinfo
[i
].castmethod
= *(PQgetvalue(res
, i
, i_castmethod
));
8404 * Try to name cast as concatenation of typnames. This is only used
8405 * for purposes of sorting. If we fail to find either type, the name
8406 * will be an empty string.
8408 initPQExpBuffer(&namebuf
);
8409 sTypeInfo
= findTypeByOid(castinfo
[i
].castsource
);
8410 tTypeInfo
= findTypeByOid(castinfo
[i
].casttarget
);
8411 if (sTypeInfo
&& tTypeInfo
)
8412 appendPQExpBuffer(&namebuf
, "%s %s",
8413 sTypeInfo
->dobj
.name
, tTypeInfo
->dobj
.name
);
8414 castinfo
[i
].dobj
.name
= namebuf
.data
;
8416 /* Decide whether we want to dump it */
8417 selectDumpableCast(&(castinfo
[i
]), fout
);
8419 /* Casts do not currently have ACLs. */
8420 castinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
8425 destroyPQExpBuffer(query
);
8431 get_language_name(Archive
*fout
, Oid langid
)
8437 query
= createPQExpBuffer();
8438 appendPQExpBuffer(query
, "SELECT lanname FROM pg_language WHERE oid = %u", langid
);
8439 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
8440 lanname
= pg_strdup(fmtId(PQgetvalue(res
, 0, 0)));
8441 destroyPQExpBuffer(query
);
8449 * get basic information about every transform in the system
8451 * numTransforms is set to the number of transforms read in
8454 getTransforms(Archive
*fout
, int *numTransforms
)
8460 TransformInfo
*transforminfo
;
8468 /* Transforms didn't exist pre-9.5 */
8469 if (fout
->remoteVersion
< 90500)
8475 query
= createPQExpBuffer();
8477 appendPQExpBuffer(query
, "SELECT tableoid, oid, "
8478 "trftype, trflang, trffromsql::oid, trftosql::oid "
8479 "FROM pg_transform "
8482 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
8484 ntups
= PQntuples(res
);
8486 *numTransforms
= ntups
;
8488 transforminfo
= (TransformInfo
*) pg_malloc(ntups
* sizeof(TransformInfo
));
8490 i_tableoid
= PQfnumber(res
, "tableoid");
8491 i_oid
= PQfnumber(res
, "oid");
8492 i_trftype
= PQfnumber(res
, "trftype");
8493 i_trflang
= PQfnumber(res
, "trflang");
8494 i_trffromsql
= PQfnumber(res
, "trffromsql");
8495 i_trftosql
= PQfnumber(res
, "trftosql");
8497 for (i
= 0; i
< ntups
; i
++)
8499 PQExpBufferData namebuf
;
8503 transforminfo
[i
].dobj
.objType
= DO_TRANSFORM
;
8504 transforminfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
8505 transforminfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
8506 AssignDumpId(&transforminfo
[i
].dobj
);
8507 transforminfo
[i
].trftype
= atooid(PQgetvalue(res
, i
, i_trftype
));
8508 transforminfo
[i
].trflang
= atooid(PQgetvalue(res
, i
, i_trflang
));
8509 transforminfo
[i
].trffromsql
= atooid(PQgetvalue(res
, i
, i_trffromsql
));
8510 transforminfo
[i
].trftosql
= atooid(PQgetvalue(res
, i
, i_trftosql
));
8513 * Try to name transform as concatenation of type and language name.
8514 * This is only used for purposes of sorting. If we fail to find
8515 * either, the name will be an empty string.
8517 initPQExpBuffer(&namebuf
);
8518 typeInfo
= findTypeByOid(transforminfo
[i
].trftype
);
8519 lanname
= get_language_name(fout
, transforminfo
[i
].trflang
);
8520 if (typeInfo
&& lanname
)
8521 appendPQExpBuffer(&namebuf
, "%s %s",
8522 typeInfo
->dobj
.name
, lanname
);
8523 transforminfo
[i
].dobj
.name
= namebuf
.data
;
8526 /* Decide whether we want to dump it */
8527 selectDumpableObject(&(transforminfo
[i
].dobj
), fout
);
8532 destroyPQExpBuffer(query
);
8534 return transforminfo
;
8539 * for each interesting table, read info about its attributes
8540 * (names, types, default values, CHECK constraints, etc)
8542 * This is implemented in a very inefficient way right now, looping
8543 * through the tblinfo and doing a join per table to find the attrs and their
8544 * types. However, because we want type names and so forth to be named
8545 * relative to the schema of each table, we couldn't do it in just one
8546 * query. (Maybe one query per schema?)
8551 getTableAttrs(Archive
*fout
, TableInfo
*tblinfo
, int numTables
)
8553 DumpOptions
*dopt
= fout
->dopt
;
8556 PQExpBuffer q
= createPQExpBuffer();
8561 int i_attstattarget
;
8574 int i_attfdwoptions
;
8575 int i_attmissingval
;
8580 for (i
= 0; i
< numTables
; i
++)
8582 TableInfo
*tbinfo
= &tblinfo
[i
];
8584 /* Don't bother to collect info for sequences */
8585 if (tbinfo
->relkind
== RELKIND_SEQUENCE
)
8588 /* Don't bother with uninteresting tables, either */
8589 if (!tbinfo
->interesting
)
8592 /* find all the user attributes and their types */
8595 * we must read the attribute names in attribute number order! because
8596 * we will use the attnum to index into the attnames array later.
8598 pg_log_info("finding the columns and types of table \"%s.%s\"",
8599 tbinfo
->dobj
.namespace->dobj
.name
,
8602 resetPQExpBuffer(q
);
8604 appendPQExpBuffer(q
,
8609 "a.attstattarget,\n"
8618 "pg_catalog.format_type(t.oid, a.atttypmod) AS atttypname,\n");
8620 if (fout
->remoteVersion
>= 120000)
8621 appendPQExpBuffer(q
,
8622 "a.attgenerated,\n");
8624 appendPQExpBuffer(q
,
8625 "'' AS attgenerated,\n");
8627 if (fout
->remoteVersion
>= 110000)
8628 appendPQExpBuffer(q
,
8629 "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8630 "THEN a.attmissingval ELSE null END AS attmissingval,\n");
8632 appendPQExpBuffer(q
,
8633 "NULL AS attmissingval,\n");
8635 if (fout
->remoteVersion
>= 100000)
8636 appendPQExpBuffer(q
,
8637 "a.attidentity,\n");
8639 appendPQExpBuffer(q
,
8640 "'' AS attidentity,\n");
8642 if (fout
->remoteVersion
>= 90200)
8643 appendPQExpBuffer(q
,
8644 "pg_catalog.array_to_string(ARRAY("
8645 "SELECT pg_catalog.quote_ident(option_name) || "
8646 "' ' || pg_catalog.quote_literal(option_value) "
8647 "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8648 "ORDER BY option_name"
8649 "), E',\n ') AS attfdwoptions,\n");
8651 appendPQExpBuffer(q
,
8652 "'' AS attfdwoptions,\n");
8654 if (fout
->remoteVersion
>= 90100)
8657 * Since we only want to dump COLLATE clauses for attributes whose
8658 * collation is different from their type's default, we use a CASE
8659 * here to suppress uninteresting attcollations cheaply.
8661 appendPQExpBuffer(q
,
8662 "CASE WHEN a.attcollation <> t.typcollation "
8663 "THEN a.attcollation ELSE 0 END AS attcollation,\n");
8666 appendPQExpBuffer(q
,
8667 "0 AS attcollation,\n");
8669 if (fout
->remoteVersion
>= 90000)
8670 appendPQExpBuffer(q
,
8671 "array_to_string(a.attoptions, ', ') AS attoptions\n");
8673 appendPQExpBuffer(q
,
8674 "'' AS attoptions\n");
8676 /* need left join here to not fail on dropped columns ... */
8677 appendPQExpBuffer(q
,
8678 "FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t "
8679 "ON a.atttypid = t.oid\n"
8680 "WHERE a.attrelid = '%u'::pg_catalog.oid "
8681 "AND a.attnum > 0::pg_catalog.int2\n"
8682 "ORDER BY a.attnum",
8683 tbinfo
->dobj
.catId
.oid
);
8685 res
= ExecuteSqlQuery(fout
, q
->data
, PGRES_TUPLES_OK
);
8687 ntups
= PQntuples(res
);
8689 i_attnum
= PQfnumber(res
, "attnum");
8690 i_attname
= PQfnumber(res
, "attname");
8691 i_atttypname
= PQfnumber(res
, "atttypname");
8692 i_atttypmod
= PQfnumber(res
, "atttypmod");
8693 i_attstattarget
= PQfnumber(res
, "attstattarget");
8694 i_attstorage
= PQfnumber(res
, "attstorage");
8695 i_typstorage
= PQfnumber(res
, "typstorage");
8696 i_attnotnull
= PQfnumber(res
, "attnotnull");
8697 i_atthasdef
= PQfnumber(res
, "atthasdef");
8698 i_attidentity
= PQfnumber(res
, "attidentity");
8699 i_attgenerated
= PQfnumber(res
, "attgenerated");
8700 i_attisdropped
= PQfnumber(res
, "attisdropped");
8701 i_attlen
= PQfnumber(res
, "attlen");
8702 i_attalign
= PQfnumber(res
, "attalign");
8703 i_attislocal
= PQfnumber(res
, "attislocal");
8704 i_attoptions
= PQfnumber(res
, "attoptions");
8705 i_attcollation
= PQfnumber(res
, "attcollation");
8706 i_attfdwoptions
= PQfnumber(res
, "attfdwoptions");
8707 i_attmissingval
= PQfnumber(res
, "attmissingval");
8709 tbinfo
->numatts
= ntups
;
8710 tbinfo
->attnames
= (char **) pg_malloc(ntups
* sizeof(char *));
8711 tbinfo
->atttypnames
= (char **) pg_malloc(ntups
* sizeof(char *));
8712 tbinfo
->atttypmod
= (int *) pg_malloc(ntups
* sizeof(int));
8713 tbinfo
->attstattarget
= (int *) pg_malloc(ntups
* sizeof(int));
8714 tbinfo
->attstorage
= (char *) pg_malloc(ntups
* sizeof(char));
8715 tbinfo
->typstorage
= (char *) pg_malloc(ntups
* sizeof(char));
8716 tbinfo
->attidentity
= (char *) pg_malloc(ntups
* sizeof(char));
8717 tbinfo
->attgenerated
= (char *) pg_malloc(ntups
* sizeof(char));
8718 tbinfo
->attisdropped
= (bool *) pg_malloc(ntups
* sizeof(bool));
8719 tbinfo
->attlen
= (int *) pg_malloc(ntups
* sizeof(int));
8720 tbinfo
->attalign
= (char *) pg_malloc(ntups
* sizeof(char));
8721 tbinfo
->attislocal
= (bool *) pg_malloc(ntups
* sizeof(bool));
8722 tbinfo
->attoptions
= (char **) pg_malloc(ntups
* sizeof(char *));
8723 tbinfo
->attcollation
= (Oid
*) pg_malloc(ntups
* sizeof(Oid
));
8724 tbinfo
->attfdwoptions
= (char **) pg_malloc(ntups
* sizeof(char *));
8725 tbinfo
->attmissingval
= (char **) pg_malloc(ntups
* sizeof(char *));
8726 tbinfo
->notnull
= (bool *) pg_malloc(ntups
* sizeof(bool));
8727 tbinfo
->inhNotNull
= (bool *) pg_malloc(ntups
* sizeof(bool));
8728 tbinfo
->attrdefs
= (AttrDefInfo
**) pg_malloc(ntups
* sizeof(AttrDefInfo
*));
8729 hasdefaults
= false;
8731 for (j
= 0; j
< ntups
; j
++)
8733 if (j
+ 1 != atoi(PQgetvalue(res
, j
, i_attnum
)))
8734 fatal("invalid column numbering in table \"%s\"",
8736 tbinfo
->attnames
[j
] = pg_strdup(PQgetvalue(res
, j
, i_attname
));
8737 tbinfo
->atttypnames
[j
] = pg_strdup(PQgetvalue(res
, j
, i_atttypname
));
8738 tbinfo
->atttypmod
[j
] = atoi(PQgetvalue(res
, j
, i_atttypmod
));
8739 tbinfo
->attstattarget
[j
] = atoi(PQgetvalue(res
, j
, i_attstattarget
));
8740 tbinfo
->attstorage
[j
] = *(PQgetvalue(res
, j
, i_attstorage
));
8741 tbinfo
->typstorage
[j
] = *(PQgetvalue(res
, j
, i_typstorage
));
8742 tbinfo
->attidentity
[j
] = *(PQgetvalue(res
, j
, i_attidentity
));
8743 tbinfo
->attgenerated
[j
] = *(PQgetvalue(res
, j
, i_attgenerated
));
8744 tbinfo
->needs_override
= tbinfo
->needs_override
|| (tbinfo
->attidentity
[j
] == ATTRIBUTE_IDENTITY_ALWAYS
);
8745 tbinfo
->attisdropped
[j
] = (PQgetvalue(res
, j
, i_attisdropped
)[0] == 't');
8746 tbinfo
->attlen
[j
] = atoi(PQgetvalue(res
, j
, i_attlen
));
8747 tbinfo
->attalign
[j
] = *(PQgetvalue(res
, j
, i_attalign
));
8748 tbinfo
->attislocal
[j
] = (PQgetvalue(res
, j
, i_attislocal
)[0] == 't');
8749 tbinfo
->notnull
[j
] = (PQgetvalue(res
, j
, i_attnotnull
)[0] == 't');
8750 tbinfo
->attoptions
[j
] = pg_strdup(PQgetvalue(res
, j
, i_attoptions
));
8751 tbinfo
->attcollation
[j
] = atooid(PQgetvalue(res
, j
, i_attcollation
));
8752 tbinfo
->attfdwoptions
[j
] = pg_strdup(PQgetvalue(res
, j
, i_attfdwoptions
));
8753 tbinfo
->attmissingval
[j
] = pg_strdup(PQgetvalue(res
, j
, i_attmissingval
));
8754 tbinfo
->attrdefs
[j
] = NULL
; /* fix below */
8755 if (PQgetvalue(res
, j
, i_atthasdef
)[0] == 't')
8757 /* these flags will be set in flagInhAttrs() */
8758 tbinfo
->inhNotNull
[j
] = false;
8764 * Get info about column defaults
8768 AttrDefInfo
*attrdefs
;
8771 pg_log_info("finding default expressions of table \"%s.%s\"",
8772 tbinfo
->dobj
.namespace->dobj
.name
,
8775 printfPQExpBuffer(q
, "SELECT tableoid, oid, adnum, "
8776 "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc "
8777 "FROM pg_catalog.pg_attrdef "
8778 "WHERE adrelid = '%u'::pg_catalog.oid",
8779 tbinfo
->dobj
.catId
.oid
);
8781 res
= ExecuteSqlQuery(fout
, q
->data
, PGRES_TUPLES_OK
);
8783 numDefaults
= PQntuples(res
);
8784 attrdefs
= (AttrDefInfo
*) pg_malloc(numDefaults
* sizeof(AttrDefInfo
));
8786 for (j
= 0; j
< numDefaults
; j
++)
8790 adnum
= atoi(PQgetvalue(res
, j
, 2));
8792 if (adnum
<= 0 || adnum
> ntups
)
8793 fatal("invalid adnum value %d for table \"%s\"",
8794 adnum
, tbinfo
->dobj
.name
);
8797 * dropped columns shouldn't have defaults, but just in case,
8800 if (tbinfo
->attisdropped
[adnum
- 1])
8803 attrdefs
[j
].dobj
.objType
= DO_ATTRDEF
;
8804 attrdefs
[j
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, j
, 0));
8805 attrdefs
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, 1));
8806 AssignDumpId(&attrdefs
[j
].dobj
);
8807 attrdefs
[j
].adtable
= tbinfo
;
8808 attrdefs
[j
].adnum
= adnum
;
8809 attrdefs
[j
].adef_expr
= pg_strdup(PQgetvalue(res
, j
, 3));
8811 attrdefs
[j
].dobj
.name
= pg_strdup(tbinfo
->dobj
.name
);
8812 attrdefs
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
8814 attrdefs
[j
].dobj
.dump
= tbinfo
->dobj
.dump
;
8817 * Figure out whether the default/generation expression should
8818 * be dumped as part of the main CREATE TABLE (or similar)
8819 * command or as a separate ALTER TABLE (or similar) command.
8820 * The preference is to put it into the CREATE command, but in
8821 * some cases that's not possible.
8823 if (tbinfo
->attgenerated
[adnum
- 1])
8826 * Column generation expressions cannot be dumped
8827 * separately, because there is no syntax for it. The
8828 * !shouldPrintColumn case below will be tempted to set
8829 * them to separate if they are attached to an inherited
8830 * column without a local definition, but that would be
8831 * wrong and unnecessary, because generation expressions
8832 * are always inherited, so there is no need to set them
8833 * again in child tables, and there is no syntax for it
8834 * either. By setting separate to false here we prevent
8835 * the "default" from being processed as its own dumpable
8836 * object, and flagInhAttrs() will remove it from the
8837 * table when it detects that it belongs to an inherited
8840 attrdefs
[j
].separate
= false;
8842 else if (tbinfo
->relkind
== RELKIND_VIEW
)
8845 * Defaults on a VIEW must always be dumped as separate
8846 * ALTER TABLE commands.
8848 attrdefs
[j
].separate
= true;
8850 else if (!shouldPrintColumn(dopt
, tbinfo
, adnum
- 1))
8852 /* column will be suppressed, print default separately */
8853 attrdefs
[j
].separate
= true;
8857 attrdefs
[j
].separate
= false;
8860 if (!attrdefs
[j
].separate
)
8863 * Mark the default as needing to appear before the table,
8864 * so that any dependencies it has must be emitted before
8865 * the CREATE TABLE. If this is not possible, we'll
8866 * change to "separate" mode while sorting dependencies.
8868 addObjectDependency(&tbinfo
->dobj
,
8869 attrdefs
[j
].dobj
.dumpId
);
8872 tbinfo
->attrdefs
[adnum
- 1] = &attrdefs
[j
];
8878 * Get info about table CHECK constraints
8880 if (tbinfo
->ncheck
> 0)
8882 ConstraintInfo
*constrs
;
8885 pg_log_info("finding check constraints for table \"%s.%s\"",
8886 tbinfo
->dobj
.namespace->dobj
.name
,
8889 resetPQExpBuffer(q
);
8890 if (fout
->remoteVersion
>= 90200)
8893 * convalidated is new in 9.2 (actually, it is there in 9.1,
8894 * but it wasn't ever false for check constraints until 9.2).
8896 appendPQExpBuffer(q
, "SELECT tableoid, oid, conname, "
8897 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8898 "conislocal, convalidated "
8899 "FROM pg_catalog.pg_constraint "
8900 "WHERE conrelid = '%u'::pg_catalog.oid "
8901 " AND contype = 'c' "
8903 tbinfo
->dobj
.catId
.oid
);
8905 else if (fout
->remoteVersion
>= 80400)
8907 /* conislocal is new in 8.4 */
8908 appendPQExpBuffer(q
, "SELECT tableoid, oid, conname, "
8909 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8910 "conislocal, true AS convalidated "
8911 "FROM pg_catalog.pg_constraint "
8912 "WHERE conrelid = '%u'::pg_catalog.oid "
8913 " AND contype = 'c' "
8915 tbinfo
->dobj
.catId
.oid
);
8919 appendPQExpBuffer(q
, "SELECT tableoid, oid, conname, "
8920 "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8921 "true AS conislocal, true AS convalidated "
8922 "FROM pg_catalog.pg_constraint "
8923 "WHERE conrelid = '%u'::pg_catalog.oid "
8924 " AND contype = 'c' "
8926 tbinfo
->dobj
.catId
.oid
);
8929 res
= ExecuteSqlQuery(fout
, q
->data
, PGRES_TUPLES_OK
);
8931 numConstrs
= PQntuples(res
);
8932 if (numConstrs
!= tbinfo
->ncheck
)
8934 pg_log_error(ngettext("expected %d check constraint on table \"%s\" but found %d",
8935 "expected %d check constraints on table \"%s\" but found %d",
8937 tbinfo
->ncheck
, tbinfo
->dobj
.name
, numConstrs
);
8938 pg_log_error("(The system catalogs might be corrupted.)");
8942 constrs
= (ConstraintInfo
*) pg_malloc(numConstrs
* sizeof(ConstraintInfo
));
8943 tbinfo
->checkexprs
= constrs
;
8945 for (j
= 0; j
< numConstrs
; j
++)
8947 bool validated
= PQgetvalue(res
, j
, 5)[0] == 't';
8949 constrs
[j
].dobj
.objType
= DO_CONSTRAINT
;
8950 constrs
[j
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, j
, 0));
8951 constrs
[j
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, j
, 1));
8952 AssignDumpId(&constrs
[j
].dobj
);
8953 constrs
[j
].dobj
.name
= pg_strdup(PQgetvalue(res
, j
, 2));
8954 constrs
[j
].dobj
.namespace = tbinfo
->dobj
.namespace;
8955 constrs
[j
].contable
= tbinfo
;
8956 constrs
[j
].condomain
= NULL
;
8957 constrs
[j
].contype
= 'c';
8958 constrs
[j
].condef
= pg_strdup(PQgetvalue(res
, j
, 3));
8959 constrs
[j
].confrelid
= InvalidOid
;
8960 constrs
[j
].conindex
= 0;
8961 constrs
[j
].condeferrable
= false;
8962 constrs
[j
].condeferred
= false;
8963 constrs
[j
].conislocal
= (PQgetvalue(res
, j
, 4)[0] == 't');
8966 * An unvalidated constraint needs to be dumped separately, so
8967 * that potentially-violating existing data is loaded before
8970 constrs
[j
].separate
= !validated
;
8972 constrs
[j
].dobj
.dump
= tbinfo
->dobj
.dump
;
8975 * Mark the constraint as needing to appear before the table
8976 * --- this is so that any other dependencies of the
8977 * constraint will be emitted before we try to create the
8978 * table. If the constraint is to be dumped separately, it
8979 * will be dumped after data is loaded anyway, so don't do it.
8980 * (There's an automatic dependency in the opposite direction
8981 * anyway, so don't need to add one manually here.)
8983 if (!constrs
[j
].separate
)
8984 addObjectDependency(&tbinfo
->dobj
,
8985 constrs
[j
].dobj
.dumpId
);
8988 * If the constraint is inherited, this will be detected later
8989 * (in pre-8.4 databases). We also detect later if the
8990 * constraint must be split out from the table definition.
8997 destroyPQExpBuffer(q
);
9001 * Test whether a column should be printed as part of table's CREATE TABLE.
9002 * Column number is zero-based.
9004 * Normally this is always true, but it's false for dropped columns, as well
9005 * as those that were inherited without any local definition. (If we print
9006 * such a column it will mistakenly get pg_attribute.attislocal set to true.)
9007 * For partitions, it's always true, because we want the partitions to be
9008 * created independently and ATTACH PARTITION used afterwards.
9010 * In binary_upgrade mode, we must print all columns and fix the attislocal/
9011 * attisdropped state later, so as to keep control of the physical column
9014 * This function exists because there are scattered nonobvious places that
9015 * must be kept in sync with this decision.
9018 shouldPrintColumn(DumpOptions
*dopt
, TableInfo
*tbinfo
, int colno
)
9020 if (dopt
->binary_upgrade
)
9022 if (tbinfo
->attisdropped
[colno
])
9024 return (tbinfo
->attislocal
[colno
] || tbinfo
->ispartition
);
9030 * read all text search parsers in the system catalogs and return them
9031 * in the TSParserInfo* structure
9033 * numTSParsers is set to the number of parsers read in
9036 getTSParsers(Archive
*fout
, int *numTSParsers
)
9042 TSParserInfo
*prsinfo
;
9053 /* Before 8.3, there is no built-in text search support */
9054 if (fout
->remoteVersion
< 80300)
9060 query
= createPQExpBuffer();
9063 * find all text search objects, including builtin ones; we filter out
9064 * system-defined objects at dump-out time.
9067 appendPQExpBufferStr(query
, "SELECT tableoid, oid, prsname, prsnamespace, "
9068 "prsstart::oid, prstoken::oid, "
9069 "prsend::oid, prsheadline::oid, prslextype::oid "
9070 "FROM pg_ts_parser");
9072 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9074 ntups
= PQntuples(res
);
9075 *numTSParsers
= ntups
;
9077 prsinfo
= (TSParserInfo
*) pg_malloc(ntups
* sizeof(TSParserInfo
));
9079 i_tableoid
= PQfnumber(res
, "tableoid");
9080 i_oid
= PQfnumber(res
, "oid");
9081 i_prsname
= PQfnumber(res
, "prsname");
9082 i_prsnamespace
= PQfnumber(res
, "prsnamespace");
9083 i_prsstart
= PQfnumber(res
, "prsstart");
9084 i_prstoken
= PQfnumber(res
, "prstoken");
9085 i_prsend
= PQfnumber(res
, "prsend");
9086 i_prsheadline
= PQfnumber(res
, "prsheadline");
9087 i_prslextype
= PQfnumber(res
, "prslextype");
9089 for (i
= 0; i
< ntups
; i
++)
9091 prsinfo
[i
].dobj
.objType
= DO_TSPARSER
;
9092 prsinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9093 prsinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9094 AssignDumpId(&prsinfo
[i
].dobj
);
9095 prsinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_prsname
));
9096 prsinfo
[i
].dobj
.namespace =
9098 atooid(PQgetvalue(res
, i
, i_prsnamespace
)));
9099 prsinfo
[i
].prsstart
= atooid(PQgetvalue(res
, i
, i_prsstart
));
9100 prsinfo
[i
].prstoken
= atooid(PQgetvalue(res
, i
, i_prstoken
));
9101 prsinfo
[i
].prsend
= atooid(PQgetvalue(res
, i
, i_prsend
));
9102 prsinfo
[i
].prsheadline
= atooid(PQgetvalue(res
, i
, i_prsheadline
));
9103 prsinfo
[i
].prslextype
= atooid(PQgetvalue(res
, i
, i_prslextype
));
9105 /* Decide whether we want to dump it */
9106 selectDumpableObject(&(prsinfo
[i
].dobj
), fout
);
9108 /* Text Search Parsers do not currently have ACLs. */
9109 prsinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
9114 destroyPQExpBuffer(query
);
9120 * getTSDictionaries:
9121 * read all text search dictionaries in the system catalogs and return them
9122 * in the TSDictInfo* structure
9124 * numTSDicts is set to the number of dictionaries read in
9127 getTSDictionaries(Archive
*fout
, int *numTSDicts
)
9133 TSDictInfo
*dictinfo
;
9137 int i_dictnamespace
;
9140 int i_dictinitoption
;
9142 /* Before 8.3, there is no built-in text search support */
9143 if (fout
->remoteVersion
< 80300)
9149 query
= createPQExpBuffer();
9151 appendPQExpBuffer(query
, "SELECT tableoid, oid, dictname, "
9152 "dictnamespace, (%s dictowner) AS rolname, "
9153 "dicttemplate, dictinitoption "
9157 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9159 ntups
= PQntuples(res
);
9160 *numTSDicts
= ntups
;
9162 dictinfo
= (TSDictInfo
*) pg_malloc(ntups
* sizeof(TSDictInfo
));
9164 i_tableoid
= PQfnumber(res
, "tableoid");
9165 i_oid
= PQfnumber(res
, "oid");
9166 i_dictname
= PQfnumber(res
, "dictname");
9167 i_dictnamespace
= PQfnumber(res
, "dictnamespace");
9168 i_rolname
= PQfnumber(res
, "rolname");
9169 i_dictinitoption
= PQfnumber(res
, "dictinitoption");
9170 i_dicttemplate
= PQfnumber(res
, "dicttemplate");
9172 for (i
= 0; i
< ntups
; i
++)
9174 dictinfo
[i
].dobj
.objType
= DO_TSDICT
;
9175 dictinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9176 dictinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9177 AssignDumpId(&dictinfo
[i
].dobj
);
9178 dictinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_dictname
));
9179 dictinfo
[i
].dobj
.namespace =
9181 atooid(PQgetvalue(res
, i
, i_dictnamespace
)));
9182 dictinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
9183 dictinfo
[i
].dicttemplate
= atooid(PQgetvalue(res
, i
, i_dicttemplate
));
9184 if (PQgetisnull(res
, i
, i_dictinitoption
))
9185 dictinfo
[i
].dictinitoption
= NULL
;
9187 dictinfo
[i
].dictinitoption
= pg_strdup(PQgetvalue(res
, i
, i_dictinitoption
));
9189 /* Decide whether we want to dump it */
9190 selectDumpableObject(&(dictinfo
[i
].dobj
), fout
);
9192 /* Text Search Dictionaries do not currently have ACLs. */
9193 dictinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
9198 destroyPQExpBuffer(query
);
9205 * read all text search templates in the system catalogs and return them
9206 * in the TSTemplateInfo* structure
9208 * numTSTemplates is set to the number of templates read in
9211 getTSTemplates(Archive
*fout
, int *numTSTemplates
)
9217 TSTemplateInfo
*tmplinfo
;
9221 int i_tmplnamespace
;
9225 /* Before 8.3, there is no built-in text search support */
9226 if (fout
->remoteVersion
< 80300)
9228 *numTSTemplates
= 0;
9232 query
= createPQExpBuffer();
9234 appendPQExpBufferStr(query
, "SELECT tableoid, oid, tmplname, "
9235 "tmplnamespace, tmplinit::oid, tmpllexize::oid "
9236 "FROM pg_ts_template");
9238 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9240 ntups
= PQntuples(res
);
9241 *numTSTemplates
= ntups
;
9243 tmplinfo
= (TSTemplateInfo
*) pg_malloc(ntups
* sizeof(TSTemplateInfo
));
9245 i_tableoid
= PQfnumber(res
, "tableoid");
9246 i_oid
= PQfnumber(res
, "oid");
9247 i_tmplname
= PQfnumber(res
, "tmplname");
9248 i_tmplnamespace
= PQfnumber(res
, "tmplnamespace");
9249 i_tmplinit
= PQfnumber(res
, "tmplinit");
9250 i_tmpllexize
= PQfnumber(res
, "tmpllexize");
9252 for (i
= 0; i
< ntups
; i
++)
9254 tmplinfo
[i
].dobj
.objType
= DO_TSTEMPLATE
;
9255 tmplinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9256 tmplinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9257 AssignDumpId(&tmplinfo
[i
].dobj
);
9258 tmplinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_tmplname
));
9259 tmplinfo
[i
].dobj
.namespace =
9261 atooid(PQgetvalue(res
, i
, i_tmplnamespace
)));
9262 tmplinfo
[i
].tmplinit
= atooid(PQgetvalue(res
, i
, i_tmplinit
));
9263 tmplinfo
[i
].tmpllexize
= atooid(PQgetvalue(res
, i
, i_tmpllexize
));
9265 /* Decide whether we want to dump it */
9266 selectDumpableObject(&(tmplinfo
[i
].dobj
), fout
);
9268 /* Text Search Templates do not currently have ACLs. */
9269 tmplinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
9274 destroyPQExpBuffer(query
);
9280 * getTSConfigurations:
9281 * read all text search configurations in the system catalogs and return
9282 * them in the TSConfigInfo* structure
9284 * numTSConfigs is set to the number of configurations read in
9287 getTSConfigurations(Archive
*fout
, int *numTSConfigs
)
9293 TSConfigInfo
*cfginfo
;
9301 /* Before 8.3, there is no built-in text search support */
9302 if (fout
->remoteVersion
< 80300)
9308 query
= createPQExpBuffer();
9310 appendPQExpBuffer(query
, "SELECT tableoid, oid, cfgname, "
9311 "cfgnamespace, (%s cfgowner) AS rolname, cfgparser "
9312 "FROM pg_ts_config",
9315 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9317 ntups
= PQntuples(res
);
9318 *numTSConfigs
= ntups
;
9320 cfginfo
= (TSConfigInfo
*) pg_malloc(ntups
* sizeof(TSConfigInfo
));
9322 i_tableoid
= PQfnumber(res
, "tableoid");
9323 i_oid
= PQfnumber(res
, "oid");
9324 i_cfgname
= PQfnumber(res
, "cfgname");
9325 i_cfgnamespace
= PQfnumber(res
, "cfgnamespace");
9326 i_rolname
= PQfnumber(res
, "rolname");
9327 i_cfgparser
= PQfnumber(res
, "cfgparser");
9329 for (i
= 0; i
< ntups
; i
++)
9331 cfginfo
[i
].dobj
.objType
= DO_TSCONFIG
;
9332 cfginfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9333 cfginfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9334 AssignDumpId(&cfginfo
[i
].dobj
);
9335 cfginfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_cfgname
));
9336 cfginfo
[i
].dobj
.namespace =
9338 atooid(PQgetvalue(res
, i
, i_cfgnamespace
)));
9339 cfginfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
9340 cfginfo
[i
].cfgparser
= atooid(PQgetvalue(res
, i
, i_cfgparser
));
9342 /* Decide whether we want to dump it */
9343 selectDumpableObject(&(cfginfo
[i
].dobj
), fout
);
9345 /* Text Search Configurations do not currently have ACLs. */
9346 cfginfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
9351 destroyPQExpBuffer(query
);
9357 * getForeignDataWrappers:
9358 * read all foreign-data wrappers in the system catalogs and return
9359 * them in the FdwInfo* structure
9361 * numForeignDataWrappers is set to the number of fdws read in
9364 getForeignDataWrappers(Archive
*fout
, int *numForeignDataWrappers
)
9366 DumpOptions
*dopt
= fout
->dopt
;
9384 /* Before 8.4, there are no foreign-data wrappers */
9385 if (fout
->remoteVersion
< 80400)
9387 *numForeignDataWrappers
= 0;
9391 query
= createPQExpBuffer();
9393 if (fout
->remoteVersion
>= 90600)
9395 PQExpBuffer acl_subquery
= createPQExpBuffer();
9396 PQExpBuffer racl_subquery
= createPQExpBuffer();
9397 PQExpBuffer initacl_subquery
= createPQExpBuffer();
9398 PQExpBuffer initracl_subquery
= createPQExpBuffer();
9400 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
9401 initracl_subquery
, "f.fdwacl", "f.fdwowner", "'F'",
9402 dopt
->binary_upgrade
);
9404 appendPQExpBuffer(query
, "SELECT f.tableoid, f.oid, f.fdwname, "
9405 "(%s f.fdwowner) AS rolname, "
9406 "f.fdwhandler::pg_catalog.regproc, "
9407 "f.fdwvalidator::pg_catalog.regproc, "
9410 "%s AS initfdwacl, "
9411 "%s AS initrfdwacl, "
9412 "array_to_string(ARRAY("
9413 "SELECT quote_ident(option_name) || ' ' || "
9414 "quote_literal(option_value) "
9415 "FROM pg_options_to_table(f.fdwoptions) "
9416 "ORDER BY option_name"
9417 "), E',\n ') AS fdwoptions "
9418 "FROM pg_foreign_data_wrapper f "
9419 "LEFT JOIN pg_init_privs pip ON "
9420 "(f.oid = pip.objoid "
9421 "AND pip.classoid = 'pg_foreign_data_wrapper'::regclass "
9422 "AND pip.objsubid = 0) ",
9425 racl_subquery
->data
,
9426 initacl_subquery
->data
,
9427 initracl_subquery
->data
);
9429 destroyPQExpBuffer(acl_subquery
);
9430 destroyPQExpBuffer(racl_subquery
);
9431 destroyPQExpBuffer(initacl_subquery
);
9432 destroyPQExpBuffer(initracl_subquery
);
9434 else if (fout
->remoteVersion
>= 90100)
9436 appendPQExpBuffer(query
, "SELECT tableoid, oid, fdwname, "
9437 "(%s fdwowner) AS rolname, "
9438 "fdwhandler::pg_catalog.regproc, "
9439 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9441 "NULL as initfdwacl, NULL AS initrfdwacl, "
9442 "array_to_string(ARRAY("
9443 "SELECT quote_ident(option_name) || ' ' || "
9444 "quote_literal(option_value) "
9445 "FROM pg_options_to_table(fdwoptions) "
9446 "ORDER BY option_name"
9447 "), E',\n ') AS fdwoptions "
9448 "FROM pg_foreign_data_wrapper",
9453 appendPQExpBuffer(query
, "SELECT tableoid, oid, fdwname, "
9454 "(%s fdwowner) AS rolname, "
9455 "'-' AS fdwhandler, "
9456 "fdwvalidator::pg_catalog.regproc, fdwacl, "
9458 "NULL as initfdwacl, NULL AS initrfdwacl, "
9459 "array_to_string(ARRAY("
9460 "SELECT quote_ident(option_name) || ' ' || "
9461 "quote_literal(option_value) "
9462 "FROM pg_options_to_table(fdwoptions) "
9463 "ORDER BY option_name"
9464 "), E',\n ') AS fdwoptions "
9465 "FROM pg_foreign_data_wrapper",
9469 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9471 ntups
= PQntuples(res
);
9472 *numForeignDataWrappers
= ntups
;
9474 fdwinfo
= (FdwInfo
*) pg_malloc(ntups
* sizeof(FdwInfo
));
9476 i_tableoid
= PQfnumber(res
, "tableoid");
9477 i_oid
= PQfnumber(res
, "oid");
9478 i_fdwname
= PQfnumber(res
, "fdwname");
9479 i_rolname
= PQfnumber(res
, "rolname");
9480 i_fdwhandler
= PQfnumber(res
, "fdwhandler");
9481 i_fdwvalidator
= PQfnumber(res
, "fdwvalidator");
9482 i_fdwacl
= PQfnumber(res
, "fdwacl");
9483 i_rfdwacl
= PQfnumber(res
, "rfdwacl");
9484 i_initfdwacl
= PQfnumber(res
, "initfdwacl");
9485 i_initrfdwacl
= PQfnumber(res
, "initrfdwacl");
9486 i_fdwoptions
= PQfnumber(res
, "fdwoptions");
9488 for (i
= 0; i
< ntups
; i
++)
9490 fdwinfo
[i
].dobj
.objType
= DO_FDW
;
9491 fdwinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9492 fdwinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9493 AssignDumpId(&fdwinfo
[i
].dobj
);
9494 fdwinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_fdwname
));
9495 fdwinfo
[i
].dobj
.namespace = NULL
;
9496 fdwinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
9497 fdwinfo
[i
].fdwhandler
= pg_strdup(PQgetvalue(res
, i
, i_fdwhandler
));
9498 fdwinfo
[i
].fdwvalidator
= pg_strdup(PQgetvalue(res
, i
, i_fdwvalidator
));
9499 fdwinfo
[i
].fdwoptions
= pg_strdup(PQgetvalue(res
, i
, i_fdwoptions
));
9500 fdwinfo
[i
].fdwacl
= pg_strdup(PQgetvalue(res
, i
, i_fdwacl
));
9501 fdwinfo
[i
].rfdwacl
= pg_strdup(PQgetvalue(res
, i
, i_rfdwacl
));
9502 fdwinfo
[i
].initfdwacl
= pg_strdup(PQgetvalue(res
, i
, i_initfdwacl
));
9503 fdwinfo
[i
].initrfdwacl
= pg_strdup(PQgetvalue(res
, i
, i_initrfdwacl
));
9505 /* Decide whether we want to dump it */
9506 selectDumpableObject(&(fdwinfo
[i
].dobj
), fout
);
9508 /* Do not try to dump ACL if no ACL exists. */
9509 if (PQgetisnull(res
, i
, i_fdwacl
) && PQgetisnull(res
, i
, i_rfdwacl
) &&
9510 PQgetisnull(res
, i
, i_initfdwacl
) &&
9511 PQgetisnull(res
, i
, i_initrfdwacl
))
9512 fdwinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
9517 destroyPQExpBuffer(query
);
9523 * getForeignServers:
9524 * read all foreign servers in the system catalogs and return
9525 * them in the ForeignServerInfo * structure
9527 * numForeignServers is set to the number of servers read in
9530 getForeignServers(Archive
*fout
, int *numForeignServers
)
9532 DumpOptions
*dopt
= fout
->dopt
;
9537 ForeignServerInfo
*srvinfo
;
9551 /* Before 8.4, there are no foreign servers */
9552 if (fout
->remoteVersion
< 80400)
9554 *numForeignServers
= 0;
9558 query
= createPQExpBuffer();
9560 if (fout
->remoteVersion
>= 90600)
9562 PQExpBuffer acl_subquery
= createPQExpBuffer();
9563 PQExpBuffer racl_subquery
= createPQExpBuffer();
9564 PQExpBuffer initacl_subquery
= createPQExpBuffer();
9565 PQExpBuffer initracl_subquery
= createPQExpBuffer();
9567 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
9568 initracl_subquery
, "f.srvacl", "f.srvowner", "'S'",
9569 dopt
->binary_upgrade
);
9571 appendPQExpBuffer(query
, "SELECT f.tableoid, f.oid, f.srvname, "
9572 "(%s f.srvowner) AS rolname, "
9573 "f.srvfdw, f.srvtype, f.srvversion, "
9576 "%s AS initsrvacl, "
9577 "%s AS initrsrvacl, "
9578 "array_to_string(ARRAY("
9579 "SELECT quote_ident(option_name) || ' ' || "
9580 "quote_literal(option_value) "
9581 "FROM pg_options_to_table(f.srvoptions) "
9582 "ORDER BY option_name"
9583 "), E',\n ') AS srvoptions "
9584 "FROM pg_foreign_server f "
9585 "LEFT JOIN pg_init_privs pip "
9586 "ON (f.oid = pip.objoid "
9587 "AND pip.classoid = 'pg_foreign_server'::regclass "
9588 "AND pip.objsubid = 0) ",
9591 racl_subquery
->data
,
9592 initacl_subquery
->data
,
9593 initracl_subquery
->data
);
9595 destroyPQExpBuffer(acl_subquery
);
9596 destroyPQExpBuffer(racl_subquery
);
9597 destroyPQExpBuffer(initacl_subquery
);
9598 destroyPQExpBuffer(initracl_subquery
);
9602 appendPQExpBuffer(query
, "SELECT tableoid, oid, srvname, "
9603 "(%s srvowner) AS rolname, "
9604 "srvfdw, srvtype, srvversion, srvacl, "
9606 "NULL AS initsrvacl, NULL AS initrsrvacl, "
9607 "array_to_string(ARRAY("
9608 "SELECT quote_ident(option_name) || ' ' || "
9609 "quote_literal(option_value) "
9610 "FROM pg_options_to_table(srvoptions) "
9611 "ORDER BY option_name"
9612 "), E',\n ') AS srvoptions "
9613 "FROM pg_foreign_server",
9617 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9619 ntups
= PQntuples(res
);
9620 *numForeignServers
= ntups
;
9622 srvinfo
= (ForeignServerInfo
*) pg_malloc(ntups
* sizeof(ForeignServerInfo
));
9624 i_tableoid
= PQfnumber(res
, "tableoid");
9625 i_oid
= PQfnumber(res
, "oid");
9626 i_srvname
= PQfnumber(res
, "srvname");
9627 i_rolname
= PQfnumber(res
, "rolname");
9628 i_srvfdw
= PQfnumber(res
, "srvfdw");
9629 i_srvtype
= PQfnumber(res
, "srvtype");
9630 i_srvversion
= PQfnumber(res
, "srvversion");
9631 i_srvacl
= PQfnumber(res
, "srvacl");
9632 i_rsrvacl
= PQfnumber(res
, "rsrvacl");
9633 i_initsrvacl
= PQfnumber(res
, "initsrvacl");
9634 i_initrsrvacl
= PQfnumber(res
, "initrsrvacl");
9635 i_srvoptions
= PQfnumber(res
, "srvoptions");
9637 for (i
= 0; i
< ntups
; i
++)
9639 srvinfo
[i
].dobj
.objType
= DO_FOREIGN_SERVER
;
9640 srvinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9641 srvinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9642 AssignDumpId(&srvinfo
[i
].dobj
);
9643 srvinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_srvname
));
9644 srvinfo
[i
].dobj
.namespace = NULL
;
9645 srvinfo
[i
].rolname
= pg_strdup(PQgetvalue(res
, i
, i_rolname
));
9646 srvinfo
[i
].srvfdw
= atooid(PQgetvalue(res
, i
, i_srvfdw
));
9647 srvinfo
[i
].srvtype
= pg_strdup(PQgetvalue(res
, i
, i_srvtype
));
9648 srvinfo
[i
].srvversion
= pg_strdup(PQgetvalue(res
, i
, i_srvversion
));
9649 srvinfo
[i
].srvoptions
= pg_strdup(PQgetvalue(res
, i
, i_srvoptions
));
9650 srvinfo
[i
].srvacl
= pg_strdup(PQgetvalue(res
, i
, i_srvacl
));
9651 srvinfo
[i
].rsrvacl
= pg_strdup(PQgetvalue(res
, i
, i_rsrvacl
));
9652 srvinfo
[i
].initsrvacl
= pg_strdup(PQgetvalue(res
, i
, i_initsrvacl
));
9653 srvinfo
[i
].initrsrvacl
= pg_strdup(PQgetvalue(res
, i
, i_initrsrvacl
));
9655 /* Decide whether we want to dump it */
9656 selectDumpableObject(&(srvinfo
[i
].dobj
), fout
);
9658 /* Do not try to dump ACL if no ACL exists. */
9659 if (PQgetisnull(res
, i
, i_srvacl
) && PQgetisnull(res
, i
, i_rsrvacl
) &&
9660 PQgetisnull(res
, i
, i_initsrvacl
) &&
9661 PQgetisnull(res
, i
, i_initrsrvacl
))
9662 srvinfo
[i
].dobj
.dump
&= ~DUMP_COMPONENT_ACL
;
9667 destroyPQExpBuffer(query
);
9674 * read all default ACL information in the system catalogs and return
9675 * them in the DefaultACLInfo structure
9677 * numDefaultACLs is set to the number of ACLs read in
9680 getDefaultACLs(Archive
*fout
, int *numDefaultACLs
)
9682 DumpOptions
*dopt
= fout
->dopt
;
9683 DefaultACLInfo
*daclinfo
;
9689 int i_defaclnamespace
;
9690 int i_defaclobjtype
;
9693 int i_initdefaclacl
;
9694 int i_initrdefaclacl
;
9698 if (fout
->remoteVersion
< 90000)
9700 *numDefaultACLs
= 0;
9704 query
= createPQExpBuffer();
9706 if (fout
->remoteVersion
>= 90600)
9708 PQExpBuffer acl_subquery
= createPQExpBuffer();
9709 PQExpBuffer racl_subquery
= createPQExpBuffer();
9710 PQExpBuffer initacl_subquery
= createPQExpBuffer();
9711 PQExpBuffer initracl_subquery
= createPQExpBuffer();
9714 * Global entries (with defaclnamespace=0) replace the hard-wired
9715 * default ACL for their object type. We should dump them as deltas
9716 * from the default ACL, since that will be used as a starting point
9717 * for interpreting the ALTER DEFAULT PRIVILEGES commands. On the
9718 * other hand, non-global entries can only add privileges not revoke
9719 * them. We must dump those as-is (i.e., as deltas from an empty
9720 * ACL). We implement that by passing NULL as the object type for
9721 * acldefault(), which works because acldefault() is STRICT.
9723 * We can use defaclobjtype as the object type for acldefault(),
9724 * except for the case of 'S' (DEFACLOBJ_SEQUENCE) which must be
9727 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
9728 initracl_subquery
, "defaclacl", "defaclrole",
9729 "CASE WHEN defaclnamespace = 0 THEN"
9730 " CASE WHEN defaclobjtype = 'S' THEN 's'::\"char\""
9731 " ELSE defaclobjtype END "
9733 dopt
->binary_upgrade
);
9735 appendPQExpBuffer(query
, "SELECT d.oid, d.tableoid, "
9736 "(%s d.defaclrole) AS defaclrole, "
9737 "d.defaclnamespace, "
9740 "%s AS rdefaclacl, "
9741 "%s AS initdefaclacl, "
9742 "%s AS initrdefaclacl "
9743 "FROM pg_default_acl d "
9744 "LEFT JOIN pg_init_privs pip ON "
9745 "(d.oid = pip.objoid "
9746 "AND pip.classoid = 'pg_default_acl'::regclass "
9747 "AND pip.objsubid = 0) ",
9750 racl_subquery
->data
,
9751 initacl_subquery
->data
,
9752 initracl_subquery
->data
);
9754 destroyPQExpBuffer(acl_subquery
);
9755 destroyPQExpBuffer(racl_subquery
);
9756 destroyPQExpBuffer(initacl_subquery
);
9757 destroyPQExpBuffer(initracl_subquery
);
9761 appendPQExpBuffer(query
, "SELECT oid, tableoid, "
9762 "(%s defaclrole) AS defaclrole, "
9766 "NULL AS rdefaclacl, "
9767 "NULL AS initdefaclacl, "
9768 "NULL AS initrdefaclacl "
9769 "FROM pg_default_acl",
9773 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
9775 ntups
= PQntuples(res
);
9776 *numDefaultACLs
= ntups
;
9778 daclinfo
= (DefaultACLInfo
*) pg_malloc(ntups
* sizeof(DefaultACLInfo
));
9780 i_oid
= PQfnumber(res
, "oid");
9781 i_tableoid
= PQfnumber(res
, "tableoid");
9782 i_defaclrole
= PQfnumber(res
, "defaclrole");
9783 i_defaclnamespace
= PQfnumber(res
, "defaclnamespace");
9784 i_defaclobjtype
= PQfnumber(res
, "defaclobjtype");
9785 i_defaclacl
= PQfnumber(res
, "defaclacl");
9786 i_rdefaclacl
= PQfnumber(res
, "rdefaclacl");
9787 i_initdefaclacl
= PQfnumber(res
, "initdefaclacl");
9788 i_initrdefaclacl
= PQfnumber(res
, "initrdefaclacl");
9790 for (i
= 0; i
< ntups
; i
++)
9792 Oid nspid
= atooid(PQgetvalue(res
, i
, i_defaclnamespace
));
9794 daclinfo
[i
].dobj
.objType
= DO_DEFAULT_ACL
;
9795 daclinfo
[i
].dobj
.catId
.tableoid
= atooid(PQgetvalue(res
, i
, i_tableoid
));
9796 daclinfo
[i
].dobj
.catId
.oid
= atooid(PQgetvalue(res
, i
, i_oid
));
9797 AssignDumpId(&daclinfo
[i
].dobj
);
9798 /* cheesy ... is it worth coming up with a better object name? */
9799 daclinfo
[i
].dobj
.name
= pg_strdup(PQgetvalue(res
, i
, i_defaclobjtype
));
9801 if (nspid
!= InvalidOid
)
9802 daclinfo
[i
].dobj
.namespace = findNamespace(fout
, nspid
);
9804 daclinfo
[i
].dobj
.namespace = NULL
;
9806 daclinfo
[i
].defaclrole
= pg_strdup(PQgetvalue(res
, i
, i_defaclrole
));
9807 daclinfo
[i
].defaclobjtype
= *(PQgetvalue(res
, i
, i_defaclobjtype
));
9808 daclinfo
[i
].defaclacl
= pg_strdup(PQgetvalue(res
, i
, i_defaclacl
));
9809 daclinfo
[i
].rdefaclacl
= pg_strdup(PQgetvalue(res
, i
, i_rdefaclacl
));
9810 daclinfo
[i
].initdefaclacl
= pg_strdup(PQgetvalue(res
, i
, i_initdefaclacl
));
9811 daclinfo
[i
].initrdefaclacl
= pg_strdup(PQgetvalue(res
, i
, i_initrdefaclacl
));
9813 /* Decide whether we want to dump it */
9814 selectDumpableDefaultACL(&(daclinfo
[i
]), dopt
);
9819 destroyPQExpBuffer(query
);
9827 * This routine is used to dump any comments associated with the
9828 * object handed to this routine. The routine takes the object type
9829 * and object name (ready to print, except for schema decoration), plus
9830 * the namespace and owner of the object (for labeling the ArchiveEntry),
9831 * plus catalog ID and subid which are the lookup key for pg_description,
9832 * plus the dump ID for the object (for setting a dependency).
9833 * If a matching pg_description entry is found, it is dumped.
9835 * Note: in some cases, such as comments for triggers and rules, the "type"
9836 * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
9837 * but it doesn't seem worth complicating the API for all callers to make
9840 * Note: although this routine takes a dumpId for dependency purposes,
9841 * that purpose is just to mark the dependency in the emitted dump file
9842 * for possible future use by pg_restore. We do NOT use it for determining
9843 * ordering of the comment in the dump file, because this routine is called
9844 * after dependency sorting occurs. This routine should be called just after
9845 * calling ArchiveEntry() for the specified object.
9848 dumpComment(Archive
*fout
, const char *type
, const char *name
,
9849 const char *namespace, const char *owner
,
9850 CatalogId catalogId
, int subid
, DumpId dumpId
)
9852 DumpOptions
*dopt
= fout
->dopt
;
9853 CommentItem
*comments
;
9856 /* do nothing, if --no-comments is supplied */
9857 if (dopt
->no_comments
)
9860 /* Comments are schema not data ... except blob comments are data */
9861 if (strcmp(type
, "LARGE OBJECT") != 0)
9868 /* We do dump blob comments in binary-upgrade mode */
9869 if (dopt
->schemaOnly
&& !dopt
->binary_upgrade
)
9873 /* Search for comments associated with catalogId, using table */
9874 ncomments
= findComments(fout
, catalogId
.tableoid
, catalogId
.oid
,
9877 /* Is there one matching the subid? */
9878 while (ncomments
> 0)
9880 if (comments
->objsubid
== subid
)
9886 /* If a comment exists, build COMMENT ON statement */
9889 PQExpBuffer query
= createPQExpBuffer();
9890 PQExpBuffer tag
= createPQExpBuffer();
9892 appendPQExpBuffer(query
, "COMMENT ON %s ", type
);
9893 if (namespace && *namespace)
9894 appendPQExpBuffer(query
, "%s.", fmtId(namespace));
9895 appendPQExpBuffer(query
, "%s IS ", name
);
9896 appendStringLiteralAH(query
, comments
->descr
, fout
);
9897 appendPQExpBufferStr(query
, ";\n");
9899 appendPQExpBuffer(tag
, "%s %s", type
, name
);
9902 * We mark comments as SECTION_NONE because they really belong in the
9903 * same section as their parent, whether that is pre-data or
9906 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
9907 ARCHIVE_OPTS(.tag
= tag
->data
,
9908 .namespace = namespace,
9910 .description
= "COMMENT",
9911 .section
= SECTION_NONE
,
9912 .createStmt
= query
->data
,
9916 destroyPQExpBuffer(query
);
9917 destroyPQExpBuffer(tag
);
9922 * dumpTableComment --
9924 * As above, but dump comments for both the specified table (or view)
9928 dumpTableComment(Archive
*fout
, TableInfo
*tbinfo
,
9929 const char *reltypename
)
9931 DumpOptions
*dopt
= fout
->dopt
;
9932 CommentItem
*comments
;
9937 /* do nothing, if --no-comments is supplied */
9938 if (dopt
->no_comments
)
9941 /* Comments are SCHEMA not data */
9945 /* Search for comments associated with relation, using table */
9946 ncomments
= findComments(fout
,
9947 tbinfo
->dobj
.catId
.tableoid
,
9948 tbinfo
->dobj
.catId
.oid
,
9951 /* If comments exist, build COMMENT ON statements */
9955 query
= createPQExpBuffer();
9956 tag
= createPQExpBuffer();
9958 while (ncomments
> 0)
9960 const char *descr
= comments
->descr
;
9961 int objsubid
= comments
->objsubid
;
9965 resetPQExpBuffer(tag
);
9966 appendPQExpBuffer(tag
, "%s %s", reltypename
,
9967 fmtId(tbinfo
->dobj
.name
));
9969 resetPQExpBuffer(query
);
9970 appendPQExpBuffer(query
, "COMMENT ON %s %s IS ", reltypename
,
9971 fmtQualifiedDumpable(tbinfo
));
9972 appendStringLiteralAH(query
, descr
, fout
);
9973 appendPQExpBufferStr(query
, ";\n");
9975 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
9976 ARCHIVE_OPTS(.tag
= tag
->data
,
9977 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
9978 .owner
= tbinfo
->rolname
,
9979 .description
= "COMMENT",
9980 .section
= SECTION_NONE
,
9981 .createStmt
= query
->data
,
9982 .deps
= &(tbinfo
->dobj
.dumpId
),
9985 else if (objsubid
> 0 && objsubid
<= tbinfo
->numatts
)
9987 resetPQExpBuffer(tag
);
9988 appendPQExpBuffer(tag
, "COLUMN %s.",
9989 fmtId(tbinfo
->dobj
.name
));
9990 appendPQExpBufferStr(tag
, fmtId(tbinfo
->attnames
[objsubid
- 1]));
9992 resetPQExpBuffer(query
);
9993 appendPQExpBuffer(query
, "COMMENT ON COLUMN %s.",
9994 fmtQualifiedDumpable(tbinfo
));
9995 appendPQExpBuffer(query
, "%s IS ",
9996 fmtId(tbinfo
->attnames
[objsubid
- 1]));
9997 appendStringLiteralAH(query
, descr
, fout
);
9998 appendPQExpBufferStr(query
, ";\n");
10000 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
10001 ARCHIVE_OPTS(.tag
= tag
->data
,
10002 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
10003 .owner
= tbinfo
->rolname
,
10004 .description
= "COMMENT",
10005 .section
= SECTION_NONE
,
10006 .createStmt
= query
->data
,
10007 .deps
= &(tbinfo
->dobj
.dumpId
),
10015 destroyPQExpBuffer(query
);
10016 destroyPQExpBuffer(tag
);
10022 * Find the comment(s), if any, associated with the given object. All the
10023 * objsubid values associated with the given classoid/objoid are found with
10027 findComments(Archive
*fout
, Oid classoid
, Oid objoid
,
10028 CommentItem
**items
)
10030 /* static storage for table of comments */
10031 static CommentItem
*comments
= NULL
;
10032 static int ncomments
= -1;
10034 CommentItem
*middle
= NULL
;
10039 /* Get comments if we didn't already */
10041 ncomments
= collectComments(fout
, &comments
);
10044 * Do binary search to find some item matching the object.
10046 low
= &comments
[0];
10047 high
= &comments
[ncomments
- 1];
10048 while (low
<= high
)
10050 middle
= low
+ (high
- low
) / 2;
10052 if (classoid
< middle
->classoid
)
10054 else if (classoid
> middle
->classoid
)
10056 else if (objoid
< middle
->objoid
)
10058 else if (objoid
> middle
->objoid
)
10061 break; /* found a match */
10064 if (low
> high
) /* no matches */
10071 * Now determine how many items match the object. The search loop
10072 * invariant still holds: only items between low and high inclusive could
10076 while (middle
> low
)
10078 if (classoid
!= middle
[-1].classoid
||
10079 objoid
!= middle
[-1].objoid
)
10088 while (middle
<= high
)
10090 if (classoid
!= middle
->classoid
||
10091 objoid
!= middle
->objoid
)
10101 * collectComments --
10103 * Construct a table of all comments available for database objects.
10104 * We used to do per-object queries for the comments, but it's much faster
10105 * to pull them all over at once, and on most databases the memory cost
10108 * The table is sorted by classoid/objid/objsubid for speed in lookup.
10111 collectComments(Archive
*fout
, CommentItem
**items
)
10121 CommentItem
*comments
;
10123 query
= createPQExpBuffer();
10125 appendPQExpBufferStr(query
, "SELECT description, classoid, objoid, objsubid "
10126 "FROM pg_catalog.pg_description "
10127 "ORDER BY classoid, objoid, objsubid");
10129 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
10131 /* Construct lookup table containing OIDs in numeric form */
10133 i_description
= PQfnumber(res
, "description");
10134 i_classoid
= PQfnumber(res
, "classoid");
10135 i_objoid
= PQfnumber(res
, "objoid");
10136 i_objsubid
= PQfnumber(res
, "objsubid");
10138 ntups
= PQntuples(res
);
10140 comments
= (CommentItem
*) pg_malloc(ntups
* sizeof(CommentItem
));
10142 for (i
= 0; i
< ntups
; i
++)
10144 comments
[i
].descr
= PQgetvalue(res
, i
, i_description
);
10145 comments
[i
].classoid
= atooid(PQgetvalue(res
, i
, i_classoid
));
10146 comments
[i
].objoid
= atooid(PQgetvalue(res
, i
, i_objoid
));
10147 comments
[i
].objsubid
= atoi(PQgetvalue(res
, i
, i_objsubid
));
10150 /* Do NOT free the PGresult since we are keeping pointers into it */
10151 destroyPQExpBuffer(query
);
10158 * dumpDumpableObject
10160 * This routine and its subsidiaries are responsible for creating
10161 * ArchiveEntries (TOC objects) for each object to be dumped.
10164 dumpDumpableObject(Archive
*fout
, DumpableObject
*dobj
)
10166 switch (dobj
->objType
)
10169 dumpNamespace(fout
, (NamespaceInfo
*) dobj
);
10172 dumpExtension(fout
, (ExtensionInfo
*) dobj
);
10175 dumpType(fout
, (TypeInfo
*) dobj
);
10177 case DO_SHELL_TYPE
:
10178 dumpShellType(fout
, (ShellTypeInfo
*) dobj
);
10181 dumpFunc(fout
, (FuncInfo
*) dobj
);
10184 dumpAgg(fout
, (AggInfo
*) dobj
);
10187 dumpOpr(fout
, (OprInfo
*) dobj
);
10189 case DO_ACCESS_METHOD
:
10190 dumpAccessMethod(fout
, (AccessMethodInfo
*) dobj
);
10193 dumpOpclass(fout
, (OpclassInfo
*) dobj
);
10196 dumpOpfamily(fout
, (OpfamilyInfo
*) dobj
);
10199 dumpCollation(fout
, (CollInfo
*) dobj
);
10201 case DO_CONVERSION
:
10202 dumpConversion(fout
, (ConvInfo
*) dobj
);
10205 dumpTable(fout
, (TableInfo
*) dobj
);
10208 dumpAttrDef(fout
, (AttrDefInfo
*) dobj
);
10211 dumpIndex(fout
, (IndxInfo
*) dobj
);
10213 case DO_INDEX_ATTACH
:
10214 dumpIndexAttach(fout
, (IndexAttachInfo
*) dobj
);
10217 dumpStatisticsExt(fout
, (StatsExtInfo
*) dobj
);
10219 case DO_REFRESH_MATVIEW
:
10220 refreshMatViewData(fout
, (TableDataInfo
*) dobj
);
10223 dumpRule(fout
, (RuleInfo
*) dobj
);
10226 dumpTrigger(fout
, (TriggerInfo
*) dobj
);
10228 case DO_EVENT_TRIGGER
:
10229 dumpEventTrigger(fout
, (EventTriggerInfo
*) dobj
);
10231 case DO_CONSTRAINT
:
10232 dumpConstraint(fout
, (ConstraintInfo
*) dobj
);
10234 case DO_FK_CONSTRAINT
:
10235 dumpConstraint(fout
, (ConstraintInfo
*) dobj
);
10238 dumpProcLang(fout
, (ProcLangInfo
*) dobj
);
10241 dumpCast(fout
, (CastInfo
*) dobj
);
10244 dumpTransform(fout
, (TransformInfo
*) dobj
);
10246 case DO_SEQUENCE_SET
:
10247 dumpSequenceData(fout
, (TableDataInfo
*) dobj
);
10249 case DO_TABLE_DATA
:
10250 dumpTableData(fout
, (TableDataInfo
*) dobj
);
10252 case DO_DUMMY_TYPE
:
10253 /* table rowtypes and array types are never dumped separately */
10256 dumpTSParser(fout
, (TSParserInfo
*) dobj
);
10259 dumpTSDictionary(fout
, (TSDictInfo
*) dobj
);
10261 case DO_TSTEMPLATE
:
10262 dumpTSTemplate(fout
, (TSTemplateInfo
*) dobj
);
10265 dumpTSConfig(fout
, (TSConfigInfo
*) dobj
);
10268 dumpForeignDataWrapper(fout
, (FdwInfo
*) dobj
);
10270 case DO_FOREIGN_SERVER
:
10271 dumpForeignServer(fout
, (ForeignServerInfo
*) dobj
);
10273 case DO_DEFAULT_ACL
:
10274 dumpDefaultACL(fout
, (DefaultACLInfo
*) dobj
);
10277 dumpBlob(fout
, (BlobInfo
*) dobj
);
10280 if (dobj
->dump
& DUMP_COMPONENT_DATA
)
10284 te
= ArchiveEntry(fout
, dobj
->catId
, dobj
->dumpId
,
10285 ARCHIVE_OPTS(.tag
= dobj
->name
,
10286 .description
= "BLOBS",
10287 .section
= SECTION_DATA
,
10288 .dumpFn
= dumpBlobs
));
10291 * Set the TocEntry's dataLength in case we are doing a
10292 * parallel dump and want to order dump jobs by table size.
10293 * (We need some size estimate for every TocEntry with a
10294 * DataDumper function.) We don't currently have any cheap
10295 * way to estimate the size of blobs, but it doesn't matter;
10296 * let's just set the size to a large value so parallel dumps
10297 * will launch this job first. If there's lots of blobs, we
10298 * win, and if there aren't, we don't lose much. (If you want
10299 * to improve on this, really what you should be thinking
10300 * about is allowing blob dumping to be parallelized, not just
10301 * getting a smarter estimate for the single TOC entry.)
10303 te
->dataLength
= MaxBlockNumber
;
10307 dumpPolicy(fout
, (PolicyInfo
*) dobj
);
10309 case DO_PUBLICATION
:
10310 dumpPublication(fout
, (PublicationInfo
*) dobj
);
10312 case DO_PUBLICATION_REL
:
10313 dumpPublicationTable(fout
, (PublicationRelInfo
*) dobj
);
10315 case DO_SUBSCRIPTION
:
10316 dumpSubscription(fout
, (SubscriptionInfo
*) dobj
);
10318 case DO_PRE_DATA_BOUNDARY
:
10319 case DO_POST_DATA_BOUNDARY
:
10320 /* never dumped, nothing to do */
10327 * writes out to fout the queries to recreate a user-defined namespace
10330 dumpNamespace(Archive
*fout
, NamespaceInfo
*nspinfo
)
10332 DumpOptions
*dopt
= fout
->dopt
;
10337 /* Skip if not to be dumped */
10338 if (!nspinfo
->dobj
.dump
|| dopt
->dataOnly
)
10341 q
= createPQExpBuffer();
10342 delq
= createPQExpBuffer();
10344 qnspname
= pg_strdup(fmtId(nspinfo
->dobj
.name
));
10346 appendPQExpBuffer(delq
, "DROP SCHEMA %s;\n", qnspname
);
10348 appendPQExpBuffer(q
, "CREATE SCHEMA %s;\n", qnspname
);
10350 if (dopt
->binary_upgrade
)
10351 binary_upgrade_extension_member(q
, &nspinfo
->dobj
,
10352 "SCHEMA", qnspname
, NULL
);
10354 if (nspinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
10355 ArchiveEntry(fout
, nspinfo
->dobj
.catId
, nspinfo
->dobj
.dumpId
,
10356 ARCHIVE_OPTS(.tag
= nspinfo
->dobj
.name
,
10357 .owner
= nspinfo
->rolname
,
10358 .description
= "SCHEMA",
10359 .section
= SECTION_PRE_DATA
,
10360 .createStmt
= q
->data
,
10361 .dropStmt
= delq
->data
));
10363 /* Dump Schema Comments and Security Labels */
10364 if (nspinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
10365 dumpComment(fout
, "SCHEMA", qnspname
,
10366 NULL
, nspinfo
->rolname
,
10367 nspinfo
->dobj
.catId
, 0, nspinfo
->dobj
.dumpId
);
10369 if (nspinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
10370 dumpSecLabel(fout
, "SCHEMA", qnspname
,
10371 NULL
, nspinfo
->rolname
,
10372 nspinfo
->dobj
.catId
, 0, nspinfo
->dobj
.dumpId
);
10374 if (nspinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
10375 dumpACL(fout
, nspinfo
->dobj
.dumpId
, InvalidDumpId
, "SCHEMA",
10376 qnspname
, NULL
, NULL
,
10377 nspinfo
->rolname
, nspinfo
->nspacl
, nspinfo
->rnspacl
,
10378 nspinfo
->initnspacl
, nspinfo
->initrnspacl
);
10382 destroyPQExpBuffer(q
);
10383 destroyPQExpBuffer(delq
);
10388 * writes out to fout the queries to recreate an extension
10391 dumpExtension(Archive
*fout
, ExtensionInfo
*extinfo
)
10393 DumpOptions
*dopt
= fout
->dopt
;
10398 /* Skip if not to be dumped */
10399 if (!extinfo
->dobj
.dump
|| dopt
->dataOnly
)
10402 q
= createPQExpBuffer();
10403 delq
= createPQExpBuffer();
10405 qextname
= pg_strdup(fmtId(extinfo
->dobj
.name
));
10407 appendPQExpBuffer(delq
, "DROP EXTENSION %s;\n", qextname
);
10409 if (!dopt
->binary_upgrade
)
10412 * In a regular dump, we simply create the extension, intentionally
10413 * not specifying a version, so that the destination installation's
10414 * default version is used.
10416 * Use of IF NOT EXISTS here is unlike our behavior for other object
10417 * types; but there are various scenarios in which it's convenient to
10418 * manually create the desired extension before restoring, so we
10419 * prefer to allow it to exist already.
10421 appendPQExpBuffer(q
, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
10422 qextname
, fmtId(extinfo
->namespace));
10427 * In binary-upgrade mode, it's critical to reproduce the state of the
10428 * database exactly, so our procedure is to create an empty extension,
10429 * restore all the contained objects normally, and add them to the
10430 * extension one by one. This function performs just the first of
10431 * those steps. binary_upgrade_extension_member() takes care of
10432 * adding member objects as they're created.
10437 appendPQExpBufferStr(q
, "-- For binary upgrade, create an empty extension and insert objects into it\n");
10440 * We unconditionally create the extension, so we must drop it if it
10441 * exists. This could happen if the user deleted 'plpgsql' and then
10442 * readded it, causing its oid to be greater than g_last_builtin_oid.
10444 appendPQExpBuffer(q
, "DROP EXTENSION IF EXISTS %s;\n", qextname
);
10446 appendPQExpBufferStr(q
,
10447 "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
10448 appendStringLiteralAH(q
, extinfo
->dobj
.name
, fout
);
10449 appendPQExpBufferStr(q
, ", ");
10450 appendStringLiteralAH(q
, extinfo
->namespace, fout
);
10451 appendPQExpBufferStr(q
, ", ");
10452 appendPQExpBuffer(q
, "%s, ", extinfo
->relocatable
? "true" : "false");
10453 appendStringLiteralAH(q
, extinfo
->extversion
, fout
);
10454 appendPQExpBufferStr(q
, ", ");
10457 * Note that we're pushing extconfig (an OID array) back into
10458 * pg_extension exactly as-is. This is OK because pg_class OIDs are
10459 * preserved in binary upgrade.
10461 if (strlen(extinfo
->extconfig
) > 2)
10462 appendStringLiteralAH(q
, extinfo
->extconfig
, fout
);
10464 appendPQExpBufferStr(q
, "NULL");
10465 appendPQExpBufferStr(q
, ", ");
10466 if (strlen(extinfo
->extcondition
) > 2)
10467 appendStringLiteralAH(q
, extinfo
->extcondition
, fout
);
10469 appendPQExpBufferStr(q
, "NULL");
10470 appendPQExpBufferStr(q
, ", ");
10471 appendPQExpBufferStr(q
, "ARRAY[");
10473 for (i
= 0; i
< extinfo
->dobj
.nDeps
; i
++)
10475 DumpableObject
*extobj
;
10477 extobj
= findObjectByDumpId(extinfo
->dobj
.dependencies
[i
]);
10478 if (extobj
&& extobj
->objType
== DO_EXTENSION
)
10481 appendPQExpBufferChar(q
, ',');
10482 appendStringLiteralAH(q
, extobj
->name
, fout
);
10485 appendPQExpBufferStr(q
, "]::pg_catalog.text[]");
10486 appendPQExpBufferStr(q
, ");\n");
10489 if (extinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
10490 ArchiveEntry(fout
, extinfo
->dobj
.catId
, extinfo
->dobj
.dumpId
,
10491 ARCHIVE_OPTS(.tag
= extinfo
->dobj
.name
,
10492 .description
= "EXTENSION",
10493 .section
= SECTION_PRE_DATA
,
10494 .createStmt
= q
->data
,
10495 .dropStmt
= delq
->data
));
10497 /* Dump Extension Comments and Security Labels */
10498 if (extinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
10499 dumpComment(fout
, "EXTENSION", qextname
,
10501 extinfo
->dobj
.catId
, 0, extinfo
->dobj
.dumpId
);
10503 if (extinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
10504 dumpSecLabel(fout
, "EXTENSION", qextname
,
10506 extinfo
->dobj
.catId
, 0, extinfo
->dobj
.dumpId
);
10510 destroyPQExpBuffer(q
);
10511 destroyPQExpBuffer(delq
);
10516 * writes out to fout the queries to recreate a user-defined type
10519 dumpType(Archive
*fout
, TypeInfo
*tyinfo
)
10521 DumpOptions
*dopt
= fout
->dopt
;
10523 /* Skip if not to be dumped */
10524 if (!tyinfo
->dobj
.dump
|| dopt
->dataOnly
)
10527 /* Dump out in proper style */
10528 if (tyinfo
->typtype
== TYPTYPE_BASE
)
10529 dumpBaseType(fout
, tyinfo
);
10530 else if (tyinfo
->typtype
== TYPTYPE_DOMAIN
)
10531 dumpDomain(fout
, tyinfo
);
10532 else if (tyinfo
->typtype
== TYPTYPE_COMPOSITE
)
10533 dumpCompositeType(fout
, tyinfo
);
10534 else if (tyinfo
->typtype
== TYPTYPE_ENUM
)
10535 dumpEnumType(fout
, tyinfo
);
10536 else if (tyinfo
->typtype
== TYPTYPE_RANGE
)
10537 dumpRangeType(fout
, tyinfo
);
10538 else if (tyinfo
->typtype
== TYPTYPE_PSEUDO
&& !tyinfo
->isDefined
)
10539 dumpUndefinedType(fout
, tyinfo
);
10541 pg_log_warning("typtype of data type \"%s\" appears to be invalid",
10542 tyinfo
->dobj
.name
);
10547 * writes out to fout the queries to recreate a user-defined enum type
10550 dumpEnumType(Archive
*fout
, TypeInfo
*tyinfo
)
10552 DumpOptions
*dopt
= fout
->dopt
;
10553 PQExpBuffer q
= createPQExpBuffer();
10554 PQExpBuffer delq
= createPQExpBuffer();
10555 PQExpBuffer query
= createPQExpBuffer();
10564 if (fout
->remoteVersion
>= 90100)
10565 appendPQExpBuffer(query
, "SELECT oid, enumlabel "
10566 "FROM pg_catalog.pg_enum "
10567 "WHERE enumtypid = '%u'"
10568 "ORDER BY enumsortorder",
10569 tyinfo
->dobj
.catId
.oid
);
10571 appendPQExpBuffer(query
, "SELECT oid, enumlabel "
10572 "FROM pg_catalog.pg_enum "
10573 "WHERE enumtypid = '%u'"
10575 tyinfo
->dobj
.catId
.oid
);
10577 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
10579 num
= PQntuples(res
);
10581 qtypname
= pg_strdup(fmtId(tyinfo
->dobj
.name
));
10582 qualtypname
= pg_strdup(fmtQualifiedDumpable(tyinfo
));
10585 * CASCADE shouldn't be required here as for normal types since the I/O
10586 * functions are generic and do not get dropped.
10588 appendPQExpBuffer(delq
, "DROP TYPE %s;\n", qualtypname
);
10590 if (dopt
->binary_upgrade
)
10591 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
10592 tyinfo
->dobj
.catId
.oid
,
10595 appendPQExpBuffer(q
, "CREATE TYPE %s AS ENUM (",
10598 if (!dopt
->binary_upgrade
)
10600 /* Labels with server-assigned oids */
10601 for (i
= 0; i
< num
; i
++)
10603 label
= PQgetvalue(res
, i
, PQfnumber(res
, "enumlabel"));
10605 appendPQExpBufferChar(q
, ',');
10606 appendPQExpBufferStr(q
, "\n ");
10607 appendStringLiteralAH(q
, label
, fout
);
10611 appendPQExpBufferStr(q
, "\n);\n");
10613 if (dopt
->binary_upgrade
)
10615 /* Labels with dump-assigned (preserved) oids */
10616 for (i
= 0; i
< num
; i
++)
10618 enum_oid
= atooid(PQgetvalue(res
, i
, PQfnumber(res
, "oid")));
10619 label
= PQgetvalue(res
, i
, PQfnumber(res
, "enumlabel"));
10622 appendPQExpBufferStr(q
, "\n-- For binary upgrade, must preserve pg_enum oids\n");
10623 appendPQExpBuffer(q
,
10624 "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
10626 appendPQExpBuffer(q
, "ALTER TYPE %s ADD VALUE ", qualtypname
);
10627 appendStringLiteralAH(q
, label
, fout
);
10628 appendPQExpBufferStr(q
, ";\n\n");
10632 if (dopt
->binary_upgrade
)
10633 binary_upgrade_extension_member(q
, &tyinfo
->dobj
,
10635 tyinfo
->dobj
.namespace->dobj
.name
);
10637 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
10638 ArchiveEntry(fout
, tyinfo
->dobj
.catId
, tyinfo
->dobj
.dumpId
,
10639 ARCHIVE_OPTS(.tag
= tyinfo
->dobj
.name
,
10640 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
10641 .owner
= tyinfo
->rolname
,
10642 .description
= "TYPE",
10643 .section
= SECTION_PRE_DATA
,
10644 .createStmt
= q
->data
,
10645 .dropStmt
= delq
->data
));
10647 /* Dump Type Comments and Security Labels */
10648 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
10649 dumpComment(fout
, "TYPE", qtypname
,
10650 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
10651 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
10653 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
10654 dumpSecLabel(fout
, "TYPE", qtypname
,
10655 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
10656 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
10658 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
10659 dumpACL(fout
, tyinfo
->dobj
.dumpId
, InvalidDumpId
, "TYPE",
10661 tyinfo
->dobj
.namespace->dobj
.name
,
10662 tyinfo
->rolname
, tyinfo
->typacl
, tyinfo
->rtypacl
,
10663 tyinfo
->inittypacl
, tyinfo
->initrtypacl
);
10666 destroyPQExpBuffer(q
);
10667 destroyPQExpBuffer(delq
);
10668 destroyPQExpBuffer(query
);
10675 * writes out to fout the queries to recreate a user-defined range type
10678 dumpRangeType(Archive
*fout
, TypeInfo
*tyinfo
)
10680 DumpOptions
*dopt
= fout
->dopt
;
10681 PQExpBuffer q
= createPQExpBuffer();
10682 PQExpBuffer delq
= createPQExpBuffer();
10683 PQExpBuffer query
= createPQExpBuffer();
10690 appendPQExpBuffer(query
,
10691 "SELECT pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
10692 "opc.opcname AS opcname, "
10693 "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
10694 " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
10696 "CASE WHEN rngcollation = st.typcollation THEN 0 "
10697 " ELSE rngcollation END AS collation, "
10698 "rngcanonical, rngsubdiff "
10699 "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
10700 " pg_catalog.pg_opclass opc "
10701 "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
10703 tyinfo
->dobj
.catId
.oid
);
10705 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
10707 qtypname
= pg_strdup(fmtId(tyinfo
->dobj
.name
));
10708 qualtypname
= pg_strdup(fmtQualifiedDumpable(tyinfo
));
10711 * CASCADE shouldn't be required here as for normal types since the I/O
10712 * functions are generic and do not get dropped.
10714 appendPQExpBuffer(delq
, "DROP TYPE %s;\n", qualtypname
);
10716 if (dopt
->binary_upgrade
)
10717 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
10718 tyinfo
->dobj
.catId
.oid
,
10721 appendPQExpBuffer(q
, "CREATE TYPE %s AS RANGE (",
10724 appendPQExpBuffer(q
, "\n subtype = %s",
10725 PQgetvalue(res
, 0, PQfnumber(res
, "rngsubtype")));
10727 /* print subtype_opclass only if not default for subtype */
10728 if (PQgetvalue(res
, 0, PQfnumber(res
, "opcdefault"))[0] != 't')
10730 char *opcname
= PQgetvalue(res
, 0, PQfnumber(res
, "opcname"));
10731 char *nspname
= PQgetvalue(res
, 0, PQfnumber(res
, "opcnsp"));
10733 appendPQExpBuffer(q
, ",\n subtype_opclass = %s.",
10735 appendPQExpBufferStr(q
, fmtId(opcname
));
10738 collationOid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "collation")));
10739 if (OidIsValid(collationOid
))
10741 CollInfo
*coll
= findCollationByOid(collationOid
);
10744 appendPQExpBuffer(q
, ",\n collation = %s",
10745 fmtQualifiedDumpable(coll
));
10748 procname
= PQgetvalue(res
, 0, PQfnumber(res
, "rngcanonical"));
10749 if (strcmp(procname
, "-") != 0)
10750 appendPQExpBuffer(q
, ",\n canonical = %s", procname
);
10752 procname
= PQgetvalue(res
, 0, PQfnumber(res
, "rngsubdiff"));
10753 if (strcmp(procname
, "-") != 0)
10754 appendPQExpBuffer(q
, ",\n subtype_diff = %s", procname
);
10756 appendPQExpBufferStr(q
, "\n);\n");
10758 if (dopt
->binary_upgrade
)
10759 binary_upgrade_extension_member(q
, &tyinfo
->dobj
,
10761 tyinfo
->dobj
.namespace->dobj
.name
);
10763 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
10764 ArchiveEntry(fout
, tyinfo
->dobj
.catId
, tyinfo
->dobj
.dumpId
,
10765 ARCHIVE_OPTS(.tag
= tyinfo
->dobj
.name
,
10766 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
10767 .owner
= tyinfo
->rolname
,
10768 .description
= "TYPE",
10769 .section
= SECTION_PRE_DATA
,
10770 .createStmt
= q
->data
,
10771 .dropStmt
= delq
->data
));
10773 /* Dump Type Comments and Security Labels */
10774 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
10775 dumpComment(fout
, "TYPE", qtypname
,
10776 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
10777 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
10779 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
10780 dumpSecLabel(fout
, "TYPE", qtypname
,
10781 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
10782 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
10784 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
10785 dumpACL(fout
, tyinfo
->dobj
.dumpId
, InvalidDumpId
, "TYPE",
10787 tyinfo
->dobj
.namespace->dobj
.name
,
10788 tyinfo
->rolname
, tyinfo
->typacl
, tyinfo
->rtypacl
,
10789 tyinfo
->inittypacl
, tyinfo
->initrtypacl
);
10792 destroyPQExpBuffer(q
);
10793 destroyPQExpBuffer(delq
);
10794 destroyPQExpBuffer(query
);
10800 * dumpUndefinedType
10801 * writes out to fout the queries to recreate a !typisdefined type
10803 * This is a shell type, but we use different terminology to distinguish
10804 * this case from where we have to emit a shell type definition to break
10805 * circular dependencies. An undefined type shouldn't ever have anything
10809 dumpUndefinedType(Archive
*fout
, TypeInfo
*tyinfo
)
10811 DumpOptions
*dopt
= fout
->dopt
;
10812 PQExpBuffer q
= createPQExpBuffer();
10813 PQExpBuffer delq
= createPQExpBuffer();
10817 qtypname
= pg_strdup(fmtId(tyinfo
->dobj
.name
));
10818 qualtypname
= pg_strdup(fmtQualifiedDumpable(tyinfo
));
10820 appendPQExpBuffer(delq
, "DROP TYPE %s;\n", qualtypname
);
10822 if (dopt
->binary_upgrade
)
10823 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
10824 tyinfo
->dobj
.catId
.oid
,
10827 appendPQExpBuffer(q
, "CREATE TYPE %s;\n",
10830 if (dopt
->binary_upgrade
)
10831 binary_upgrade_extension_member(q
, &tyinfo
->dobj
,
10833 tyinfo
->dobj
.namespace->dobj
.name
);
10835 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
10836 ArchiveEntry(fout
, tyinfo
->dobj
.catId
, tyinfo
->dobj
.dumpId
,
10837 ARCHIVE_OPTS(.tag
= tyinfo
->dobj
.name
,
10838 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
10839 .owner
= tyinfo
->rolname
,
10840 .description
= "TYPE",
10841 .section
= SECTION_PRE_DATA
,
10842 .createStmt
= q
->data
,
10843 .dropStmt
= delq
->data
));
10845 /* Dump Type Comments and Security Labels */
10846 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
10847 dumpComment(fout
, "TYPE", qtypname
,
10848 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
10849 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
10851 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
10852 dumpSecLabel(fout
, "TYPE", qtypname
,
10853 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
10854 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
10856 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
10857 dumpACL(fout
, tyinfo
->dobj
.dumpId
, InvalidDumpId
, "TYPE",
10859 tyinfo
->dobj
.namespace->dobj
.name
,
10860 tyinfo
->rolname
, tyinfo
->typacl
, tyinfo
->rtypacl
,
10861 tyinfo
->inittypacl
, tyinfo
->initrtypacl
);
10863 destroyPQExpBuffer(q
);
10864 destroyPQExpBuffer(delq
);
10871 * writes out to fout the queries to recreate a user-defined base type
10874 dumpBaseType(Archive
*fout
, TypeInfo
*tyinfo
)
10876 DumpOptions
*dopt
= fout
->dopt
;
10877 PQExpBuffer q
= createPQExpBuffer();
10878 PQExpBuffer delq
= createPQExpBuffer();
10879 PQExpBuffer query
= createPQExpBuffer();
10897 char *typispreferred
;
10902 char *typcollatable
;
10904 bool typdefault_is_literal
= false;
10906 /* Fetch type-specific details */
10907 if (fout
->remoteVersion
>= 90100)
10909 appendPQExpBuffer(query
, "SELECT typlen, "
10910 "typinput, typoutput, typreceive, typsend, "
10911 "typmodin, typmodout, typanalyze, "
10912 "typreceive::pg_catalog.oid AS typreceiveoid, "
10913 "typsend::pg_catalog.oid AS typsendoid, "
10914 "typmodin::pg_catalog.oid AS typmodinoid, "
10915 "typmodout::pg_catalog.oid AS typmodoutoid, "
10916 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10917 "typcategory, typispreferred, "
10918 "typdelim, typbyval, typalign, typstorage, "
10919 "(typcollation <> 0) AS typcollatable, "
10920 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10921 "FROM pg_catalog.pg_type "
10922 "WHERE oid = '%u'::pg_catalog.oid",
10923 tyinfo
->dobj
.catId
.oid
);
10925 else if (fout
->remoteVersion
>= 80400)
10927 appendPQExpBuffer(query
, "SELECT typlen, "
10928 "typinput, typoutput, typreceive, typsend, "
10929 "typmodin, typmodout, typanalyze, "
10930 "typreceive::pg_catalog.oid AS typreceiveoid, "
10931 "typsend::pg_catalog.oid AS typsendoid, "
10932 "typmodin::pg_catalog.oid AS typmodinoid, "
10933 "typmodout::pg_catalog.oid AS typmodoutoid, "
10934 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10935 "typcategory, typispreferred, "
10936 "typdelim, typbyval, typalign, typstorage, "
10937 "false AS typcollatable, "
10938 "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault "
10939 "FROM pg_catalog.pg_type "
10940 "WHERE oid = '%u'::pg_catalog.oid",
10941 tyinfo
->dobj
.catId
.oid
);
10943 else if (fout
->remoteVersion
>= 80300)
10945 /* Before 8.4, pg_get_expr does not allow 0 for its second arg */
10946 appendPQExpBuffer(query
, "SELECT typlen, "
10947 "typinput, typoutput, typreceive, typsend, "
10948 "typmodin, typmodout, typanalyze, "
10949 "typreceive::pg_catalog.oid AS typreceiveoid, "
10950 "typsend::pg_catalog.oid AS typsendoid, "
10951 "typmodin::pg_catalog.oid AS typmodinoid, "
10952 "typmodout::pg_catalog.oid AS typmodoutoid, "
10953 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10954 "'U' AS typcategory, false AS typispreferred, "
10955 "typdelim, typbyval, typalign, typstorage, "
10956 "false AS typcollatable, "
10957 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10958 "FROM pg_catalog.pg_type "
10959 "WHERE oid = '%u'::pg_catalog.oid",
10960 tyinfo
->dobj
.catId
.oid
);
10964 appendPQExpBuffer(query
, "SELECT typlen, "
10965 "typinput, typoutput, typreceive, typsend, "
10966 "'-' AS typmodin, '-' AS typmodout, "
10968 "typreceive::pg_catalog.oid AS typreceiveoid, "
10969 "typsend::pg_catalog.oid AS typsendoid, "
10970 "0 AS typmodinoid, 0 AS typmodoutoid, "
10971 "typanalyze::pg_catalog.oid AS typanalyzeoid, "
10972 "'U' AS typcategory, false AS typispreferred, "
10973 "typdelim, typbyval, typalign, typstorage, "
10974 "false AS typcollatable, "
10975 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, typdefault "
10976 "FROM pg_catalog.pg_type "
10977 "WHERE oid = '%u'::pg_catalog.oid",
10978 tyinfo
->dobj
.catId
.oid
);
10981 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
10983 typlen
= PQgetvalue(res
, 0, PQfnumber(res
, "typlen"));
10984 typinput
= PQgetvalue(res
, 0, PQfnumber(res
, "typinput"));
10985 typoutput
= PQgetvalue(res
, 0, PQfnumber(res
, "typoutput"));
10986 typreceive
= PQgetvalue(res
, 0, PQfnumber(res
, "typreceive"));
10987 typsend
= PQgetvalue(res
, 0, PQfnumber(res
, "typsend"));
10988 typmodin
= PQgetvalue(res
, 0, PQfnumber(res
, "typmodin"));
10989 typmodout
= PQgetvalue(res
, 0, PQfnumber(res
, "typmodout"));
10990 typanalyze
= PQgetvalue(res
, 0, PQfnumber(res
, "typanalyze"));
10991 typreceiveoid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typreceiveoid")));
10992 typsendoid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typsendoid")));
10993 typmodinoid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typmodinoid")));
10994 typmodoutoid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typmodoutoid")));
10995 typanalyzeoid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typanalyzeoid")));
10996 typcategory
= PQgetvalue(res
, 0, PQfnumber(res
, "typcategory"));
10997 typispreferred
= PQgetvalue(res
, 0, PQfnumber(res
, "typispreferred"));
10998 typdelim
= PQgetvalue(res
, 0, PQfnumber(res
, "typdelim"));
10999 typbyval
= PQgetvalue(res
, 0, PQfnumber(res
, "typbyval"));
11000 typalign
= PQgetvalue(res
, 0, PQfnumber(res
, "typalign"));
11001 typstorage
= PQgetvalue(res
, 0, PQfnumber(res
, "typstorage"));
11002 typcollatable
= PQgetvalue(res
, 0, PQfnumber(res
, "typcollatable"));
11003 if (!PQgetisnull(res
, 0, PQfnumber(res
, "typdefaultbin")))
11004 typdefault
= PQgetvalue(res
, 0, PQfnumber(res
, "typdefaultbin"));
11005 else if (!PQgetisnull(res
, 0, PQfnumber(res
, "typdefault")))
11007 typdefault
= PQgetvalue(res
, 0, PQfnumber(res
, "typdefault"));
11008 typdefault_is_literal
= true; /* it needs quotes */
11013 qtypname
= pg_strdup(fmtId(tyinfo
->dobj
.name
));
11014 qualtypname
= pg_strdup(fmtQualifiedDumpable(tyinfo
));
11017 * The reason we include CASCADE is that the circular dependency between
11018 * the type and its I/O functions makes it impossible to drop the type any
11021 appendPQExpBuffer(delq
, "DROP TYPE %s CASCADE;\n", qualtypname
);
11024 * We might already have a shell type, but setting pg_type_oid is
11025 * harmless, and in any case we'd better set the array type OID.
11027 if (dopt
->binary_upgrade
)
11028 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
11029 tyinfo
->dobj
.catId
.oid
,
11032 appendPQExpBuffer(q
,
11033 "CREATE TYPE %s (\n"
11034 " INTERNALLENGTH = %s",
11036 (strcmp(typlen
, "-1") == 0) ? "variable" : typlen
);
11038 /* regproc result is sufficiently quoted already */
11039 appendPQExpBuffer(q
, ",\n INPUT = %s", typinput
);
11040 appendPQExpBuffer(q
, ",\n OUTPUT = %s", typoutput
);
11041 if (OidIsValid(typreceiveoid
))
11042 appendPQExpBuffer(q
, ",\n RECEIVE = %s", typreceive
);
11043 if (OidIsValid(typsendoid
))
11044 appendPQExpBuffer(q
, ",\n SEND = %s", typsend
);
11045 if (OidIsValid(typmodinoid
))
11046 appendPQExpBuffer(q
, ",\n TYPMOD_IN = %s", typmodin
);
11047 if (OidIsValid(typmodoutoid
))
11048 appendPQExpBuffer(q
, ",\n TYPMOD_OUT = %s", typmodout
);
11049 if (OidIsValid(typanalyzeoid
))
11050 appendPQExpBuffer(q
, ",\n ANALYZE = %s", typanalyze
);
11052 if (strcmp(typcollatable
, "t") == 0)
11053 appendPQExpBufferStr(q
, ",\n COLLATABLE = true");
11055 if (typdefault
!= NULL
)
11057 appendPQExpBufferStr(q
, ",\n DEFAULT = ");
11058 if (typdefault_is_literal
)
11059 appendStringLiteralAH(q
, typdefault
, fout
);
11061 appendPQExpBufferStr(q
, typdefault
);
11064 if (OidIsValid(tyinfo
->typelem
))
11065 appendPQExpBuffer(q
, ",\n ELEMENT = %s",
11066 getFormattedTypeName(fout
, tyinfo
->typelem
,
11069 if (strcmp(typcategory
, "U") != 0)
11071 appendPQExpBufferStr(q
, ",\n CATEGORY = ");
11072 appendStringLiteralAH(q
, typcategory
, fout
);
11075 if (strcmp(typispreferred
, "t") == 0)
11076 appendPQExpBufferStr(q
, ",\n PREFERRED = true");
11078 if (typdelim
&& strcmp(typdelim
, ",") != 0)
11080 appendPQExpBufferStr(q
, ",\n DELIMITER = ");
11081 appendStringLiteralAH(q
, typdelim
, fout
);
11084 if (strcmp(typalign
, "c") == 0)
11085 appendPQExpBufferStr(q
, ",\n ALIGNMENT = char");
11086 else if (strcmp(typalign
, "s") == 0)
11087 appendPQExpBufferStr(q
, ",\n ALIGNMENT = int2");
11088 else if (strcmp(typalign
, "i") == 0)
11089 appendPQExpBufferStr(q
, ",\n ALIGNMENT = int4");
11090 else if (strcmp(typalign
, "d") == 0)
11091 appendPQExpBufferStr(q
, ",\n ALIGNMENT = double");
11093 if (strcmp(typstorage
, "p") == 0)
11094 appendPQExpBufferStr(q
, ",\n STORAGE = plain");
11095 else if (strcmp(typstorage
, "e") == 0)
11096 appendPQExpBufferStr(q
, ",\n STORAGE = external");
11097 else if (strcmp(typstorage
, "x") == 0)
11098 appendPQExpBufferStr(q
, ",\n STORAGE = extended");
11099 else if (strcmp(typstorage
, "m") == 0)
11100 appendPQExpBufferStr(q
, ",\n STORAGE = main");
11102 if (strcmp(typbyval
, "t") == 0)
11103 appendPQExpBufferStr(q
, ",\n PASSEDBYVALUE");
11105 appendPQExpBufferStr(q
, "\n);\n");
11107 if (dopt
->binary_upgrade
)
11108 binary_upgrade_extension_member(q
, &tyinfo
->dobj
,
11110 tyinfo
->dobj
.namespace->dobj
.name
);
11112 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
11113 ArchiveEntry(fout
, tyinfo
->dobj
.catId
, tyinfo
->dobj
.dumpId
,
11114 ARCHIVE_OPTS(.tag
= tyinfo
->dobj
.name
,
11115 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
11116 .owner
= tyinfo
->rolname
,
11117 .description
= "TYPE",
11118 .section
= SECTION_PRE_DATA
,
11119 .createStmt
= q
->data
,
11120 .dropStmt
= delq
->data
));
11122 /* Dump Type Comments and Security Labels */
11123 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
11124 dumpComment(fout
, "TYPE", qtypname
,
11125 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
11126 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11128 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
11129 dumpSecLabel(fout
, "TYPE", qtypname
,
11130 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
11131 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11133 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
11134 dumpACL(fout
, tyinfo
->dobj
.dumpId
, InvalidDumpId
, "TYPE",
11136 tyinfo
->dobj
.namespace->dobj
.name
,
11137 tyinfo
->rolname
, tyinfo
->typacl
, tyinfo
->rtypacl
,
11138 tyinfo
->inittypacl
, tyinfo
->initrtypacl
);
11141 destroyPQExpBuffer(q
);
11142 destroyPQExpBuffer(delq
);
11143 destroyPQExpBuffer(query
);
11150 * writes out to fout the queries to recreate a user-defined domain
11153 dumpDomain(Archive
*fout
, TypeInfo
*tyinfo
)
11155 DumpOptions
*dopt
= fout
->dopt
;
11156 PQExpBuffer q
= createPQExpBuffer();
11157 PQExpBuffer delq
= createPQExpBuffer();
11158 PQExpBuffer query
= createPQExpBuffer();
11167 bool typdefault_is_literal
= false;
11169 /* Fetch domain specific details */
11170 if (fout
->remoteVersion
>= 90100)
11172 /* typcollation is new in 9.1 */
11173 appendPQExpBuffer(query
, "SELECT t.typnotnull, "
11174 "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
11175 "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
11177 "CASE WHEN t.typcollation <> u.typcollation "
11178 "THEN t.typcollation ELSE 0 END AS typcollation "
11179 "FROM pg_catalog.pg_type t "
11180 "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
11181 "WHERE t.oid = '%u'::pg_catalog.oid",
11182 tyinfo
->dobj
.catId
.oid
);
11186 appendPQExpBuffer(query
, "SELECT typnotnull, "
11187 "pg_catalog.format_type(typbasetype, typtypmod) AS typdefn, "
11188 "pg_catalog.pg_get_expr(typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
11189 "typdefault, 0 AS typcollation "
11190 "FROM pg_catalog.pg_type "
11191 "WHERE oid = '%u'::pg_catalog.oid",
11192 tyinfo
->dobj
.catId
.oid
);
11195 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
11197 typnotnull
= PQgetvalue(res
, 0, PQfnumber(res
, "typnotnull"));
11198 typdefn
= PQgetvalue(res
, 0, PQfnumber(res
, "typdefn"));
11199 if (!PQgetisnull(res
, 0, PQfnumber(res
, "typdefaultbin")))
11200 typdefault
= PQgetvalue(res
, 0, PQfnumber(res
, "typdefaultbin"));
11201 else if (!PQgetisnull(res
, 0, PQfnumber(res
, "typdefault")))
11203 typdefault
= PQgetvalue(res
, 0, PQfnumber(res
, "typdefault"));
11204 typdefault_is_literal
= true; /* it needs quotes */
11208 typcollation
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "typcollation")));
11210 if (dopt
->binary_upgrade
)
11211 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
11212 tyinfo
->dobj
.catId
.oid
,
11213 true); /* force array type */
11215 qtypname
= pg_strdup(fmtId(tyinfo
->dobj
.name
));
11216 qualtypname
= pg_strdup(fmtQualifiedDumpable(tyinfo
));
11218 appendPQExpBuffer(q
,
11219 "CREATE DOMAIN %s AS %s",
11223 /* Print collation only if different from base type's collation */
11224 if (OidIsValid(typcollation
))
11228 coll
= findCollationByOid(typcollation
);
11230 appendPQExpBuffer(q
, " COLLATE %s", fmtQualifiedDumpable(coll
));
11233 if (typnotnull
[0] == 't')
11234 appendPQExpBufferStr(q
, " NOT NULL");
11236 if (typdefault
!= NULL
)
11238 appendPQExpBufferStr(q
, " DEFAULT ");
11239 if (typdefault_is_literal
)
11240 appendStringLiteralAH(q
, typdefault
, fout
);
11242 appendPQExpBufferStr(q
, typdefault
);
11248 * Add any CHECK constraints for the domain
11250 for (i
= 0; i
< tyinfo
->nDomChecks
; i
++)
11252 ConstraintInfo
*domcheck
= &(tyinfo
->domChecks
[i
]);
11254 if (!domcheck
->separate
)
11255 appendPQExpBuffer(q
, "\n\tCONSTRAINT %s %s",
11256 fmtId(domcheck
->dobj
.name
), domcheck
->condef
);
11259 appendPQExpBufferStr(q
, ";\n");
11261 appendPQExpBuffer(delq
, "DROP DOMAIN %s;\n", qualtypname
);
11263 if (dopt
->binary_upgrade
)
11264 binary_upgrade_extension_member(q
, &tyinfo
->dobj
,
11265 "DOMAIN", qtypname
,
11266 tyinfo
->dobj
.namespace->dobj
.name
);
11268 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
11269 ArchiveEntry(fout
, tyinfo
->dobj
.catId
, tyinfo
->dobj
.dumpId
,
11270 ARCHIVE_OPTS(.tag
= tyinfo
->dobj
.name
,
11271 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
11272 .owner
= tyinfo
->rolname
,
11273 .description
= "DOMAIN",
11274 .section
= SECTION_PRE_DATA
,
11275 .createStmt
= q
->data
,
11276 .dropStmt
= delq
->data
));
11278 /* Dump Domain Comments and Security Labels */
11279 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
11280 dumpComment(fout
, "DOMAIN", qtypname
,
11281 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
11282 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11284 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
11285 dumpSecLabel(fout
, "DOMAIN", qtypname
,
11286 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
11287 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11289 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
11290 dumpACL(fout
, tyinfo
->dobj
.dumpId
, InvalidDumpId
, "TYPE",
11292 tyinfo
->dobj
.namespace->dobj
.name
,
11293 tyinfo
->rolname
, tyinfo
->typacl
, tyinfo
->rtypacl
,
11294 tyinfo
->inittypacl
, tyinfo
->initrtypacl
);
11296 /* Dump any per-constraint comments */
11297 for (i
= 0; i
< tyinfo
->nDomChecks
; i
++)
11299 ConstraintInfo
*domcheck
= &(tyinfo
->domChecks
[i
]);
11300 PQExpBuffer conprefix
= createPQExpBuffer();
11302 appendPQExpBuffer(conprefix
, "CONSTRAINT %s ON DOMAIN",
11303 fmtId(domcheck
->dobj
.name
));
11305 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
11306 dumpComment(fout
, conprefix
->data
, qtypname
,
11307 tyinfo
->dobj
.namespace->dobj
.name
,
11309 domcheck
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11311 destroyPQExpBuffer(conprefix
);
11314 destroyPQExpBuffer(q
);
11315 destroyPQExpBuffer(delq
);
11316 destroyPQExpBuffer(query
);
11322 * dumpCompositeType
11323 * writes out to fout the queries to recreate a user-defined stand-alone
11327 dumpCompositeType(Archive
*fout
, TypeInfo
*tyinfo
)
11329 DumpOptions
*dopt
= fout
->dopt
;
11330 PQExpBuffer q
= createPQExpBuffer();
11331 PQExpBuffer dropped
= createPQExpBuffer();
11332 PQExpBuffer delq
= createPQExpBuffer();
11333 PQExpBuffer query
= createPQExpBuffer();
11342 int i_attisdropped
;
11343 int i_attcollation
;
11347 /* Fetch type specific details */
11348 if (fout
->remoteVersion
>= 90100)
11351 * attcollation is new in 9.1. Since we only want to dump COLLATE
11352 * clauses for attributes whose collation is different from their
11353 * type's default, we use a CASE here to suppress uninteresting
11354 * attcollations cheaply. atttypid will be 0 for dropped columns;
11355 * collation does not matter for those.
11357 appendPQExpBuffer(query
, "SELECT a.attname, "
11358 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
11359 "a.attlen, a.attalign, a.attisdropped, "
11360 "CASE WHEN a.attcollation <> at.typcollation "
11361 "THEN a.attcollation ELSE 0 END AS attcollation "
11362 "FROM pg_catalog.pg_type ct "
11363 "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
11364 "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
11365 "WHERE ct.oid = '%u'::pg_catalog.oid "
11366 "ORDER BY a.attnum ",
11367 tyinfo
->dobj
.catId
.oid
);
11372 * Since ALTER TYPE could not drop columns until 9.1, attisdropped
11373 * should always be false.
11375 appendPQExpBuffer(query
, "SELECT a.attname, "
11376 "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
11377 "a.attlen, a.attalign, a.attisdropped, "
11378 "0 AS attcollation "
11379 "FROM pg_catalog.pg_type ct, pg_catalog.pg_attribute a "
11380 "WHERE ct.oid = '%u'::pg_catalog.oid "
11381 "AND a.attrelid = ct.typrelid "
11382 "ORDER BY a.attnum ",
11383 tyinfo
->dobj
.catId
.oid
);
11386 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
11388 ntups
= PQntuples(res
);
11390 i_attname
= PQfnumber(res
, "attname");
11391 i_atttypdefn
= PQfnumber(res
, "atttypdefn");
11392 i_attlen
= PQfnumber(res
, "attlen");
11393 i_attalign
= PQfnumber(res
, "attalign");
11394 i_attisdropped
= PQfnumber(res
, "attisdropped");
11395 i_attcollation
= PQfnumber(res
, "attcollation");
11397 if (dopt
->binary_upgrade
)
11399 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
11400 tyinfo
->dobj
.catId
.oid
,
11402 binary_upgrade_set_pg_class_oids(fout
, q
, tyinfo
->typrelid
, false);
11405 qtypname
= pg_strdup(fmtId(tyinfo
->dobj
.name
));
11406 qualtypname
= pg_strdup(fmtQualifiedDumpable(tyinfo
));
11408 appendPQExpBuffer(q
, "CREATE TYPE %s AS (",
11412 for (i
= 0; i
< ntups
; i
++)
11421 attname
= PQgetvalue(res
, i
, i_attname
);
11422 atttypdefn
= PQgetvalue(res
, i
, i_atttypdefn
);
11423 attlen
= PQgetvalue(res
, i
, i_attlen
);
11424 attalign
= PQgetvalue(res
, i
, i_attalign
);
11425 attisdropped
= (PQgetvalue(res
, i
, i_attisdropped
)[0] == 't');
11426 attcollation
= atooid(PQgetvalue(res
, i
, i_attcollation
));
11428 if (attisdropped
&& !dopt
->binary_upgrade
)
11431 /* Format properly if not first attr */
11432 if (actual_atts
++ > 0)
11433 appendPQExpBufferChar(q
, ',');
11434 appendPQExpBufferStr(q
, "\n\t");
11438 appendPQExpBuffer(q
, "%s %s", fmtId(attname
), atttypdefn
);
11440 /* Add collation if not default for the column type */
11441 if (OidIsValid(attcollation
))
11445 coll
= findCollationByOid(attcollation
);
11447 appendPQExpBuffer(q
, " COLLATE %s",
11448 fmtQualifiedDumpable(coll
));
11454 * This is a dropped attribute and we're in binary_upgrade mode.
11455 * Insert a placeholder for it in the CREATE TYPE command, and set
11456 * length and alignment with direct UPDATE to the catalogs
11457 * afterwards. See similar code in dumpTableSchema().
11459 appendPQExpBuffer(q
, "%s INTEGER /* dummy */", fmtId(attname
));
11461 /* stash separately for insertion after the CREATE TYPE */
11462 appendPQExpBufferStr(dropped
,
11463 "\n-- For binary upgrade, recreate dropped column.\n");
11464 appendPQExpBuffer(dropped
, "UPDATE pg_catalog.pg_attribute\n"
11465 "SET attlen = %s, "
11466 "attalign = '%s', attbyval = false\n"
11467 "WHERE attname = ", attlen
, attalign
);
11468 appendStringLiteralAH(dropped
, attname
, fout
);
11469 appendPQExpBufferStr(dropped
, "\n AND attrelid = ");
11470 appendStringLiteralAH(dropped
, qualtypname
, fout
);
11471 appendPQExpBufferStr(dropped
, "::pg_catalog.regclass;\n");
11473 appendPQExpBuffer(dropped
, "ALTER TYPE %s ",
11475 appendPQExpBuffer(dropped
, "DROP ATTRIBUTE %s;\n",
11479 appendPQExpBufferStr(q
, "\n);\n");
11480 appendPQExpBufferStr(q
, dropped
->data
);
11482 appendPQExpBuffer(delq
, "DROP TYPE %s;\n", qualtypname
);
11484 if (dopt
->binary_upgrade
)
11485 binary_upgrade_extension_member(q
, &tyinfo
->dobj
,
11487 tyinfo
->dobj
.namespace->dobj
.name
);
11489 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
11490 ArchiveEntry(fout
, tyinfo
->dobj
.catId
, tyinfo
->dobj
.dumpId
,
11491 ARCHIVE_OPTS(.tag
= tyinfo
->dobj
.name
,
11492 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
11493 .owner
= tyinfo
->rolname
,
11494 .description
= "TYPE",
11495 .section
= SECTION_PRE_DATA
,
11496 .createStmt
= q
->data
,
11497 .dropStmt
= delq
->data
));
11500 /* Dump Type Comments and Security Labels */
11501 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
11502 dumpComment(fout
, "TYPE", qtypname
,
11503 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
11504 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11506 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
11507 dumpSecLabel(fout
, "TYPE", qtypname
,
11508 tyinfo
->dobj
.namespace->dobj
.name
, tyinfo
->rolname
,
11509 tyinfo
->dobj
.catId
, 0, tyinfo
->dobj
.dumpId
);
11511 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
11512 dumpACL(fout
, tyinfo
->dobj
.dumpId
, InvalidDumpId
, "TYPE",
11514 tyinfo
->dobj
.namespace->dobj
.name
,
11515 tyinfo
->rolname
, tyinfo
->typacl
, tyinfo
->rtypacl
,
11516 tyinfo
->inittypacl
, tyinfo
->initrtypacl
);
11519 destroyPQExpBuffer(q
);
11520 destroyPQExpBuffer(dropped
);
11521 destroyPQExpBuffer(delq
);
11522 destroyPQExpBuffer(query
);
11526 /* Dump any per-column comments */
11527 if (tyinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
11528 dumpCompositeTypeColComments(fout
, tyinfo
);
11532 * dumpCompositeTypeColComments
11533 * writes out to fout the queries to recreate comments on the columns of
11534 * a user-defined stand-alone composite type
11537 dumpCompositeTypeColComments(Archive
*fout
, TypeInfo
*tyinfo
)
11539 CommentItem
*comments
;
11543 PQExpBuffer target
;
11550 /* do nothing, if --no-comments is supplied */
11551 if (fout
->dopt
->no_comments
)
11554 query
= createPQExpBuffer();
11556 appendPQExpBuffer(query
,
11557 "SELECT c.tableoid, a.attname, a.attnum "
11558 "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
11559 "WHERE c.oid = '%u' AND c.oid = a.attrelid "
11560 " AND NOT a.attisdropped "
11561 "ORDER BY a.attnum ",
11564 /* Fetch column attnames */
11565 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
11567 ntups
= PQntuples(res
);
11571 destroyPQExpBuffer(query
);
11575 pgClassOid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "tableoid")));
11577 /* Search for comments associated with type's pg_class OID */
11578 ncomments
= findComments(fout
,
11583 /* If no comments exist, we're done */
11584 if (ncomments
<= 0)
11587 destroyPQExpBuffer(query
);
11591 /* Build COMMENT ON statements */
11592 target
= createPQExpBuffer();
11594 i_attnum
= PQfnumber(res
, "attnum");
11595 i_attname
= PQfnumber(res
, "attname");
11596 while (ncomments
> 0)
11598 const char *attname
;
11601 for (i
= 0; i
< ntups
; i
++)
11603 if (atoi(PQgetvalue(res
, i
, i_attnum
)) == comments
->objsubid
)
11605 attname
= PQgetvalue(res
, i
, i_attname
);
11609 if (attname
) /* just in case we don't find it */
11611 const char *descr
= comments
->descr
;
11613 resetPQExpBuffer(target
);
11614 appendPQExpBuffer(target
, "COLUMN %s.",
11615 fmtId(tyinfo
->dobj
.name
));
11616 appendPQExpBufferStr(target
, fmtId(attname
));
11618 resetPQExpBuffer(query
);
11619 appendPQExpBuffer(query
, "COMMENT ON COLUMN %s.",
11620 fmtQualifiedDumpable(tyinfo
));
11621 appendPQExpBuffer(query
, "%s IS ", fmtId(attname
));
11622 appendStringLiteralAH(query
, descr
, fout
);
11623 appendPQExpBufferStr(query
, ";\n");
11625 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
11626 ARCHIVE_OPTS(.tag
= target
->data
,
11627 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
11628 .owner
= tyinfo
->rolname
,
11629 .description
= "COMMENT",
11630 .section
= SECTION_NONE
,
11631 .createStmt
= query
->data
,
11632 .deps
= &(tyinfo
->dobj
.dumpId
),
11641 destroyPQExpBuffer(query
);
11642 destroyPQExpBuffer(target
);
11647 * writes out to fout the queries to create a shell type
11649 * We dump a shell definition in advance of the I/O functions for the type.
11652 dumpShellType(Archive
*fout
, ShellTypeInfo
*stinfo
)
11654 DumpOptions
*dopt
= fout
->dopt
;
11657 /* Skip if not to be dumped */
11658 if (!stinfo
->dobj
.dump
|| dopt
->dataOnly
)
11661 q
= createPQExpBuffer();
11664 * Note the lack of a DROP command for the shell type; any required DROP
11665 * is driven off the base type entry, instead. This interacts with
11666 * _printTocEntry()'s use of the presence of a DROP command to decide
11667 * whether an entry needs an ALTER OWNER command. We don't want to alter
11668 * the shell type's owner immediately on creation; that should happen only
11669 * after it's filled in, otherwise the backend complains.
11672 if (dopt
->binary_upgrade
)
11673 binary_upgrade_set_type_oids_by_type_oid(fout
, q
,
11674 stinfo
->baseType
->dobj
.catId
.oid
,
11677 appendPQExpBuffer(q
, "CREATE TYPE %s;\n",
11678 fmtQualifiedDumpable(stinfo
));
11680 if (stinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
11681 ArchiveEntry(fout
, stinfo
->dobj
.catId
, stinfo
->dobj
.dumpId
,
11682 ARCHIVE_OPTS(.tag
= stinfo
->dobj
.name
,
11683 .namespace = stinfo
->dobj
.namespace->dobj
.name
,
11684 .owner
= stinfo
->baseType
->rolname
,
11685 .description
= "SHELL TYPE",
11686 .section
= SECTION_PRE_DATA
,
11687 .createStmt
= q
->data
));
11689 destroyPQExpBuffer(q
);
11694 * writes out to fout the queries to recreate a user-defined
11695 * procedural language
11698 dumpProcLang(Archive
*fout
, ProcLangInfo
*plang
)
11700 DumpOptions
*dopt
= fout
->dopt
;
11701 PQExpBuffer defqry
;
11702 PQExpBuffer delqry
;
11705 FuncInfo
*funcInfo
;
11706 FuncInfo
*inlineInfo
= NULL
;
11707 FuncInfo
*validatorInfo
= NULL
;
11709 /* Skip if not to be dumped */
11710 if (!plang
->dobj
.dump
|| dopt
->dataOnly
)
11714 * Try to find the support function(s). It is not an error if we don't
11715 * find them --- if the functions are in the pg_catalog schema, as is
11716 * standard in 8.1 and up, then we won't have loaded them. (In this case
11717 * we will emit a parameterless CREATE LANGUAGE command, which will
11718 * require PL template knowledge in the backend to reload.)
11721 funcInfo
= findFuncByOid(plang
->lanplcallfoid
);
11722 if (funcInfo
!= NULL
&& !funcInfo
->dobj
.dump
)
11723 funcInfo
= NULL
; /* treat not-dumped same as not-found */
11725 if (OidIsValid(plang
->laninline
))
11727 inlineInfo
= findFuncByOid(plang
->laninline
);
11728 if (inlineInfo
!= NULL
&& !inlineInfo
->dobj
.dump
)
11732 if (OidIsValid(plang
->lanvalidator
))
11734 validatorInfo
= findFuncByOid(plang
->lanvalidator
);
11735 if (validatorInfo
!= NULL
&& !validatorInfo
->dobj
.dump
)
11736 validatorInfo
= NULL
;
11740 * If the functions are dumpable then emit a traditional CREATE LANGUAGE
11741 * with parameters. Otherwise, we'll write a parameterless command, which
11742 * will rely on data from pg_pltemplate.
11744 useParams
= (funcInfo
!= NULL
&&
11745 (inlineInfo
!= NULL
|| !OidIsValid(plang
->laninline
)) &&
11746 (validatorInfo
!= NULL
|| !OidIsValid(plang
->lanvalidator
)));
11748 defqry
= createPQExpBuffer();
11749 delqry
= createPQExpBuffer();
11751 qlanname
= pg_strdup(fmtId(plang
->dobj
.name
));
11753 appendPQExpBuffer(delqry
, "DROP PROCEDURAL LANGUAGE %s;\n",
11758 appendPQExpBuffer(defqry
, "CREATE %sPROCEDURAL LANGUAGE %s",
11759 plang
->lanpltrusted
? "TRUSTED " : "",
11761 appendPQExpBuffer(defqry
, " HANDLER %s",
11762 fmtQualifiedDumpable(funcInfo
));
11763 if (OidIsValid(plang
->laninline
))
11764 appendPQExpBuffer(defqry
, " INLINE %s",
11765 fmtQualifiedDumpable(inlineInfo
));
11766 if (OidIsValid(plang
->lanvalidator
))
11767 appendPQExpBuffer(defqry
, " VALIDATOR %s",
11768 fmtQualifiedDumpable(validatorInfo
));
11773 * If not dumping parameters, then use CREATE OR REPLACE so that the
11774 * command will not fail if the language is preinstalled in the target
11775 * database. We restrict the use of REPLACE to this case so as to
11776 * eliminate the risk of replacing a language with incompatible
11777 * parameter settings: this command will only succeed at all if there
11778 * is a pg_pltemplate entry, and if there is one, the existing entry
11779 * must match it too.
11781 appendPQExpBuffer(defqry
, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
11784 appendPQExpBufferStr(defqry
, ";\n");
11786 if (dopt
->binary_upgrade
)
11787 binary_upgrade_extension_member(defqry
, &plang
->dobj
,
11788 "LANGUAGE", qlanname
, NULL
);
11790 if (plang
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
11791 ArchiveEntry(fout
, plang
->dobj
.catId
, plang
->dobj
.dumpId
,
11792 ARCHIVE_OPTS(.tag
= plang
->dobj
.name
,
11793 .owner
= plang
->lanowner
,
11794 .description
= "PROCEDURAL LANGUAGE",
11795 .section
= SECTION_PRE_DATA
,
11796 .createStmt
= defqry
->data
,
11797 .dropStmt
= delqry
->data
,
11800 /* Dump Proc Lang Comments and Security Labels */
11801 if (plang
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
11802 dumpComment(fout
, "LANGUAGE", qlanname
,
11803 NULL
, plang
->lanowner
,
11804 plang
->dobj
.catId
, 0, plang
->dobj
.dumpId
);
11806 if (plang
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
11807 dumpSecLabel(fout
, "LANGUAGE", qlanname
,
11808 NULL
, plang
->lanowner
,
11809 plang
->dobj
.catId
, 0, plang
->dobj
.dumpId
);
11811 if (plang
->lanpltrusted
&& plang
->dobj
.dump
& DUMP_COMPONENT_ACL
)
11812 dumpACL(fout
, plang
->dobj
.dumpId
, InvalidDumpId
, "LANGUAGE",
11813 qlanname
, NULL
, NULL
,
11814 plang
->lanowner
, plang
->lanacl
, plang
->rlanacl
,
11815 plang
->initlanacl
, plang
->initrlanacl
);
11819 destroyPQExpBuffer(defqry
);
11820 destroyPQExpBuffer(delqry
);
11824 * format_function_arguments: generate function name and argument list
11826 * This is used when we can rely on pg_get_function_arguments to format
11827 * the argument list. Note, however, that pg_get_function_arguments
11828 * does not special-case zero-argument aggregates.
11831 format_function_arguments(FuncInfo
*finfo
, char *funcargs
, bool is_agg
)
11833 PQExpBufferData fn
;
11835 initPQExpBuffer(&fn
);
11836 appendPQExpBufferStr(&fn
, fmtId(finfo
->dobj
.name
));
11837 if (is_agg
&& finfo
->nargs
== 0)
11838 appendPQExpBufferStr(&fn
, "(*)");
11840 appendPQExpBuffer(&fn
, "(%s)", funcargs
);
11845 * format_function_arguments_old: generate function name and argument list
11847 * The argument type names are qualified if needed. The function name
11848 * is never qualified.
11850 * This is used only with pre-8.4 servers, so we aren't expecting to see
11851 * VARIADIC or TABLE arguments, nor are there any defaults for arguments.
11853 * Any or all of allargtypes, argmodes, argnames may be NULL.
11856 format_function_arguments_old(Archive
*fout
,
11857 FuncInfo
*finfo
, int nallargs
,
11858 char **allargtypes
,
11862 PQExpBufferData fn
;
11865 initPQExpBuffer(&fn
);
11866 appendPQExpBuffer(&fn
, "%s(", fmtId(finfo
->dobj
.name
));
11867 for (j
= 0; j
< nallargs
; j
++)
11870 const char *typname
;
11871 const char *argmode
;
11872 const char *argname
;
11874 typid
= allargtypes
? atooid(allargtypes
[j
]) : finfo
->argtypes
[j
];
11875 typname
= getFormattedTypeName(fout
, typid
, zeroAsOpaque
);
11879 switch (argmodes
[j
][0])
11881 case PROARGMODE_IN
:
11884 case PROARGMODE_OUT
:
11887 case PROARGMODE_INOUT
:
11888 argmode
= "INOUT ";
11891 pg_log_warning("bogus value in proargmodes array");
11899 argname
= argnames
? argnames
[j
] : (char *) NULL
;
11900 if (argname
&& argname
[0] == '\0')
11903 appendPQExpBuffer(&fn
, "%s%s%s%s%s",
11904 (j
> 0) ? ", " : "",
11906 argname
? fmtId(argname
) : "",
11907 argname
? " " : "",
11910 appendPQExpBufferChar(&fn
, ')');
11915 * format_function_signature: generate function name and argument list
11917 * This is like format_function_arguments_old except that only a minimal
11918 * list of input argument types is generated; this is sufficient to
11919 * reference the function, but not to define it.
11921 * If honor_quotes is false then the function name is never quoted.
11922 * This is appropriate for use in TOC tags, but not in SQL commands.
11925 format_function_signature(Archive
*fout
, FuncInfo
*finfo
, bool honor_quotes
)
11927 PQExpBufferData fn
;
11930 initPQExpBuffer(&fn
);
11932 appendPQExpBuffer(&fn
, "%s(", fmtId(finfo
->dobj
.name
));
11934 appendPQExpBuffer(&fn
, "%s(", finfo
->dobj
.name
);
11935 for (j
= 0; j
< finfo
->nargs
; j
++)
11938 appendPQExpBufferStr(&fn
, ", ");
11940 appendPQExpBufferStr(&fn
,
11941 getFormattedTypeName(fout
, finfo
->argtypes
[j
],
11944 appendPQExpBufferChar(&fn
, ')');
11951 * dump out one function
11954 dumpFunc(Archive
*fout
, FuncInfo
*finfo
)
11956 DumpOptions
*dopt
= fout
->dopt
;
11959 PQExpBuffer delqry
;
11960 PQExpBuffer asPart
;
11962 char *funcsig
; /* identity signature */
11963 char *funcfullsig
= NULL
; /* full signature */
11971 char *proallargtypes
;
11979 char *proleakproof
;
11987 char **allargtypes
= NULL
;
11988 char **argmodes
= NULL
;
11989 char **argnames
= NULL
;
11990 char **configitems
= NULL
;
11991 int nconfigitems
= 0;
11992 const char *keyword
;
11995 /* Skip if not to be dumped */
11996 if (!finfo
->dobj
.dump
|| dopt
->dataOnly
)
11999 query
= createPQExpBuffer();
12000 q
= createPQExpBuffer();
12001 delqry
= createPQExpBuffer();
12002 asPart
= createPQExpBuffer();
12004 /* Fetch function-specific details */
12005 if (fout
->remoteVersion
>= 120000)
12008 * prosupport was added in 12
12010 appendPQExpBuffer(query
,
12011 "SELECT proretset, prosrc, probin, "
12012 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12013 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12014 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12015 "array_to_string(protrftypes, ' ') AS protrftypes, "
12016 "prokind, provolatile, proisstrict, prosecdef, "
12017 "proleakproof, proconfig, procost, prorows, "
12018 "prosupport, proparallel, "
12019 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12020 "FROM pg_catalog.pg_proc "
12021 "WHERE oid = '%u'::pg_catalog.oid",
12022 finfo
->dobj
.catId
.oid
);
12024 else if (fout
->remoteVersion
>= 110000)
12027 * prokind was added in 11
12029 appendPQExpBuffer(query
,
12030 "SELECT proretset, prosrc, probin, "
12031 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12032 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12033 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12034 "array_to_string(protrftypes, ' ') AS protrftypes, "
12035 "prokind, provolatile, proisstrict, prosecdef, "
12036 "proleakproof, proconfig, procost, prorows, "
12037 "'-' AS prosupport, proparallel, "
12038 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12039 "FROM pg_catalog.pg_proc "
12040 "WHERE oid = '%u'::pg_catalog.oid",
12041 finfo
->dobj
.catId
.oid
);
12043 else if (fout
->remoteVersion
>= 90600)
12046 * proparallel was added in 9.6
12048 appendPQExpBuffer(query
,
12049 "SELECT proretset, prosrc, probin, "
12050 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12051 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12052 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12053 "array_to_string(protrftypes, ' ') AS protrftypes, "
12054 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12055 "provolatile, proisstrict, prosecdef, "
12056 "proleakproof, proconfig, procost, prorows, "
12057 "'-' AS prosupport, proparallel, "
12058 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12059 "FROM pg_catalog.pg_proc "
12060 "WHERE oid = '%u'::pg_catalog.oid",
12061 finfo
->dobj
.catId
.oid
);
12063 else if (fout
->remoteVersion
>= 90500)
12066 * protrftypes was added in 9.5
12068 appendPQExpBuffer(query
,
12069 "SELECT proretset, prosrc, probin, "
12070 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12071 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12072 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12073 "array_to_string(protrftypes, ' ') AS protrftypes, "
12074 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12075 "provolatile, proisstrict, prosecdef, "
12076 "proleakproof, proconfig, procost, prorows, "
12077 "'-' AS prosupport, "
12078 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12079 "FROM pg_catalog.pg_proc "
12080 "WHERE oid = '%u'::pg_catalog.oid",
12081 finfo
->dobj
.catId
.oid
);
12083 else if (fout
->remoteVersion
>= 90200)
12086 * proleakproof was added in 9.2
12088 appendPQExpBuffer(query
,
12089 "SELECT proretset, prosrc, probin, "
12090 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12091 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12092 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12093 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12094 "provolatile, proisstrict, prosecdef, "
12095 "proleakproof, proconfig, procost, prorows, "
12096 "'-' AS prosupport, "
12097 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12098 "FROM pg_catalog.pg_proc "
12099 "WHERE oid = '%u'::pg_catalog.oid",
12100 finfo
->dobj
.catId
.oid
);
12102 else if (fout
->remoteVersion
>= 80400)
12105 * In 8.4 and up we rely on pg_get_function_arguments and
12106 * pg_get_function_result instead of examining proallargtypes etc.
12108 appendPQExpBuffer(query
,
12109 "SELECT proretset, prosrc, probin, "
12110 "pg_catalog.pg_get_function_arguments(oid) AS funcargs, "
12111 "pg_catalog.pg_get_function_identity_arguments(oid) AS funciargs, "
12112 "pg_catalog.pg_get_function_result(oid) AS funcresult, "
12113 "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind, "
12114 "provolatile, proisstrict, prosecdef, "
12115 "false AS proleakproof, "
12116 " proconfig, procost, prorows, "
12117 "'-' AS prosupport, "
12118 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12119 "FROM pg_catalog.pg_proc "
12120 "WHERE oid = '%u'::pg_catalog.oid",
12121 finfo
->dobj
.catId
.oid
);
12123 else if (fout
->remoteVersion
>= 80300)
12125 appendPQExpBuffer(query
,
12126 "SELECT proretset, prosrc, probin, "
12127 "proallargtypes, proargmodes, proargnames, "
12129 "provolatile, proisstrict, prosecdef, "
12130 "false AS proleakproof, "
12131 "proconfig, procost, prorows, "
12132 "'-' AS prosupport, "
12133 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12134 "FROM pg_catalog.pg_proc "
12135 "WHERE oid = '%u'::pg_catalog.oid",
12136 finfo
->dobj
.catId
.oid
);
12138 else if (fout
->remoteVersion
>= 80100)
12140 appendPQExpBuffer(query
,
12141 "SELECT proretset, prosrc, probin, "
12142 "proallargtypes, proargmodes, proargnames, "
12144 "provolatile, proisstrict, prosecdef, "
12145 "false AS proleakproof, "
12146 "null AS proconfig, 0 AS procost, 0 AS prorows, "
12147 "'-' AS prosupport, "
12148 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12149 "FROM pg_catalog.pg_proc "
12150 "WHERE oid = '%u'::pg_catalog.oid",
12151 finfo
->dobj
.catId
.oid
);
12155 appendPQExpBuffer(query
,
12156 "SELECT proretset, prosrc, probin, "
12157 "null AS proallargtypes, "
12158 "null AS proargmodes, "
12161 "provolatile, proisstrict, prosecdef, "
12162 "false AS proleakproof, "
12163 "null AS proconfig, 0 AS procost, 0 AS prorows, "
12164 "'-' AS prosupport, "
12165 "(SELECT lanname FROM pg_catalog.pg_language WHERE oid = prolang) AS lanname "
12166 "FROM pg_catalog.pg_proc "
12167 "WHERE oid = '%u'::pg_catalog.oid",
12168 finfo
->dobj
.catId
.oid
);
12171 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
12173 proretset
= PQgetvalue(res
, 0, PQfnumber(res
, "proretset"));
12174 prosrc
= PQgetvalue(res
, 0, PQfnumber(res
, "prosrc"));
12175 probin
= PQgetvalue(res
, 0, PQfnumber(res
, "probin"));
12176 if (fout
->remoteVersion
>= 80400)
12178 funcargs
= PQgetvalue(res
, 0, PQfnumber(res
, "funcargs"));
12179 funciargs
= PQgetvalue(res
, 0, PQfnumber(res
, "funciargs"));
12180 funcresult
= PQgetvalue(res
, 0, PQfnumber(res
, "funcresult"));
12181 proallargtypes
= proargmodes
= proargnames
= NULL
;
12185 proallargtypes
= PQgetvalue(res
, 0, PQfnumber(res
, "proallargtypes"));
12186 proargmodes
= PQgetvalue(res
, 0, PQfnumber(res
, "proargmodes"));
12187 proargnames
= PQgetvalue(res
, 0, PQfnumber(res
, "proargnames"));
12188 funcargs
= funciargs
= funcresult
= NULL
;
12190 if (PQfnumber(res
, "protrftypes") != -1)
12191 protrftypes
= PQgetvalue(res
, 0, PQfnumber(res
, "protrftypes"));
12193 protrftypes
= NULL
;
12194 prokind
= PQgetvalue(res
, 0, PQfnumber(res
, "prokind"));
12195 provolatile
= PQgetvalue(res
, 0, PQfnumber(res
, "provolatile"));
12196 proisstrict
= PQgetvalue(res
, 0, PQfnumber(res
, "proisstrict"));
12197 prosecdef
= PQgetvalue(res
, 0, PQfnumber(res
, "prosecdef"));
12198 proleakproof
= PQgetvalue(res
, 0, PQfnumber(res
, "proleakproof"));
12199 proconfig
= PQgetvalue(res
, 0, PQfnumber(res
, "proconfig"));
12200 procost
= PQgetvalue(res
, 0, PQfnumber(res
, "procost"));
12201 prorows
= PQgetvalue(res
, 0, PQfnumber(res
, "prorows"));
12202 prosupport
= PQgetvalue(res
, 0, PQfnumber(res
, "prosupport"));
12204 if (PQfnumber(res
, "proparallel") != -1)
12205 proparallel
= PQgetvalue(res
, 0, PQfnumber(res
, "proparallel"));
12207 proparallel
= NULL
;
12209 lanname
= PQgetvalue(res
, 0, PQfnumber(res
, "lanname"));
12212 * See backend/commands/functioncmds.c for details of how the 'AS' clause
12213 * is used. In 8.4 and up, an unused probin is NULL (here ""); previous
12214 * versions would set it to "-". There are no known cases in which prosrc
12215 * is unused, so the tests below for "-" are probably useless.
12217 if (probin
[0] != '\0' && strcmp(probin
, "-") != 0)
12219 appendPQExpBufferStr(asPart
, "AS ");
12220 appendStringLiteralAH(asPart
, probin
, fout
);
12221 if (strcmp(prosrc
, "-") != 0)
12223 appendPQExpBufferStr(asPart
, ", ");
12226 * where we have bin, use dollar quoting if allowed and src
12227 * contains quote or backslash; else use regular quoting.
12229 if (dopt
->disable_dollar_quoting
||
12230 (strchr(prosrc
, '\'') == NULL
&& strchr(prosrc
, '\\') == NULL
))
12231 appendStringLiteralAH(asPart
, prosrc
, fout
);
12233 appendStringLiteralDQ(asPart
, prosrc
, NULL
);
12238 if (strcmp(prosrc
, "-") != 0)
12240 appendPQExpBufferStr(asPart
, "AS ");
12241 /* with no bin, dollar quote src unconditionally if allowed */
12242 if (dopt
->disable_dollar_quoting
)
12243 appendStringLiteralAH(asPart
, prosrc
, fout
);
12245 appendStringLiteralDQ(asPart
, prosrc
, NULL
);
12249 nallargs
= finfo
->nargs
; /* unless we learn different from allargs */
12251 if (proallargtypes
&& *proallargtypes
)
12255 if (!parsePGArray(proallargtypes
, &allargtypes
, &nitems
) ||
12256 nitems
< finfo
->nargs
)
12258 pg_log_warning("could not parse proallargtypes array");
12261 allargtypes
= NULL
;
12267 if (proargmodes
&& *proargmodes
)
12271 if (!parsePGArray(proargmodes
, &argmodes
, &nitems
) ||
12272 nitems
!= nallargs
)
12274 pg_log_warning("could not parse proargmodes array");
12281 if (proargnames
&& *proargnames
)
12285 if (!parsePGArray(proargnames
, &argnames
, &nitems
) ||
12286 nitems
!= nallargs
)
12288 pg_log_warning("could not parse proargnames array");
12295 if (proconfig
&& *proconfig
)
12297 if (!parsePGArray(proconfig
, &configitems
, &nconfigitems
))
12299 pg_log_warning("could not parse proconfig array");
12302 configitems
= NULL
;
12309 /* 8.4 or later; we rely on server-side code for most of the work */
12310 funcfullsig
= format_function_arguments(finfo
, funcargs
, false);
12311 funcsig
= format_function_arguments(finfo
, funciargs
, false);
12314 /* pre-8.4, do it ourselves */
12315 funcsig
= format_function_arguments_old(fout
,
12316 finfo
, nallargs
, allargtypes
,
12317 argmodes
, argnames
);
12319 funcsig_tag
= format_function_signature(fout
, finfo
, false);
12321 if (prokind
[0] == PROKIND_PROCEDURE
)
12322 keyword
= "PROCEDURE";
12324 keyword
= "FUNCTION"; /* works for window functions too */
12326 appendPQExpBuffer(delqry
, "DROP %s %s.%s;\n",
12328 fmtId(finfo
->dobj
.namespace->dobj
.name
),
12331 appendPQExpBuffer(q
, "CREATE %s %s.%s",
12333 fmtId(finfo
->dobj
.namespace->dobj
.name
),
12334 funcfullsig
? funcfullsig
:
12337 if (prokind
[0] == PROKIND_PROCEDURE
)
12338 /* no result type to output */ ;
12339 else if (funcresult
)
12340 appendPQExpBuffer(q
, " RETURNS %s", funcresult
);
12342 appendPQExpBuffer(q
, " RETURNS %s%s",
12343 (proretset
[0] == 't') ? "SETOF " : "",
12344 getFormattedTypeName(fout
, finfo
->prorettype
,
12347 appendPQExpBuffer(q
, "\n LANGUAGE %s", fmtId(lanname
));
12349 if (protrftypes
!= NULL
&& strcmp(protrftypes
, "") != 0)
12351 Oid
*typeids
= palloc(FUNC_MAX_ARGS
* sizeof(Oid
));
12354 appendPQExpBufferStr(q
, " TRANSFORM ");
12355 parseOidArray(protrftypes
, typeids
, FUNC_MAX_ARGS
);
12356 for (i
= 0; typeids
[i
]; i
++)
12359 appendPQExpBufferStr(q
, ", ");
12360 appendPQExpBuffer(q
, "FOR TYPE %s",
12361 getFormattedTypeName(fout
, typeids
[i
], zeroAsNone
));
12365 if (prokind
[0] == PROKIND_WINDOW
)
12366 appendPQExpBufferStr(q
, " WINDOW");
12368 if (provolatile
[0] != PROVOLATILE_VOLATILE
)
12370 if (provolatile
[0] == PROVOLATILE_IMMUTABLE
)
12371 appendPQExpBufferStr(q
, " IMMUTABLE");
12372 else if (provolatile
[0] == PROVOLATILE_STABLE
)
12373 appendPQExpBufferStr(q
, " STABLE");
12374 else if (provolatile
[0] != PROVOLATILE_VOLATILE
)
12375 fatal("unrecognized provolatile value for function \"%s\"",
12379 if (proisstrict
[0] == 't')
12380 appendPQExpBufferStr(q
, " STRICT");
12382 if (prosecdef
[0] == 't')
12383 appendPQExpBufferStr(q
, " SECURITY DEFINER");
12385 if (proleakproof
[0] == 't')
12386 appendPQExpBufferStr(q
, " LEAKPROOF");
12389 * COST and ROWS are emitted only if present and not default, so as not to
12390 * break backwards-compatibility of the dump without need. Keep this code
12391 * in sync with the defaults in functioncmds.c.
12393 if (strcmp(procost
, "0") != 0)
12395 if (strcmp(lanname
, "internal") == 0 || strcmp(lanname
, "c") == 0)
12397 /* default cost is 1 */
12398 if (strcmp(procost
, "1") != 0)
12399 appendPQExpBuffer(q
, " COST %s", procost
);
12403 /* default cost is 100 */
12404 if (strcmp(procost
, "100") != 0)
12405 appendPQExpBuffer(q
, " COST %s", procost
);
12408 if (proretset
[0] == 't' &&
12409 strcmp(prorows
, "0") != 0 && strcmp(prorows
, "1000") != 0)
12410 appendPQExpBuffer(q
, " ROWS %s", prorows
);
12412 if (strcmp(prosupport
, "-") != 0)
12414 /* We rely on regprocout to provide quoting and qualification */
12415 appendPQExpBuffer(q
, " SUPPORT %s", prosupport
);
12418 if (proparallel
!= NULL
&& proparallel
[0] != PROPARALLEL_UNSAFE
)
12420 if (proparallel
[0] == PROPARALLEL_SAFE
)
12421 appendPQExpBufferStr(q
, " PARALLEL SAFE");
12422 else if (proparallel
[0] == PROPARALLEL_RESTRICTED
)
12423 appendPQExpBufferStr(q
, " PARALLEL RESTRICTED");
12424 else if (proparallel
[0] != PROPARALLEL_UNSAFE
)
12425 fatal("unrecognized proparallel value for function \"%s\"",
12429 for (i
= 0; i
< nconfigitems
; i
++)
12431 /* we feel free to scribble on configitems[] here */
12432 char *configitem
= configitems
[i
];
12435 pos
= strchr(configitem
, '=');
12439 appendPQExpBuffer(q
, "\n SET %s TO ", fmtId(configitem
));
12442 * Variables that are marked GUC_LIST_QUOTE were already fully quoted
12443 * by flatten_set_variable_args() before they were put into the
12444 * proconfig array. However, because the quoting rules used there
12445 * aren't exactly like SQL's, we have to break the list value apart
12446 * and then quote the elements as string literals. (The elements may
12447 * be double-quoted as-is, but we can't just feed them to the SQL
12448 * parser; it would do the wrong thing with elements that are
12449 * zero-length or longer than NAMEDATALEN.)
12451 * Variables that are not so marked should just be emitted as simple
12452 * string literals. If the variable is not known to
12453 * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
12454 * to use GUC_LIST_QUOTE for extension variables.
12456 if (variable_is_guc_list_quote(configitem
))
12461 /* Parse string into list of identifiers */
12462 /* this shouldn't fail really */
12463 if (SplitGUCList(pos
, ',', &namelist
))
12465 for (nameptr
= namelist
; *nameptr
; nameptr
++)
12467 if (nameptr
!= namelist
)
12468 appendPQExpBufferStr(q
, ", ");
12469 appendStringLiteralAH(q
, *nameptr
, fout
);
12475 appendStringLiteralAH(q
, pos
, fout
);
12478 appendPQExpBuffer(q
, "\n %s;\n", asPart
->data
);
12480 append_depends_on_extension(fout
, q
, &finfo
->dobj
,
12481 "pg_catalog.pg_proc", keyword
,
12483 fmtId(finfo
->dobj
.namespace->dobj
.name
),
12486 if (dopt
->binary_upgrade
)
12487 binary_upgrade_extension_member(q
, &finfo
->dobj
,
12489 finfo
->dobj
.namespace->dobj
.name
);
12491 if (finfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
12492 ArchiveEntry(fout
, finfo
->dobj
.catId
, finfo
->dobj
.dumpId
,
12493 ARCHIVE_OPTS(.tag
= funcsig_tag
,
12494 .namespace = finfo
->dobj
.namespace->dobj
.name
,
12495 .owner
= finfo
->rolname
,
12496 .description
= keyword
,
12497 .section
= SECTION_PRE_DATA
,
12498 .createStmt
= q
->data
,
12499 .dropStmt
= delqry
->data
));
12501 /* Dump Function Comments and Security Labels */
12502 if (finfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
12503 dumpComment(fout
, keyword
, funcsig
,
12504 finfo
->dobj
.namespace->dobj
.name
, finfo
->rolname
,
12505 finfo
->dobj
.catId
, 0, finfo
->dobj
.dumpId
);
12507 if (finfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
12508 dumpSecLabel(fout
, keyword
, funcsig
,
12509 finfo
->dobj
.namespace->dobj
.name
, finfo
->rolname
,
12510 finfo
->dobj
.catId
, 0, finfo
->dobj
.dumpId
);
12512 if (finfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
12513 dumpACL(fout
, finfo
->dobj
.dumpId
, InvalidDumpId
, keyword
,
12515 finfo
->dobj
.namespace->dobj
.name
,
12516 finfo
->rolname
, finfo
->proacl
, finfo
->rproacl
,
12517 finfo
->initproacl
, finfo
->initrproacl
);
12521 destroyPQExpBuffer(query
);
12522 destroyPQExpBuffer(q
);
12523 destroyPQExpBuffer(delqry
);
12524 destroyPQExpBuffer(asPart
);
12541 * Dump a user-defined cast
12544 dumpCast(Archive
*fout
, CastInfo
*cast
)
12546 DumpOptions
*dopt
= fout
->dopt
;
12547 PQExpBuffer defqry
;
12548 PQExpBuffer delqry
;
12549 PQExpBuffer labelq
;
12550 PQExpBuffer castargs
;
12551 FuncInfo
*funcInfo
= NULL
;
12552 const char *sourceType
;
12553 const char *targetType
;
12555 /* Skip if not to be dumped */
12556 if (!cast
->dobj
.dump
|| dopt
->dataOnly
)
12559 /* Cannot dump if we don't have the cast function's info */
12560 if (OidIsValid(cast
->castfunc
))
12562 funcInfo
= findFuncByOid(cast
->castfunc
);
12563 if (funcInfo
== NULL
)
12564 fatal("could not find function definition for function with OID %u",
12568 defqry
= createPQExpBuffer();
12569 delqry
= createPQExpBuffer();
12570 labelq
= createPQExpBuffer();
12571 castargs
= createPQExpBuffer();
12573 sourceType
= getFormattedTypeName(fout
, cast
->castsource
, zeroAsNone
);
12574 targetType
= getFormattedTypeName(fout
, cast
->casttarget
, zeroAsNone
);
12575 appendPQExpBuffer(delqry
, "DROP CAST (%s AS %s);\n",
12576 sourceType
, targetType
);
12578 appendPQExpBuffer(defqry
, "CREATE CAST (%s AS %s) ",
12579 sourceType
, targetType
);
12581 switch (cast
->castmethod
)
12583 case COERCION_METHOD_BINARY
:
12584 appendPQExpBufferStr(defqry
, "WITHOUT FUNCTION");
12586 case COERCION_METHOD_INOUT
:
12587 appendPQExpBufferStr(defqry
, "WITH INOUT");
12589 case COERCION_METHOD_FUNCTION
:
12592 char *fsig
= format_function_signature(fout
, funcInfo
, true);
12595 * Always qualify the function name (format_function_signature
12596 * won't qualify it).
12598 appendPQExpBuffer(defqry
, "WITH FUNCTION %s.%s",
12599 fmtId(funcInfo
->dobj
.namespace->dobj
.name
), fsig
);
12603 pg_log_warning("bogus value in pg_cast.castfunc or pg_cast.castmethod field");
12606 pg_log_warning("bogus value in pg_cast.castmethod field");
12609 if (cast
->castcontext
== 'a')
12610 appendPQExpBufferStr(defqry
, " AS ASSIGNMENT");
12611 else if (cast
->castcontext
== 'i')
12612 appendPQExpBufferStr(defqry
, " AS IMPLICIT");
12613 appendPQExpBufferStr(defqry
, ";\n");
12615 appendPQExpBuffer(labelq
, "CAST (%s AS %s)",
12616 sourceType
, targetType
);
12618 appendPQExpBuffer(castargs
, "(%s AS %s)",
12619 sourceType
, targetType
);
12621 if (dopt
->binary_upgrade
)
12622 binary_upgrade_extension_member(defqry
, &cast
->dobj
,
12623 "CAST", castargs
->data
, NULL
);
12625 if (cast
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
12626 ArchiveEntry(fout
, cast
->dobj
.catId
, cast
->dobj
.dumpId
,
12627 ARCHIVE_OPTS(.tag
= labelq
->data
,
12628 .description
= "CAST",
12629 .section
= SECTION_PRE_DATA
,
12630 .createStmt
= defqry
->data
,
12631 .dropStmt
= delqry
->data
));
12633 /* Dump Cast Comments */
12634 if (cast
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
12635 dumpComment(fout
, "CAST", castargs
->data
,
12637 cast
->dobj
.catId
, 0, cast
->dobj
.dumpId
);
12639 destroyPQExpBuffer(defqry
);
12640 destroyPQExpBuffer(delqry
);
12641 destroyPQExpBuffer(labelq
);
12642 destroyPQExpBuffer(castargs
);
12649 dumpTransform(Archive
*fout
, TransformInfo
*transform
)
12651 DumpOptions
*dopt
= fout
->dopt
;
12652 PQExpBuffer defqry
;
12653 PQExpBuffer delqry
;
12654 PQExpBuffer labelq
;
12655 PQExpBuffer transformargs
;
12656 FuncInfo
*fromsqlFuncInfo
= NULL
;
12657 FuncInfo
*tosqlFuncInfo
= NULL
;
12659 const char *transformType
;
12661 /* Skip if not to be dumped */
12662 if (!transform
->dobj
.dump
|| dopt
->dataOnly
)
12665 /* Cannot dump if we don't have the transform functions' info */
12666 if (OidIsValid(transform
->trffromsql
))
12668 fromsqlFuncInfo
= findFuncByOid(transform
->trffromsql
);
12669 if (fromsqlFuncInfo
== NULL
)
12670 fatal("could not find function definition for function with OID %u",
12671 transform
->trffromsql
);
12673 if (OidIsValid(transform
->trftosql
))
12675 tosqlFuncInfo
= findFuncByOid(transform
->trftosql
);
12676 if (tosqlFuncInfo
== NULL
)
12677 fatal("could not find function definition for function with OID %u",
12678 transform
->trftosql
);
12681 defqry
= createPQExpBuffer();
12682 delqry
= createPQExpBuffer();
12683 labelq
= createPQExpBuffer();
12684 transformargs
= createPQExpBuffer();
12686 lanname
= get_language_name(fout
, transform
->trflang
);
12687 transformType
= getFormattedTypeName(fout
, transform
->trftype
, zeroAsNone
);
12689 appendPQExpBuffer(delqry
, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12690 transformType
, lanname
);
12692 appendPQExpBuffer(defqry
, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12693 transformType
, lanname
);
12695 if (!transform
->trffromsql
&& !transform
->trftosql
)
12696 pg_log_warning("bogus transform definition, at least one of trffromsql and trftosql should be nonzero");
12698 if (transform
->trffromsql
)
12700 if (fromsqlFuncInfo
)
12702 char *fsig
= format_function_signature(fout
, fromsqlFuncInfo
, true);
12705 * Always qualify the function name (format_function_signature
12706 * won't qualify it).
12708 appendPQExpBuffer(defqry
, "FROM SQL WITH FUNCTION %s.%s",
12709 fmtId(fromsqlFuncInfo
->dobj
.namespace->dobj
.name
), fsig
);
12713 pg_log_warning("bogus value in pg_transform.trffromsql field");
12716 if (transform
->trftosql
)
12718 if (transform
->trffromsql
)
12719 appendPQExpBuffer(defqry
, ", ");
12723 char *fsig
= format_function_signature(fout
, tosqlFuncInfo
, true);
12726 * Always qualify the function name (format_function_signature
12727 * won't qualify it).
12729 appendPQExpBuffer(defqry
, "TO SQL WITH FUNCTION %s.%s",
12730 fmtId(tosqlFuncInfo
->dobj
.namespace->dobj
.name
), fsig
);
12734 pg_log_warning("bogus value in pg_transform.trftosql field");
12737 appendPQExpBuffer(defqry
, ");\n");
12739 appendPQExpBuffer(labelq
, "TRANSFORM FOR %s LANGUAGE %s",
12740 transformType
, lanname
);
12742 appendPQExpBuffer(transformargs
, "FOR %s LANGUAGE %s",
12743 transformType
, lanname
);
12745 if (dopt
->binary_upgrade
)
12746 binary_upgrade_extension_member(defqry
, &transform
->dobj
,
12747 "TRANSFORM", transformargs
->data
, NULL
);
12749 if (transform
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
12750 ArchiveEntry(fout
, transform
->dobj
.catId
, transform
->dobj
.dumpId
,
12751 ARCHIVE_OPTS(.tag
= labelq
->data
,
12752 .description
= "TRANSFORM",
12753 .section
= SECTION_PRE_DATA
,
12754 .createStmt
= defqry
->data
,
12755 .dropStmt
= delqry
->data
,
12756 .deps
= transform
->dobj
.dependencies
,
12757 .nDeps
= transform
->dobj
.nDeps
));
12759 /* Dump Transform Comments */
12760 if (transform
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
12761 dumpComment(fout
, "TRANSFORM", transformargs
->data
,
12763 transform
->dobj
.catId
, 0, transform
->dobj
.dumpId
);
12766 destroyPQExpBuffer(defqry
);
12767 destroyPQExpBuffer(delqry
);
12768 destroyPQExpBuffer(labelq
);
12769 destroyPQExpBuffer(transformargs
);
12775 * write out a single operator definition
12778 dumpOpr(Archive
*fout
, OprInfo
*oprinfo
)
12780 DumpOptions
*dopt
= fout
->dopt
;
12785 PQExpBuffer details
;
12810 /* Skip if not to be dumped */
12811 if (!oprinfo
->dobj
.dump
|| dopt
->dataOnly
)
12815 * some operators are invalid because they were the result of user
12816 * defining operators before commutators exist
12818 if (!OidIsValid(oprinfo
->oprcode
))
12821 query
= createPQExpBuffer();
12822 q
= createPQExpBuffer();
12823 delq
= createPQExpBuffer();
12824 oprid
= createPQExpBuffer();
12825 details
= createPQExpBuffer();
12827 if (fout
->remoteVersion
>= 80300)
12829 appendPQExpBuffer(query
, "SELECT oprkind, "
12830 "oprcode::pg_catalog.regprocedure, "
12831 "oprleft::pg_catalog.regtype, "
12832 "oprright::pg_catalog.regtype, "
12835 "oprrest::pg_catalog.regprocedure, "
12836 "oprjoin::pg_catalog.regprocedure, "
12837 "oprcanmerge, oprcanhash "
12838 "FROM pg_catalog.pg_operator "
12839 "WHERE oid = '%u'::pg_catalog.oid",
12840 oprinfo
->dobj
.catId
.oid
);
12844 appendPQExpBuffer(query
, "SELECT oprkind, "
12845 "oprcode::pg_catalog.regprocedure, "
12846 "oprleft::pg_catalog.regtype, "
12847 "oprright::pg_catalog.regtype, "
12850 "oprrest::pg_catalog.regprocedure, "
12851 "oprjoin::pg_catalog.regprocedure, "
12852 "(oprlsortop != 0) AS oprcanmerge, "
12854 "FROM pg_catalog.pg_operator "
12855 "WHERE oid = '%u'::pg_catalog.oid",
12856 oprinfo
->dobj
.catId
.oid
);
12859 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
12861 i_oprkind
= PQfnumber(res
, "oprkind");
12862 i_oprcode
= PQfnumber(res
, "oprcode");
12863 i_oprleft
= PQfnumber(res
, "oprleft");
12864 i_oprright
= PQfnumber(res
, "oprright");
12865 i_oprcom
= PQfnumber(res
, "oprcom");
12866 i_oprnegate
= PQfnumber(res
, "oprnegate");
12867 i_oprrest
= PQfnumber(res
, "oprrest");
12868 i_oprjoin
= PQfnumber(res
, "oprjoin");
12869 i_oprcanmerge
= PQfnumber(res
, "oprcanmerge");
12870 i_oprcanhash
= PQfnumber(res
, "oprcanhash");
12872 oprkind
= PQgetvalue(res
, 0, i_oprkind
);
12873 oprcode
= PQgetvalue(res
, 0, i_oprcode
);
12874 oprleft
= PQgetvalue(res
, 0, i_oprleft
);
12875 oprright
= PQgetvalue(res
, 0, i_oprright
);
12876 oprcom
= PQgetvalue(res
, 0, i_oprcom
);
12877 oprnegate
= PQgetvalue(res
, 0, i_oprnegate
);
12878 oprrest
= PQgetvalue(res
, 0, i_oprrest
);
12879 oprjoin
= PQgetvalue(res
, 0, i_oprjoin
);
12880 oprcanmerge
= PQgetvalue(res
, 0, i_oprcanmerge
);
12881 oprcanhash
= PQgetvalue(res
, 0, i_oprcanhash
);
12883 oprregproc
= convertRegProcReference(fout
, oprcode
);
12886 appendPQExpBuffer(details
, " FUNCTION = %s", oprregproc
);
12890 appendPQExpBuffer(oprid
, "%s (",
12891 oprinfo
->dobj
.name
);
12894 * right unary means there's a left arg and left unary means there's a
12897 if (strcmp(oprkind
, "r") == 0 ||
12898 strcmp(oprkind
, "b") == 0)
12900 appendPQExpBuffer(details
, ",\n LEFTARG = %s", oprleft
);
12901 appendPQExpBufferStr(oprid
, oprleft
);
12904 appendPQExpBufferStr(oprid
, "NONE");
12906 if (strcmp(oprkind
, "l") == 0 ||
12907 strcmp(oprkind
, "b") == 0)
12909 appendPQExpBuffer(details
, ",\n RIGHTARG = %s", oprright
);
12910 appendPQExpBuffer(oprid
, ", %s)", oprright
);
12913 appendPQExpBufferStr(oprid
, ", NONE)");
12915 oprref
= getFormattedOperatorName(fout
, oprcom
);
12918 appendPQExpBuffer(details
, ",\n COMMUTATOR = %s", oprref
);
12922 oprref
= getFormattedOperatorName(fout
, oprnegate
);
12925 appendPQExpBuffer(details
, ",\n NEGATOR = %s", oprref
);
12929 if (strcmp(oprcanmerge
, "t") == 0)
12930 appendPQExpBufferStr(details
, ",\n MERGES");
12932 if (strcmp(oprcanhash
, "t") == 0)
12933 appendPQExpBufferStr(details
, ",\n HASHES");
12935 oprregproc
= convertRegProcReference(fout
, oprrest
);
12938 appendPQExpBuffer(details
, ",\n RESTRICT = %s", oprregproc
);
12942 oprregproc
= convertRegProcReference(fout
, oprjoin
);
12945 appendPQExpBuffer(details
, ",\n JOIN = %s", oprregproc
);
12949 appendPQExpBuffer(delq
, "DROP OPERATOR %s.%s;\n",
12950 fmtId(oprinfo
->dobj
.namespace->dobj
.name
),
12953 appendPQExpBuffer(q
, "CREATE OPERATOR %s.%s (\n%s\n);\n",
12954 fmtId(oprinfo
->dobj
.namespace->dobj
.name
),
12955 oprinfo
->dobj
.name
, details
->data
);
12957 if (dopt
->binary_upgrade
)
12958 binary_upgrade_extension_member(q
, &oprinfo
->dobj
,
12959 "OPERATOR", oprid
->data
,
12960 oprinfo
->dobj
.namespace->dobj
.name
);
12962 if (oprinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
12963 ArchiveEntry(fout
, oprinfo
->dobj
.catId
, oprinfo
->dobj
.dumpId
,
12964 ARCHIVE_OPTS(.tag
= oprinfo
->dobj
.name
,
12965 .namespace = oprinfo
->dobj
.namespace->dobj
.name
,
12966 .owner
= oprinfo
->rolname
,
12967 .description
= "OPERATOR",
12968 .section
= SECTION_PRE_DATA
,
12969 .createStmt
= q
->data
,
12970 .dropStmt
= delq
->data
));
12972 /* Dump Operator Comments */
12973 if (oprinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
12974 dumpComment(fout
, "OPERATOR", oprid
->data
,
12975 oprinfo
->dobj
.namespace->dobj
.name
, oprinfo
->rolname
,
12976 oprinfo
->dobj
.catId
, 0, oprinfo
->dobj
.dumpId
);
12980 destroyPQExpBuffer(query
);
12981 destroyPQExpBuffer(q
);
12982 destroyPQExpBuffer(delq
);
12983 destroyPQExpBuffer(oprid
);
12984 destroyPQExpBuffer(details
);
12988 * Convert a function reference obtained from pg_operator
12990 * Returns allocated string of what to print, or NULL if function references
12991 * is InvalidOid. Returned string is expected to be free'd by the caller.
12993 * The input is a REGPROCEDURE display; we have to strip the argument-types
12997 convertRegProcReference(Archive
*fout
, const char *proc
)
13003 /* In all cases "-" means a null reference */
13004 if (strcmp(proc
, "-") == 0)
13007 name
= pg_strdup(proc
);
13008 /* find non-double-quoted left paren */
13010 for (paren
= name
; *paren
; paren
++)
13012 if (*paren
== '(' && !inquote
)
13018 inquote
= !inquote
;
13024 * getFormattedOperatorName - retrieve the operator name for the
13025 * given operator OID (presented in string form).
13027 * Returns an allocated string, or NULL if the given OID is invalid.
13028 * Caller is responsible for free'ing result string.
13030 * What we produce has the format "OPERATOR(schema.oprname)". This is only
13031 * useful in commands where the operator's argument types can be inferred from
13032 * context. We always schema-qualify the name, though. The predecessor to
13033 * this code tried to skip the schema qualification if possible, but that led
13034 * to wrong results in corner cases, such as if an operator and its negator
13035 * are in different schemas.
13038 getFormattedOperatorName(Archive
*fout
, const char *oproid
)
13042 /* In all cases "0" means a null reference */
13043 if (strcmp(oproid
, "0") == 0)
13046 oprInfo
= findOprByOid(atooid(oproid
));
13047 if (oprInfo
== NULL
)
13049 pg_log_warning("could not find operator with OID %s",
13054 return psprintf("OPERATOR(%s.%s)",
13055 fmtId(oprInfo
->dobj
.namespace->dobj
.name
),
13056 oprInfo
->dobj
.name
);
13060 * Convert a function OID obtained from pg_ts_parser or pg_ts_template
13062 * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
13063 * argument lists of these functions are predetermined. Note that the
13064 * caller should ensure we are in the proper schema, because the results
13065 * are search path dependent!
13068 convertTSFunction(Archive
*fout
, Oid funcOid
)
13074 snprintf(query
, sizeof(query
),
13075 "SELECT '%u'::pg_catalog.regproc", funcOid
);
13076 res
= ExecuteSqlQueryForSingleRow(fout
, query
);
13078 result
= pg_strdup(PQgetvalue(res
, 0, 0));
13087 * write out a single access method definition
13090 dumpAccessMethod(Archive
*fout
, AccessMethodInfo
*aminfo
)
13092 DumpOptions
*dopt
= fout
->dopt
;
13097 /* Skip if not to be dumped */
13098 if (!aminfo
->dobj
.dump
|| dopt
->dataOnly
)
13101 q
= createPQExpBuffer();
13102 delq
= createPQExpBuffer();
13104 qamname
= pg_strdup(fmtId(aminfo
->dobj
.name
));
13106 appendPQExpBuffer(q
, "CREATE ACCESS METHOD %s ", qamname
);
13108 switch (aminfo
->amtype
)
13111 appendPQExpBuffer(q
, "TYPE INDEX ");
13114 appendPQExpBuffer(q
, "TYPE TABLE ");
13117 pg_log_warning("invalid type \"%c\" of access method \"%s\"",
13118 aminfo
->amtype
, qamname
);
13119 destroyPQExpBuffer(q
);
13120 destroyPQExpBuffer(delq
);
13125 appendPQExpBuffer(q
, "HANDLER %s;\n", aminfo
->amhandler
);
13127 appendPQExpBuffer(delq
, "DROP ACCESS METHOD %s;\n",
13130 if (dopt
->binary_upgrade
)
13131 binary_upgrade_extension_member(q
, &aminfo
->dobj
,
13132 "ACCESS METHOD", qamname
, NULL
);
13134 if (aminfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
13135 ArchiveEntry(fout
, aminfo
->dobj
.catId
, aminfo
->dobj
.dumpId
,
13136 ARCHIVE_OPTS(.tag
= aminfo
->dobj
.name
,
13137 .description
= "ACCESS METHOD",
13138 .section
= SECTION_PRE_DATA
,
13139 .createStmt
= q
->data
,
13140 .dropStmt
= delq
->data
));
13142 /* Dump Access Method Comments */
13143 if (aminfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
13144 dumpComment(fout
, "ACCESS METHOD", qamname
,
13146 aminfo
->dobj
.catId
, 0, aminfo
->dobj
.dumpId
);
13148 destroyPQExpBuffer(q
);
13149 destroyPQExpBuffer(delq
);
13155 * write out a single operator class definition
13158 dumpOpclass(Archive
*fout
, OpclassInfo
*opcinfo
)
13160 DumpOptions
*dopt
= fout
->dopt
;
13164 PQExpBuffer nameusing
;
13171 int i_opcfamilyname
;
13172 int i_opcfamilynsp
;
13174 int i_amopstrategy
;
13175 int i_amopreqcheck
;
13178 int i_sortfamilynsp
;
13181 int i_amproclefttype
;
13182 int i_amprocrighttype
;
13187 char *opcfamilyname
;
13188 char *opcfamilynsp
;
13190 char *amopstrategy
;
13191 char *amopreqcheck
;
13194 char *sortfamilynsp
;
13197 char *amproclefttype
;
13198 char *amprocrighttype
;
13202 /* Skip if not to be dumped */
13203 if (!opcinfo
->dobj
.dump
|| dopt
->dataOnly
)
13206 query
= createPQExpBuffer();
13207 q
= createPQExpBuffer();
13208 delq
= createPQExpBuffer();
13209 nameusing
= createPQExpBuffer();
13211 /* Get additional fields from the pg_opclass row */
13212 if (fout
->remoteVersion
>= 80300)
13214 appendPQExpBuffer(query
, "SELECT opcintype::pg_catalog.regtype, "
13215 "opckeytype::pg_catalog.regtype, "
13216 "opcdefault, opcfamily, "
13217 "opfname AS opcfamilyname, "
13218 "nspname AS opcfamilynsp, "
13219 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
13220 "FROM pg_catalog.pg_opclass c "
13221 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
13222 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13223 "WHERE c.oid = '%u'::pg_catalog.oid",
13224 opcinfo
->dobj
.catId
.oid
);
13228 appendPQExpBuffer(query
, "SELECT opcintype::pg_catalog.regtype, "
13229 "opckeytype::pg_catalog.regtype, "
13230 "opcdefault, NULL AS opcfamily, "
13231 "NULL AS opcfamilyname, "
13232 "NULL AS opcfamilynsp, "
13233 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcamid) AS amname "
13234 "FROM pg_catalog.pg_opclass "
13235 "WHERE oid = '%u'::pg_catalog.oid",
13236 opcinfo
->dobj
.catId
.oid
);
13239 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
13241 i_opcintype
= PQfnumber(res
, "opcintype");
13242 i_opckeytype
= PQfnumber(res
, "opckeytype");
13243 i_opcdefault
= PQfnumber(res
, "opcdefault");
13244 i_opcfamily
= PQfnumber(res
, "opcfamily");
13245 i_opcfamilyname
= PQfnumber(res
, "opcfamilyname");
13246 i_opcfamilynsp
= PQfnumber(res
, "opcfamilynsp");
13247 i_amname
= PQfnumber(res
, "amname");
13249 /* opcintype may still be needed after we PQclear res */
13250 opcintype
= pg_strdup(PQgetvalue(res
, 0, i_opcintype
));
13251 opckeytype
= PQgetvalue(res
, 0, i_opckeytype
);
13252 opcdefault
= PQgetvalue(res
, 0, i_opcdefault
);
13253 /* opcfamily will still be needed after we PQclear res */
13254 opcfamily
= pg_strdup(PQgetvalue(res
, 0, i_opcfamily
));
13255 opcfamilyname
= PQgetvalue(res
, 0, i_opcfamilyname
);
13256 opcfamilynsp
= PQgetvalue(res
, 0, i_opcfamilynsp
);
13257 /* amname will still be needed after we PQclear res */
13258 amname
= pg_strdup(PQgetvalue(res
, 0, i_amname
));
13260 appendPQExpBuffer(delq
, "DROP OPERATOR CLASS %s",
13261 fmtQualifiedDumpable(opcinfo
));
13262 appendPQExpBuffer(delq
, " USING %s;\n",
13265 /* Build the fixed portion of the CREATE command */
13266 appendPQExpBuffer(q
, "CREATE OPERATOR CLASS %s\n ",
13267 fmtQualifiedDumpable(opcinfo
));
13268 if (strcmp(opcdefault
, "t") == 0)
13269 appendPQExpBufferStr(q
, "DEFAULT ");
13270 appendPQExpBuffer(q
, "FOR TYPE %s USING %s",
13273 if (strlen(opcfamilyname
) > 0)
13275 appendPQExpBufferStr(q
, " FAMILY ");
13276 appendPQExpBuffer(q
, "%s.", fmtId(opcfamilynsp
));
13277 appendPQExpBufferStr(q
, fmtId(opcfamilyname
));
13279 appendPQExpBufferStr(q
, " AS\n ");
13283 if (strcmp(opckeytype
, "-") != 0)
13285 appendPQExpBuffer(q
, "STORAGE %s",
13293 * Now fetch and print the OPERATOR entries (pg_amop rows).
13295 * Print only those opfamily members that are tied to the opclass by
13296 * pg_depend entries.
13298 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13299 * older server's opclass in which it is used. This is to avoid
13300 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13301 * older server and then reload into that old version. This can go away
13302 * once 8.3 is so old as to not be of interest to anyone.
13304 resetPQExpBuffer(query
);
13306 if (fout
->remoteVersion
>= 90100)
13308 appendPQExpBuffer(query
, "SELECT amopstrategy, false AS amopreqcheck, "
13309 "amopopr::pg_catalog.regoperator, "
13310 "opfname AS sortfamily, "
13311 "nspname AS sortfamilynsp "
13312 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13313 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13314 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13315 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13316 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13317 "AND refobjid = '%u'::pg_catalog.oid "
13318 "AND amopfamily = '%s'::pg_catalog.oid "
13319 "ORDER BY amopstrategy",
13320 opcinfo
->dobj
.catId
.oid
,
13323 else if (fout
->remoteVersion
>= 80400)
13325 appendPQExpBuffer(query
, "SELECT amopstrategy, false AS amopreqcheck, "
13326 "amopopr::pg_catalog.regoperator, "
13327 "NULL AS sortfamily, "
13328 "NULL AS sortfamilynsp "
13329 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13330 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13331 "AND refobjid = '%u'::pg_catalog.oid "
13332 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13333 "AND objid = ao.oid "
13334 "ORDER BY amopstrategy",
13335 opcinfo
->dobj
.catId
.oid
);
13337 else if (fout
->remoteVersion
>= 80300)
13339 appendPQExpBuffer(query
, "SELECT amopstrategy, amopreqcheck, "
13340 "amopopr::pg_catalog.regoperator, "
13341 "NULL AS sortfamily, "
13342 "NULL AS sortfamilynsp "
13343 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13344 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13345 "AND refobjid = '%u'::pg_catalog.oid "
13346 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13347 "AND objid = ao.oid "
13348 "ORDER BY amopstrategy",
13349 opcinfo
->dobj
.catId
.oid
);
13354 * Here, we print all entries since there are no opfamilies and hence
13355 * no loose operators to worry about.
13357 appendPQExpBuffer(query
, "SELECT amopstrategy, amopreqcheck, "
13358 "amopopr::pg_catalog.regoperator, "
13359 "NULL AS sortfamily, "
13360 "NULL AS sortfamilynsp "
13361 "FROM pg_catalog.pg_amop "
13362 "WHERE amopclaid = '%u'::pg_catalog.oid "
13363 "ORDER BY amopstrategy",
13364 opcinfo
->dobj
.catId
.oid
);
13367 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
13369 ntups
= PQntuples(res
);
13371 i_amopstrategy
= PQfnumber(res
, "amopstrategy");
13372 i_amopreqcheck
= PQfnumber(res
, "amopreqcheck");
13373 i_amopopr
= PQfnumber(res
, "amopopr");
13374 i_sortfamily
= PQfnumber(res
, "sortfamily");
13375 i_sortfamilynsp
= PQfnumber(res
, "sortfamilynsp");
13377 for (i
= 0; i
< ntups
; i
++)
13379 amopstrategy
= PQgetvalue(res
, i
, i_amopstrategy
);
13380 amopreqcheck
= PQgetvalue(res
, i
, i_amopreqcheck
);
13381 amopopr
= PQgetvalue(res
, i
, i_amopopr
);
13382 sortfamily
= PQgetvalue(res
, i
, i_sortfamily
);
13383 sortfamilynsp
= PQgetvalue(res
, i
, i_sortfamilynsp
);
13386 appendPQExpBufferStr(q
, " ,\n ");
13388 appendPQExpBuffer(q
, "OPERATOR %s %s",
13389 amopstrategy
, amopopr
);
13391 if (strlen(sortfamily
) > 0)
13393 appendPQExpBufferStr(q
, " FOR ORDER BY ");
13394 appendPQExpBuffer(q
, "%s.", fmtId(sortfamilynsp
));
13395 appendPQExpBufferStr(q
, fmtId(sortfamily
));
13398 if (strcmp(amopreqcheck
, "t") == 0)
13399 appendPQExpBufferStr(q
, " RECHECK");
13407 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13409 * Print only those opfamily members that are tied to the opclass by
13410 * pg_depend entries.
13412 * We print the amproclefttype/amprocrighttype even though in most cases
13413 * the backend could deduce the right values, because of the corner case
13414 * of a btree sort support function for a cross-type comparison. That's
13415 * only allowed in 9.2 and later, but for simplicity print them in all
13416 * versions that have the columns.
13418 resetPQExpBuffer(query
);
13420 if (fout
->remoteVersion
>= 80300)
13422 appendPQExpBuffer(query
, "SELECT amprocnum, "
13423 "amproc::pg_catalog.regprocedure, "
13424 "amproclefttype::pg_catalog.regtype, "
13425 "amprocrighttype::pg_catalog.regtype "
13426 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13427 "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13428 "AND refobjid = '%u'::pg_catalog.oid "
13429 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13430 "AND objid = ap.oid "
13431 "ORDER BY amprocnum",
13432 opcinfo
->dobj
.catId
.oid
);
13436 appendPQExpBuffer(query
, "SELECT amprocnum, "
13437 "amproc::pg_catalog.regprocedure, "
13438 "'' AS amproclefttype, "
13439 "'' AS amprocrighttype "
13440 "FROM pg_catalog.pg_amproc "
13441 "WHERE amopclaid = '%u'::pg_catalog.oid "
13442 "ORDER BY amprocnum",
13443 opcinfo
->dobj
.catId
.oid
);
13446 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
13448 ntups
= PQntuples(res
);
13450 i_amprocnum
= PQfnumber(res
, "amprocnum");
13451 i_amproc
= PQfnumber(res
, "amproc");
13452 i_amproclefttype
= PQfnumber(res
, "amproclefttype");
13453 i_amprocrighttype
= PQfnumber(res
, "amprocrighttype");
13455 for (i
= 0; i
< ntups
; i
++)
13457 amprocnum
= PQgetvalue(res
, i
, i_amprocnum
);
13458 amproc
= PQgetvalue(res
, i
, i_amproc
);
13459 amproclefttype
= PQgetvalue(res
, i
, i_amproclefttype
);
13460 amprocrighttype
= PQgetvalue(res
, i
, i_amprocrighttype
);
13463 appendPQExpBufferStr(q
, " ,\n ");
13465 appendPQExpBuffer(q
, "FUNCTION %s", amprocnum
);
13467 if (*amproclefttype
&& *amprocrighttype
)
13468 appendPQExpBuffer(q
, " (%s, %s)", amproclefttype
, amprocrighttype
);
13470 appendPQExpBuffer(q
, " %s", amproc
);
13478 * If needComma is still false it means we haven't added anything after
13479 * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13480 * clause with the same datatype. This isn't sanctioned by the
13481 * documentation, but actually DefineOpClass will treat it as a no-op.
13484 appendPQExpBuffer(q
, "STORAGE %s", opcintype
);
13486 appendPQExpBufferStr(q
, ";\n");
13488 appendPQExpBufferStr(nameusing
, fmtId(opcinfo
->dobj
.name
));
13489 appendPQExpBuffer(nameusing
, " USING %s",
13492 if (dopt
->binary_upgrade
)
13493 binary_upgrade_extension_member(q
, &opcinfo
->dobj
,
13494 "OPERATOR CLASS", nameusing
->data
,
13495 opcinfo
->dobj
.namespace->dobj
.name
);
13497 if (opcinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
13498 ArchiveEntry(fout
, opcinfo
->dobj
.catId
, opcinfo
->dobj
.dumpId
,
13499 ARCHIVE_OPTS(.tag
= opcinfo
->dobj
.name
,
13500 .namespace = opcinfo
->dobj
.namespace->dobj
.name
,
13501 .owner
= opcinfo
->rolname
,
13502 .description
= "OPERATOR CLASS",
13503 .section
= SECTION_PRE_DATA
,
13504 .createStmt
= q
->data
,
13505 .dropStmt
= delq
->data
));
13507 /* Dump Operator Class Comments */
13508 if (opcinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
13509 dumpComment(fout
, "OPERATOR CLASS", nameusing
->data
,
13510 opcinfo
->dobj
.namespace->dobj
.name
, opcinfo
->rolname
,
13511 opcinfo
->dobj
.catId
, 0, opcinfo
->dobj
.dumpId
);
13516 destroyPQExpBuffer(query
);
13517 destroyPQExpBuffer(q
);
13518 destroyPQExpBuffer(delq
);
13519 destroyPQExpBuffer(nameusing
);
13524 * write out a single operator family definition
13526 * Note: this also dumps any "loose" operator members that aren't bound to a
13527 * specific opclass within the opfamily.
13530 dumpOpfamily(Archive
*fout
, OpfamilyInfo
*opfinfo
)
13532 DumpOptions
*dopt
= fout
->dopt
;
13536 PQExpBuffer nameusing
;
13539 PGresult
*res_procs
;
13542 int i_amopstrategy
;
13543 int i_amopreqcheck
;
13546 int i_sortfamilynsp
;
13549 int i_amproclefttype
;
13550 int i_amprocrighttype
;
13552 char *amopstrategy
;
13553 char *amopreqcheck
;
13556 char *sortfamilynsp
;
13559 char *amproclefttype
;
13560 char *amprocrighttype
;
13564 /* Skip if not to be dumped */
13565 if (!opfinfo
->dobj
.dump
|| dopt
->dataOnly
)
13568 query
= createPQExpBuffer();
13569 q
= createPQExpBuffer();
13570 delq
= createPQExpBuffer();
13571 nameusing
= createPQExpBuffer();
13574 * Fetch only those opfamily members that are tied directly to the
13575 * opfamily by pg_depend entries.
13577 * XXX RECHECK is gone as of 8.4, but we'll still print it if dumping an
13578 * older server's opclass in which it is used. This is to avoid
13579 * hard-to-detect breakage if a newer pg_dump is used to dump from an
13580 * older server and then reload into that old version. This can go away
13581 * once 8.3 is so old as to not be of interest to anyone.
13583 if (fout
->remoteVersion
>= 90100)
13585 appendPQExpBuffer(query
, "SELECT amopstrategy, false AS amopreqcheck, "
13586 "amopopr::pg_catalog.regoperator, "
13587 "opfname AS sortfamily, "
13588 "nspname AS sortfamilynsp "
13589 "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13590 "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13591 "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13592 "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13593 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13594 "AND refobjid = '%u'::pg_catalog.oid "
13595 "AND amopfamily = '%u'::pg_catalog.oid "
13596 "ORDER BY amopstrategy",
13597 opfinfo
->dobj
.catId
.oid
,
13598 opfinfo
->dobj
.catId
.oid
);
13600 else if (fout
->remoteVersion
>= 80400)
13602 appendPQExpBuffer(query
, "SELECT amopstrategy, false AS amopreqcheck, "
13603 "amopopr::pg_catalog.regoperator, "
13604 "NULL AS sortfamily, "
13605 "NULL AS sortfamilynsp "
13606 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13607 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13608 "AND refobjid = '%u'::pg_catalog.oid "
13609 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13610 "AND objid = ao.oid "
13611 "ORDER BY amopstrategy",
13612 opfinfo
->dobj
.catId
.oid
);
13616 appendPQExpBuffer(query
, "SELECT amopstrategy, amopreqcheck, "
13617 "amopopr::pg_catalog.regoperator, "
13618 "NULL AS sortfamily, "
13619 "NULL AS sortfamilynsp "
13620 "FROM pg_catalog.pg_amop ao, pg_catalog.pg_depend "
13621 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13622 "AND refobjid = '%u'::pg_catalog.oid "
13623 "AND classid = 'pg_catalog.pg_amop'::pg_catalog.regclass "
13624 "AND objid = ao.oid "
13625 "ORDER BY amopstrategy",
13626 opfinfo
->dobj
.catId
.oid
);
13629 res_ops
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
13631 resetPQExpBuffer(query
);
13633 appendPQExpBuffer(query
, "SELECT amprocnum, "
13634 "amproc::pg_catalog.regprocedure, "
13635 "amproclefttype::pg_catalog.regtype, "
13636 "amprocrighttype::pg_catalog.regtype "
13637 "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13638 "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13639 "AND refobjid = '%u'::pg_catalog.oid "
13640 "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13641 "AND objid = ap.oid "
13642 "ORDER BY amprocnum",
13643 opfinfo
->dobj
.catId
.oid
);
13645 res_procs
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
13647 /* Get additional fields from the pg_opfamily row */
13648 resetPQExpBuffer(query
);
13650 appendPQExpBuffer(query
, "SELECT "
13651 "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13652 "FROM pg_catalog.pg_opfamily "
13653 "WHERE oid = '%u'::pg_catalog.oid",
13654 opfinfo
->dobj
.catId
.oid
);
13656 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
13658 i_amname
= PQfnumber(res
, "amname");
13660 /* amname will still be needed after we PQclear res */
13661 amname
= pg_strdup(PQgetvalue(res
, 0, i_amname
));
13663 appendPQExpBuffer(delq
, "DROP OPERATOR FAMILY %s",
13664 fmtQualifiedDumpable(opfinfo
));
13665 appendPQExpBuffer(delq
, " USING %s;\n",
13668 /* Build the fixed portion of the CREATE command */
13669 appendPQExpBuffer(q
, "CREATE OPERATOR FAMILY %s",
13670 fmtQualifiedDumpable(opfinfo
));
13671 appendPQExpBuffer(q
, " USING %s;\n",
13676 /* Do we need an ALTER to add loose members? */
13677 if (PQntuples(res_ops
) > 0 || PQntuples(res_procs
) > 0)
13679 appendPQExpBuffer(q
, "ALTER OPERATOR FAMILY %s",
13680 fmtQualifiedDumpable(opfinfo
));
13681 appendPQExpBuffer(q
, " USING %s ADD\n ",
13687 * Now fetch and print the OPERATOR entries (pg_amop rows).
13689 ntups
= PQntuples(res_ops
);
13691 i_amopstrategy
= PQfnumber(res_ops
, "amopstrategy");
13692 i_amopreqcheck
= PQfnumber(res_ops
, "amopreqcheck");
13693 i_amopopr
= PQfnumber(res_ops
, "amopopr");
13694 i_sortfamily
= PQfnumber(res_ops
, "sortfamily");
13695 i_sortfamilynsp
= PQfnumber(res_ops
, "sortfamilynsp");
13697 for (i
= 0; i
< ntups
; i
++)
13699 amopstrategy
= PQgetvalue(res_ops
, i
, i_amopstrategy
);
13700 amopreqcheck
= PQgetvalue(res_ops
, i
, i_amopreqcheck
);
13701 amopopr
= PQgetvalue(res_ops
, i
, i_amopopr
);
13702 sortfamily
= PQgetvalue(res_ops
, i
, i_sortfamily
);
13703 sortfamilynsp
= PQgetvalue(res_ops
, i
, i_sortfamilynsp
);
13706 appendPQExpBufferStr(q
, " ,\n ");
13708 appendPQExpBuffer(q
, "OPERATOR %s %s",
13709 amopstrategy
, amopopr
);
13711 if (strlen(sortfamily
) > 0)
13713 appendPQExpBufferStr(q
, " FOR ORDER BY ");
13714 appendPQExpBuffer(q
, "%s.", fmtId(sortfamilynsp
));
13715 appendPQExpBufferStr(q
, fmtId(sortfamily
));
13718 if (strcmp(amopreqcheck
, "t") == 0)
13719 appendPQExpBufferStr(q
, " RECHECK");
13725 * Now fetch and print the FUNCTION entries (pg_amproc rows).
13727 ntups
= PQntuples(res_procs
);
13729 i_amprocnum
= PQfnumber(res_procs
, "amprocnum");
13730 i_amproc
= PQfnumber(res_procs
, "amproc");
13731 i_amproclefttype
= PQfnumber(res_procs
, "amproclefttype");
13732 i_amprocrighttype
= PQfnumber(res_procs
, "amprocrighttype");
13734 for (i
= 0; i
< ntups
; i
++)
13736 amprocnum
= PQgetvalue(res_procs
, i
, i_amprocnum
);
13737 amproc
= PQgetvalue(res_procs
, i
, i_amproc
);
13738 amproclefttype
= PQgetvalue(res_procs
, i
, i_amproclefttype
);
13739 amprocrighttype
= PQgetvalue(res_procs
, i
, i_amprocrighttype
);
13742 appendPQExpBufferStr(q
, " ,\n ");
13744 appendPQExpBuffer(q
, "FUNCTION %s (%s, %s) %s",
13745 amprocnum
, amproclefttype
, amprocrighttype
,
13751 appendPQExpBufferStr(q
, ";\n");
13754 appendPQExpBufferStr(nameusing
, fmtId(opfinfo
->dobj
.name
));
13755 appendPQExpBuffer(nameusing
, " USING %s",
13758 if (dopt
->binary_upgrade
)
13759 binary_upgrade_extension_member(q
, &opfinfo
->dobj
,
13760 "OPERATOR FAMILY", nameusing
->data
,
13761 opfinfo
->dobj
.namespace->dobj
.name
);
13763 if (opfinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
13764 ArchiveEntry(fout
, opfinfo
->dobj
.catId
, opfinfo
->dobj
.dumpId
,
13765 ARCHIVE_OPTS(.tag
= opfinfo
->dobj
.name
,
13766 .namespace = opfinfo
->dobj
.namespace->dobj
.name
,
13767 .owner
= opfinfo
->rolname
,
13768 .description
= "OPERATOR FAMILY",
13769 .section
= SECTION_PRE_DATA
,
13770 .createStmt
= q
->data
,
13771 .dropStmt
= delq
->data
));
13773 /* Dump Operator Family Comments */
13774 if (opfinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
13775 dumpComment(fout
, "OPERATOR FAMILY", nameusing
->data
,
13776 opfinfo
->dobj
.namespace->dobj
.name
, opfinfo
->rolname
,
13777 opfinfo
->dobj
.catId
, 0, opfinfo
->dobj
.dumpId
);
13781 PQclear(res_procs
);
13782 destroyPQExpBuffer(query
);
13783 destroyPQExpBuffer(q
);
13784 destroyPQExpBuffer(delq
);
13785 destroyPQExpBuffer(nameusing
);
13790 * write out a single collation definition
13793 dumpCollation(Archive
*fout
, CollInfo
*collinfo
)
13795 DumpOptions
*dopt
= fout
->dopt
;
13801 int i_collprovider
;
13802 int i_collisdeterministic
;
13805 const char *collprovider
;
13806 const char *collcollate
;
13807 const char *collctype
;
13809 /* Skip if not to be dumped */
13810 if (!collinfo
->dobj
.dump
|| dopt
->dataOnly
)
13813 query
= createPQExpBuffer();
13814 q
= createPQExpBuffer();
13815 delq
= createPQExpBuffer();
13817 qcollname
= pg_strdup(fmtId(collinfo
->dobj
.name
));
13819 /* Get collation-specific details */
13820 appendPQExpBuffer(query
, "SELECT ");
13822 if (fout
->remoteVersion
>= 100000)
13823 appendPQExpBuffer(query
,
13827 appendPQExpBuffer(query
,
13828 "'c' AS collprovider, "
13829 "NULL AS collversion, ");
13831 if (fout
->remoteVersion
>= 120000)
13832 appendPQExpBuffer(query
,
13833 "collisdeterministic, ");
13835 appendPQExpBuffer(query
,
13836 "true AS collisdeterministic, ");
13838 appendPQExpBuffer(query
,
13841 "FROM pg_catalog.pg_collation c "
13842 "WHERE c.oid = '%u'::pg_catalog.oid",
13843 collinfo
->dobj
.catId
.oid
);
13845 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
13847 i_collprovider
= PQfnumber(res
, "collprovider");
13848 i_collisdeterministic
= PQfnumber(res
, "collisdeterministic");
13849 i_collcollate
= PQfnumber(res
, "collcollate");
13850 i_collctype
= PQfnumber(res
, "collctype");
13852 collprovider
= PQgetvalue(res
, 0, i_collprovider
);
13853 collcollate
= PQgetvalue(res
, 0, i_collcollate
);
13854 collctype
= PQgetvalue(res
, 0, i_collctype
);
13856 appendPQExpBuffer(delq
, "DROP COLLATION %s;\n",
13857 fmtQualifiedDumpable(collinfo
));
13859 appendPQExpBuffer(q
, "CREATE COLLATION %s (",
13860 fmtQualifiedDumpable(collinfo
));
13862 appendPQExpBufferStr(q
, "provider = ");
13863 if (collprovider
[0] == 'c')
13864 appendPQExpBufferStr(q
, "libc");
13865 else if (collprovider
[0] == 'i')
13866 appendPQExpBufferStr(q
, "icu");
13867 else if (collprovider
[0] == 'd')
13868 /* to allow dumping pg_catalog; not accepted on input */
13869 appendPQExpBufferStr(q
, "default");
13871 fatal("unrecognized collation provider: %s",
13874 if (strcmp(PQgetvalue(res
, 0, i_collisdeterministic
), "f") == 0)
13875 appendPQExpBufferStr(q
, ", deterministic = false");
13877 if (strcmp(collcollate
, collctype
) == 0)
13879 appendPQExpBufferStr(q
, ", locale = ");
13880 appendStringLiteralAH(q
, collcollate
, fout
);
13884 appendPQExpBufferStr(q
, ", lc_collate = ");
13885 appendStringLiteralAH(q
, collcollate
, fout
);
13886 appendPQExpBufferStr(q
, ", lc_ctype = ");
13887 appendStringLiteralAH(q
, collctype
, fout
);
13891 * For binary upgrade, carry over the collation version. For normal
13892 * dump/restore, omit the version, so that it is computed upon restore.
13894 if (dopt
->binary_upgrade
)
13898 i_collversion
= PQfnumber(res
, "collversion");
13899 if (!PQgetisnull(res
, 0, i_collversion
))
13901 appendPQExpBufferStr(q
, ", version = ");
13902 appendStringLiteralAH(q
,
13903 PQgetvalue(res
, 0, i_collversion
),
13908 appendPQExpBufferStr(q
, ");\n");
13910 if (dopt
->binary_upgrade
)
13911 binary_upgrade_extension_member(q
, &collinfo
->dobj
,
13912 "COLLATION", qcollname
,
13913 collinfo
->dobj
.namespace->dobj
.name
);
13915 if (collinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
13916 ArchiveEntry(fout
, collinfo
->dobj
.catId
, collinfo
->dobj
.dumpId
,
13917 ARCHIVE_OPTS(.tag
= collinfo
->dobj
.name
,
13918 .namespace = collinfo
->dobj
.namespace->dobj
.name
,
13919 .owner
= collinfo
->rolname
,
13920 .description
= "COLLATION",
13921 .section
= SECTION_PRE_DATA
,
13922 .createStmt
= q
->data
,
13923 .dropStmt
= delq
->data
));
13925 /* Dump Collation Comments */
13926 if (collinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
13927 dumpComment(fout
, "COLLATION", qcollname
,
13928 collinfo
->dobj
.namespace->dobj
.name
, collinfo
->rolname
,
13929 collinfo
->dobj
.catId
, 0, collinfo
->dobj
.dumpId
);
13933 destroyPQExpBuffer(query
);
13934 destroyPQExpBuffer(q
);
13935 destroyPQExpBuffer(delq
);
13941 * write out a single conversion definition
13944 dumpConversion(Archive
*fout
, ConvInfo
*convinfo
)
13946 DumpOptions
*dopt
= fout
->dopt
;
13952 int i_conforencoding
;
13953 int i_contoencoding
;
13956 const char *conforencoding
;
13957 const char *contoencoding
;
13958 const char *conproc
;
13961 /* Skip if not to be dumped */
13962 if (!convinfo
->dobj
.dump
|| dopt
->dataOnly
)
13965 query
= createPQExpBuffer();
13966 q
= createPQExpBuffer();
13967 delq
= createPQExpBuffer();
13969 qconvname
= pg_strdup(fmtId(convinfo
->dobj
.name
));
13971 /* Get conversion-specific details */
13972 appendPQExpBuffer(query
, "SELECT "
13973 "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
13974 "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
13975 "conproc, condefault "
13976 "FROM pg_catalog.pg_conversion c "
13977 "WHERE c.oid = '%u'::pg_catalog.oid",
13978 convinfo
->dobj
.catId
.oid
);
13980 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
13982 i_conforencoding
= PQfnumber(res
, "conforencoding");
13983 i_contoencoding
= PQfnumber(res
, "contoencoding");
13984 i_conproc
= PQfnumber(res
, "conproc");
13985 i_condefault
= PQfnumber(res
, "condefault");
13987 conforencoding
= PQgetvalue(res
, 0, i_conforencoding
);
13988 contoencoding
= PQgetvalue(res
, 0, i_contoencoding
);
13989 conproc
= PQgetvalue(res
, 0, i_conproc
);
13990 condefault
= (PQgetvalue(res
, 0, i_condefault
)[0] == 't');
13992 appendPQExpBuffer(delq
, "DROP CONVERSION %s;\n",
13993 fmtQualifiedDumpable(convinfo
));
13995 appendPQExpBuffer(q
, "CREATE %sCONVERSION %s FOR ",
13996 (condefault
) ? "DEFAULT " : "",
13997 fmtQualifiedDumpable(convinfo
));
13998 appendStringLiteralAH(q
, conforencoding
, fout
);
13999 appendPQExpBufferStr(q
, " TO ");
14000 appendStringLiteralAH(q
, contoencoding
, fout
);
14001 /* regproc output is already sufficiently quoted */
14002 appendPQExpBuffer(q
, " FROM %s;\n", conproc
);
14004 if (dopt
->binary_upgrade
)
14005 binary_upgrade_extension_member(q
, &convinfo
->dobj
,
14006 "CONVERSION", qconvname
,
14007 convinfo
->dobj
.namespace->dobj
.name
);
14009 if (convinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14010 ArchiveEntry(fout
, convinfo
->dobj
.catId
, convinfo
->dobj
.dumpId
,
14011 ARCHIVE_OPTS(.tag
= convinfo
->dobj
.name
,
14012 .namespace = convinfo
->dobj
.namespace->dobj
.name
,
14013 .owner
= convinfo
->rolname
,
14014 .description
= "CONVERSION",
14015 .section
= SECTION_PRE_DATA
,
14016 .createStmt
= q
->data
,
14017 .dropStmt
= delq
->data
));
14019 /* Dump Conversion Comments */
14020 if (convinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14021 dumpComment(fout
, "CONVERSION", qconvname
,
14022 convinfo
->dobj
.namespace->dobj
.name
, convinfo
->rolname
,
14023 convinfo
->dobj
.catId
, 0, convinfo
->dobj
.dumpId
);
14027 destroyPQExpBuffer(query
);
14028 destroyPQExpBuffer(q
);
14029 destroyPQExpBuffer(delq
);
14034 * format_aggregate_signature: generate aggregate name and argument list
14036 * The argument type names are qualified if needed. The aggregate name
14037 * is never qualified.
14040 format_aggregate_signature(AggInfo
*agginfo
, Archive
*fout
, bool honor_quotes
)
14042 PQExpBufferData buf
;
14045 initPQExpBuffer(&buf
);
14047 appendPQExpBufferStr(&buf
, fmtId(agginfo
->aggfn
.dobj
.name
));
14049 appendPQExpBufferStr(&buf
, agginfo
->aggfn
.dobj
.name
);
14051 if (agginfo
->aggfn
.nargs
== 0)
14052 appendPQExpBuffer(&buf
, "(*)");
14055 appendPQExpBufferChar(&buf
, '(');
14056 for (j
= 0; j
< agginfo
->aggfn
.nargs
; j
++)
14057 appendPQExpBuffer(&buf
, "%s%s",
14058 (j
> 0) ? ", " : "",
14059 getFormattedTypeName(fout
,
14060 agginfo
->aggfn
.argtypes
[j
],
14062 appendPQExpBufferChar(&buf
, ')');
14069 * write out a single aggregate definition
14072 dumpAgg(Archive
*fout
, AggInfo
*agginfo
)
14074 DumpOptions
*dopt
= fout
->dopt
;
14078 PQExpBuffer details
;
14079 char *aggsig
; /* identity signature */
14080 char *aggfullsig
= NULL
; /* full signature */
14085 int i_aggcombinefn
;
14087 int i_aggdeserialfn
;
14089 int i_aggminvtransfn
;
14091 int i_aggfinalextra
;
14092 int i_aggmfinalextra
;
14093 int i_aggfinalmodify
;
14094 int i_aggmfinalmodify
;
14097 int i_aggtranstype
;
14098 int i_aggtransspace
;
14099 int i_aggmtranstype
;
14100 int i_aggmtransspace
;
14105 const char *aggtransfn
;
14106 const char *aggfinalfn
;
14107 const char *aggcombinefn
;
14108 const char *aggserialfn
;
14109 const char *aggdeserialfn
;
14110 const char *aggmtransfn
;
14111 const char *aggminvtransfn
;
14112 const char *aggmfinalfn
;
14113 bool aggfinalextra
;
14114 bool aggmfinalextra
;
14115 char aggfinalmodify
;
14116 char aggmfinalmodify
;
14117 const char *aggsortop
;
14118 char *aggsortconvop
;
14120 const char *aggtranstype
;
14121 const char *aggtransspace
;
14122 const char *aggmtranstype
;
14123 const char *aggmtransspace
;
14124 const char *agginitval
;
14125 const char *aggminitval
;
14127 const char *proparallel
;
14128 char defaultfinalmodify
;
14130 /* Skip if not to be dumped */
14131 if (!agginfo
->aggfn
.dobj
.dump
|| dopt
->dataOnly
)
14134 query
= createPQExpBuffer();
14135 q
= createPQExpBuffer();
14136 delq
= createPQExpBuffer();
14137 details
= createPQExpBuffer();
14139 /* Get aggregate-specific details */
14140 if (fout
->remoteVersion
>= 110000)
14142 appendPQExpBuffer(query
, "SELECT aggtransfn, "
14143 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14144 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
14145 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
14146 "aggfinalextra, aggmfinalextra, "
14147 "aggfinalmodify, aggmfinalmodify, "
14150 "aggtransspace, agginitval, "
14151 "aggmtransspace, aggminitval, "
14152 "true AS convertok, "
14153 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14154 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
14156 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14157 "WHERE a.aggfnoid = p.oid "
14158 "AND p.oid = '%u'::pg_catalog.oid",
14159 agginfo
->aggfn
.dobj
.catId
.oid
);
14161 else if (fout
->remoteVersion
>= 90600)
14163 appendPQExpBuffer(query
, "SELECT aggtransfn, "
14164 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14165 "aggcombinefn, aggserialfn, aggdeserialfn, aggmtransfn, "
14166 "aggminvtransfn, aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
14167 "aggfinalextra, aggmfinalextra, "
14168 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14171 "aggtransspace, agginitval, "
14172 "aggmtransspace, aggminitval, "
14173 "true AS convertok, "
14174 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14175 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs, "
14177 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14178 "WHERE a.aggfnoid = p.oid "
14179 "AND p.oid = '%u'::pg_catalog.oid",
14180 agginfo
->aggfn
.dobj
.catId
.oid
);
14182 else if (fout
->remoteVersion
>= 90400)
14184 appendPQExpBuffer(query
, "SELECT aggtransfn, "
14185 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14186 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14187 "'-' AS aggdeserialfn, aggmtransfn, aggminvtransfn, "
14188 "aggmfinalfn, aggmtranstype::pg_catalog.regtype, "
14189 "aggfinalextra, aggmfinalextra, "
14190 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14193 "aggtransspace, agginitval, "
14194 "aggmtransspace, aggminitval, "
14195 "true AS convertok, "
14196 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14197 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
14198 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14199 "WHERE a.aggfnoid = p.oid "
14200 "AND p.oid = '%u'::pg_catalog.oid",
14201 agginfo
->aggfn
.dobj
.catId
.oid
);
14203 else if (fout
->remoteVersion
>= 80400)
14205 appendPQExpBuffer(query
, "SELECT aggtransfn, "
14206 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14207 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14208 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
14209 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
14210 "0 AS aggmtranstype, false AS aggfinalextra, "
14211 "false AS aggmfinalextra, "
14212 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14215 "0 AS aggtransspace, agginitval, "
14216 "0 AS aggmtransspace, NULL AS aggminitval, "
14217 "true AS convertok, "
14218 "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs, "
14219 "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs "
14220 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14221 "WHERE a.aggfnoid = p.oid "
14222 "AND p.oid = '%u'::pg_catalog.oid",
14223 agginfo
->aggfn
.dobj
.catId
.oid
);
14225 else if (fout
->remoteVersion
>= 80100)
14227 appendPQExpBuffer(query
, "SELECT aggtransfn, "
14228 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14229 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14230 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
14231 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
14232 "0 AS aggmtranstype, false AS aggfinalextra, "
14233 "false AS aggmfinalextra, "
14234 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14237 "0 AS aggtransspace, agginitval, "
14238 "0 AS aggmtransspace, NULL AS aggminitval, "
14239 "true AS convertok "
14240 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14241 "WHERE a.aggfnoid = p.oid "
14242 "AND p.oid = '%u'::pg_catalog.oid",
14243 agginfo
->aggfn
.dobj
.catId
.oid
);
14247 appendPQExpBuffer(query
, "SELECT aggtransfn, "
14248 "aggfinalfn, aggtranstype::pg_catalog.regtype, "
14249 "'-' AS aggcombinefn, '-' AS aggserialfn, "
14250 "'-' AS aggdeserialfn, '-' AS aggmtransfn, "
14251 "'-' AS aggminvtransfn, '-' AS aggmfinalfn, "
14252 "0 AS aggmtranstype, false AS aggfinalextra, "
14253 "false AS aggmfinalextra, "
14254 "'0' AS aggfinalmodify, '0' AS aggmfinalmodify, "
14257 "0 AS aggtransspace, agginitval, "
14258 "0 AS aggmtransspace, NULL AS aggminitval, "
14259 "true AS convertok "
14260 "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14261 "WHERE a.aggfnoid = p.oid "
14262 "AND p.oid = '%u'::pg_catalog.oid",
14263 agginfo
->aggfn
.dobj
.catId
.oid
);
14266 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
14268 i_aggtransfn
= PQfnumber(res
, "aggtransfn");
14269 i_aggfinalfn
= PQfnumber(res
, "aggfinalfn");
14270 i_aggcombinefn
= PQfnumber(res
, "aggcombinefn");
14271 i_aggserialfn
= PQfnumber(res
, "aggserialfn");
14272 i_aggdeserialfn
= PQfnumber(res
, "aggdeserialfn");
14273 i_aggmtransfn
= PQfnumber(res
, "aggmtransfn");
14274 i_aggminvtransfn
= PQfnumber(res
, "aggminvtransfn");
14275 i_aggmfinalfn
= PQfnumber(res
, "aggmfinalfn");
14276 i_aggfinalextra
= PQfnumber(res
, "aggfinalextra");
14277 i_aggmfinalextra
= PQfnumber(res
, "aggmfinalextra");
14278 i_aggfinalmodify
= PQfnumber(res
, "aggfinalmodify");
14279 i_aggmfinalmodify
= PQfnumber(res
, "aggmfinalmodify");
14280 i_aggsortop
= PQfnumber(res
, "aggsortop");
14281 i_aggkind
= PQfnumber(res
, "aggkind");
14282 i_aggtranstype
= PQfnumber(res
, "aggtranstype");
14283 i_aggtransspace
= PQfnumber(res
, "aggtransspace");
14284 i_aggmtranstype
= PQfnumber(res
, "aggmtranstype");
14285 i_aggmtransspace
= PQfnumber(res
, "aggmtransspace");
14286 i_agginitval
= PQfnumber(res
, "agginitval");
14287 i_aggminitval
= PQfnumber(res
, "aggminitval");
14288 i_convertok
= PQfnumber(res
, "convertok");
14289 i_proparallel
= PQfnumber(res
, "proparallel");
14291 aggtransfn
= PQgetvalue(res
, 0, i_aggtransfn
);
14292 aggfinalfn
= PQgetvalue(res
, 0, i_aggfinalfn
);
14293 aggcombinefn
= PQgetvalue(res
, 0, i_aggcombinefn
);
14294 aggserialfn
= PQgetvalue(res
, 0, i_aggserialfn
);
14295 aggdeserialfn
= PQgetvalue(res
, 0, i_aggdeserialfn
);
14296 aggmtransfn
= PQgetvalue(res
, 0, i_aggmtransfn
);
14297 aggminvtransfn
= PQgetvalue(res
, 0, i_aggminvtransfn
);
14298 aggmfinalfn
= PQgetvalue(res
, 0, i_aggmfinalfn
);
14299 aggfinalextra
= (PQgetvalue(res
, 0, i_aggfinalextra
)[0] == 't');
14300 aggmfinalextra
= (PQgetvalue(res
, 0, i_aggmfinalextra
)[0] == 't');
14301 aggfinalmodify
= PQgetvalue(res
, 0, i_aggfinalmodify
)[0];
14302 aggmfinalmodify
= PQgetvalue(res
, 0, i_aggmfinalmodify
)[0];
14303 aggsortop
= PQgetvalue(res
, 0, i_aggsortop
);
14304 aggkind
= PQgetvalue(res
, 0, i_aggkind
)[0];
14305 aggtranstype
= PQgetvalue(res
, 0, i_aggtranstype
);
14306 aggtransspace
= PQgetvalue(res
, 0, i_aggtransspace
);
14307 aggmtranstype
= PQgetvalue(res
, 0, i_aggmtranstype
);
14308 aggmtransspace
= PQgetvalue(res
, 0, i_aggmtransspace
);
14309 agginitval
= PQgetvalue(res
, 0, i_agginitval
);
14310 aggminitval
= PQgetvalue(res
, 0, i_aggminitval
);
14311 convertok
= (PQgetvalue(res
, 0, i_convertok
)[0] == 't');
14313 if (fout
->remoteVersion
>= 80400)
14315 /* 8.4 or later; we rely on server-side code for most of the work */
14319 funcargs
= PQgetvalue(res
, 0, PQfnumber(res
, "funcargs"));
14320 funciargs
= PQgetvalue(res
, 0, PQfnumber(res
, "funciargs"));
14321 aggfullsig
= format_function_arguments(&agginfo
->aggfn
, funcargs
, true);
14322 aggsig
= format_function_arguments(&agginfo
->aggfn
, funciargs
, true);
14325 /* pre-8.4, do it ourselves */
14326 aggsig
= format_aggregate_signature(agginfo
, fout
, true);
14328 aggsig_tag
= format_aggregate_signature(agginfo
, fout
, false);
14330 if (i_proparallel
!= -1)
14331 proparallel
= PQgetvalue(res
, 0, PQfnumber(res
, "proparallel"));
14333 proparallel
= NULL
;
14337 pg_log_warning("aggregate function %s could not be dumped correctly for this database version; ignored",
14348 /* identify default modify flag for aggkind (must match DefineAggregate) */
14349 defaultfinalmodify
= (aggkind
== AGGKIND_NORMAL
) ? AGGMODIFY_READ_ONLY
: AGGMODIFY_READ_WRITE
;
14350 /* replace omitted flags for old versions */
14351 if (aggfinalmodify
== '0')
14352 aggfinalmodify
= defaultfinalmodify
;
14353 if (aggmfinalmodify
== '0')
14354 aggmfinalmodify
= defaultfinalmodify
;
14356 /* regproc and regtype output is already sufficiently quoted */
14357 appendPQExpBuffer(details
, " SFUNC = %s,\n STYPE = %s",
14358 aggtransfn
, aggtranstype
);
14360 if (strcmp(aggtransspace
, "0") != 0)
14362 appendPQExpBuffer(details
, ",\n SSPACE = %s",
14366 if (!PQgetisnull(res
, 0, i_agginitval
))
14368 appendPQExpBufferStr(details
, ",\n INITCOND = ");
14369 appendStringLiteralAH(details
, agginitval
, fout
);
14372 if (strcmp(aggfinalfn
, "-") != 0)
14374 appendPQExpBuffer(details
, ",\n FINALFUNC = %s",
14377 appendPQExpBufferStr(details
, ",\n FINALFUNC_EXTRA");
14378 if (aggfinalmodify
!= defaultfinalmodify
)
14380 switch (aggfinalmodify
)
14382 case AGGMODIFY_READ_ONLY
:
14383 appendPQExpBufferStr(details
, ",\n FINALFUNC_MODIFY = READ_ONLY");
14385 case AGGMODIFY_SHAREABLE
:
14386 appendPQExpBufferStr(details
, ",\n FINALFUNC_MODIFY = SHAREABLE");
14388 case AGGMODIFY_READ_WRITE
:
14389 appendPQExpBufferStr(details
, ",\n FINALFUNC_MODIFY = READ_WRITE");
14392 fatal("unrecognized aggfinalmodify value for aggregate \"%s\"",
14393 agginfo
->aggfn
.dobj
.name
);
14399 if (strcmp(aggcombinefn
, "-") != 0)
14400 appendPQExpBuffer(details
, ",\n COMBINEFUNC = %s", aggcombinefn
);
14402 if (strcmp(aggserialfn
, "-") != 0)
14403 appendPQExpBuffer(details
, ",\n SERIALFUNC = %s", aggserialfn
);
14405 if (strcmp(aggdeserialfn
, "-") != 0)
14406 appendPQExpBuffer(details
, ",\n DESERIALFUNC = %s", aggdeserialfn
);
14408 if (strcmp(aggmtransfn
, "-") != 0)
14410 appendPQExpBuffer(details
, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
14416 if (strcmp(aggmtransspace
, "0") != 0)
14418 appendPQExpBuffer(details
, ",\n MSSPACE = %s",
14422 if (!PQgetisnull(res
, 0, i_aggminitval
))
14424 appendPQExpBufferStr(details
, ",\n MINITCOND = ");
14425 appendStringLiteralAH(details
, aggminitval
, fout
);
14428 if (strcmp(aggmfinalfn
, "-") != 0)
14430 appendPQExpBuffer(details
, ",\n MFINALFUNC = %s",
14432 if (aggmfinalextra
)
14433 appendPQExpBufferStr(details
, ",\n MFINALFUNC_EXTRA");
14434 if (aggmfinalmodify
!= defaultfinalmodify
)
14436 switch (aggmfinalmodify
)
14438 case AGGMODIFY_READ_ONLY
:
14439 appendPQExpBufferStr(details
, ",\n MFINALFUNC_MODIFY = READ_ONLY");
14441 case AGGMODIFY_SHAREABLE
:
14442 appendPQExpBufferStr(details
, ",\n MFINALFUNC_MODIFY = SHAREABLE");
14444 case AGGMODIFY_READ_WRITE
:
14445 appendPQExpBufferStr(details
, ",\n MFINALFUNC_MODIFY = READ_WRITE");
14448 fatal("unrecognized aggmfinalmodify value for aggregate \"%s\"",
14449 agginfo
->aggfn
.dobj
.name
);
14455 aggsortconvop
= getFormattedOperatorName(fout
, aggsortop
);
14458 appendPQExpBuffer(details
, ",\n SORTOP = %s",
14460 free(aggsortconvop
);
14463 if (aggkind
== AGGKIND_HYPOTHETICAL
)
14464 appendPQExpBufferStr(details
, ",\n HYPOTHETICAL");
14466 if (proparallel
!= NULL
&& proparallel
[0] != PROPARALLEL_UNSAFE
)
14468 if (proparallel
[0] == PROPARALLEL_SAFE
)
14469 appendPQExpBufferStr(details
, ",\n PARALLEL = safe");
14470 else if (proparallel
[0] == PROPARALLEL_RESTRICTED
)
14471 appendPQExpBufferStr(details
, ",\n PARALLEL = restricted");
14472 else if (proparallel
[0] != PROPARALLEL_UNSAFE
)
14473 fatal("unrecognized proparallel value for function \"%s\"",
14474 agginfo
->aggfn
.dobj
.name
);
14477 appendPQExpBuffer(delq
, "DROP AGGREGATE %s.%s;\n",
14478 fmtId(agginfo
->aggfn
.dobj
.namespace->dobj
.name
),
14481 appendPQExpBuffer(q
, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14482 fmtId(agginfo
->aggfn
.dobj
.namespace->dobj
.name
),
14483 aggfullsig
? aggfullsig
: aggsig
, details
->data
);
14485 if (dopt
->binary_upgrade
)
14486 binary_upgrade_extension_member(q
, &agginfo
->aggfn
.dobj
,
14487 "AGGREGATE", aggsig
,
14488 agginfo
->aggfn
.dobj
.namespace->dobj
.name
);
14490 if (agginfo
->aggfn
.dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14491 ArchiveEntry(fout
, agginfo
->aggfn
.dobj
.catId
,
14492 agginfo
->aggfn
.dobj
.dumpId
,
14493 ARCHIVE_OPTS(.tag
= aggsig_tag
,
14494 .namespace = agginfo
->aggfn
.dobj
.namespace->dobj
.name
,
14495 .owner
= agginfo
->aggfn
.rolname
,
14496 .description
= "AGGREGATE",
14497 .section
= SECTION_PRE_DATA
,
14498 .createStmt
= q
->data
,
14499 .dropStmt
= delq
->data
));
14501 /* Dump Aggregate Comments */
14502 if (agginfo
->aggfn
.dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14503 dumpComment(fout
, "AGGREGATE", aggsig
,
14504 agginfo
->aggfn
.dobj
.namespace->dobj
.name
,
14505 agginfo
->aggfn
.rolname
,
14506 agginfo
->aggfn
.dobj
.catId
, 0, agginfo
->aggfn
.dobj
.dumpId
);
14508 if (agginfo
->aggfn
.dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
14509 dumpSecLabel(fout
, "AGGREGATE", aggsig
,
14510 agginfo
->aggfn
.dobj
.namespace->dobj
.name
,
14511 agginfo
->aggfn
.rolname
,
14512 agginfo
->aggfn
.dobj
.catId
, 0, agginfo
->aggfn
.dobj
.dumpId
);
14515 * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14516 * command look like a function's GRANT; in particular this affects the
14517 * syntax for zero-argument aggregates and ordered-set aggregates.
14521 aggsig
= format_function_signature(fout
, &agginfo
->aggfn
, true);
14523 if (agginfo
->aggfn
.dobj
.dump
& DUMP_COMPONENT_ACL
)
14524 dumpACL(fout
, agginfo
->aggfn
.dobj
.dumpId
, InvalidDumpId
,
14525 "FUNCTION", aggsig
, NULL
,
14526 agginfo
->aggfn
.dobj
.namespace->dobj
.name
,
14527 agginfo
->aggfn
.rolname
, agginfo
->aggfn
.proacl
,
14528 agginfo
->aggfn
.rproacl
,
14529 agginfo
->aggfn
.initproacl
, agginfo
->aggfn
.initrproacl
);
14538 destroyPQExpBuffer(query
);
14539 destroyPQExpBuffer(q
);
14540 destroyPQExpBuffer(delq
);
14541 destroyPQExpBuffer(details
);
14546 * write out a single text search parser
14549 dumpTSParser(Archive
*fout
, TSParserInfo
*prsinfo
)
14551 DumpOptions
*dopt
= fout
->dopt
;
14556 /* Skip if not to be dumped */
14557 if (!prsinfo
->dobj
.dump
|| dopt
->dataOnly
)
14560 q
= createPQExpBuffer();
14561 delq
= createPQExpBuffer();
14563 qprsname
= pg_strdup(fmtId(prsinfo
->dobj
.name
));
14565 appendPQExpBuffer(q
, "CREATE TEXT SEARCH PARSER %s (\n",
14566 fmtQualifiedDumpable(prsinfo
));
14568 appendPQExpBuffer(q
, " START = %s,\n",
14569 convertTSFunction(fout
, prsinfo
->prsstart
));
14570 appendPQExpBuffer(q
, " GETTOKEN = %s,\n",
14571 convertTSFunction(fout
, prsinfo
->prstoken
));
14572 appendPQExpBuffer(q
, " END = %s,\n",
14573 convertTSFunction(fout
, prsinfo
->prsend
));
14574 if (prsinfo
->prsheadline
!= InvalidOid
)
14575 appendPQExpBuffer(q
, " HEADLINE = %s,\n",
14576 convertTSFunction(fout
, prsinfo
->prsheadline
));
14577 appendPQExpBuffer(q
, " LEXTYPES = %s );\n",
14578 convertTSFunction(fout
, prsinfo
->prslextype
));
14580 appendPQExpBuffer(delq
, "DROP TEXT SEARCH PARSER %s;\n",
14581 fmtQualifiedDumpable(prsinfo
));
14583 if (dopt
->binary_upgrade
)
14584 binary_upgrade_extension_member(q
, &prsinfo
->dobj
,
14585 "TEXT SEARCH PARSER", qprsname
,
14586 prsinfo
->dobj
.namespace->dobj
.name
);
14588 if (prsinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14589 ArchiveEntry(fout
, prsinfo
->dobj
.catId
, prsinfo
->dobj
.dumpId
,
14590 ARCHIVE_OPTS(.tag
= prsinfo
->dobj
.name
,
14591 .namespace = prsinfo
->dobj
.namespace->dobj
.name
,
14592 .description
= "TEXT SEARCH PARSER",
14593 .section
= SECTION_PRE_DATA
,
14594 .createStmt
= q
->data
,
14595 .dropStmt
= delq
->data
));
14597 /* Dump Parser Comments */
14598 if (prsinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14599 dumpComment(fout
, "TEXT SEARCH PARSER", qprsname
,
14600 prsinfo
->dobj
.namespace->dobj
.name
, "",
14601 prsinfo
->dobj
.catId
, 0, prsinfo
->dobj
.dumpId
);
14603 destroyPQExpBuffer(q
);
14604 destroyPQExpBuffer(delq
);
14610 * write out a single text search dictionary
14613 dumpTSDictionary(Archive
*fout
, TSDictInfo
*dictinfo
)
14615 DumpOptions
*dopt
= fout
->dopt
;
14624 /* Skip if not to be dumped */
14625 if (!dictinfo
->dobj
.dump
|| dopt
->dataOnly
)
14628 q
= createPQExpBuffer();
14629 delq
= createPQExpBuffer();
14630 query
= createPQExpBuffer();
14632 qdictname
= pg_strdup(fmtId(dictinfo
->dobj
.name
));
14634 /* Fetch name and namespace of the dictionary's template */
14635 appendPQExpBuffer(query
, "SELECT nspname, tmplname "
14636 "FROM pg_ts_template p, pg_namespace n "
14637 "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14638 dictinfo
->dicttemplate
);
14639 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
14640 nspname
= PQgetvalue(res
, 0, 0);
14641 tmplname
= PQgetvalue(res
, 0, 1);
14643 appendPQExpBuffer(q
, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14644 fmtQualifiedDumpable(dictinfo
));
14646 appendPQExpBufferStr(q
, " TEMPLATE = ");
14647 appendPQExpBuffer(q
, "%s.", fmtId(nspname
));
14648 appendPQExpBufferStr(q
, fmtId(tmplname
));
14652 /* the dictinitoption can be dumped straight into the command */
14653 if (dictinfo
->dictinitoption
)
14654 appendPQExpBuffer(q
, ",\n %s", dictinfo
->dictinitoption
);
14656 appendPQExpBufferStr(q
, " );\n");
14658 appendPQExpBuffer(delq
, "DROP TEXT SEARCH DICTIONARY %s;\n",
14659 fmtQualifiedDumpable(dictinfo
));
14661 if (dopt
->binary_upgrade
)
14662 binary_upgrade_extension_member(q
, &dictinfo
->dobj
,
14663 "TEXT SEARCH DICTIONARY", qdictname
,
14664 dictinfo
->dobj
.namespace->dobj
.name
);
14666 if (dictinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14667 ArchiveEntry(fout
, dictinfo
->dobj
.catId
, dictinfo
->dobj
.dumpId
,
14668 ARCHIVE_OPTS(.tag
= dictinfo
->dobj
.name
,
14669 .namespace = dictinfo
->dobj
.namespace->dobj
.name
,
14670 .owner
= dictinfo
->rolname
,
14671 .description
= "TEXT SEARCH DICTIONARY",
14672 .section
= SECTION_PRE_DATA
,
14673 .createStmt
= q
->data
,
14674 .dropStmt
= delq
->data
));
14676 /* Dump Dictionary Comments */
14677 if (dictinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14678 dumpComment(fout
, "TEXT SEARCH DICTIONARY", qdictname
,
14679 dictinfo
->dobj
.namespace->dobj
.name
, dictinfo
->rolname
,
14680 dictinfo
->dobj
.catId
, 0, dictinfo
->dobj
.dumpId
);
14682 destroyPQExpBuffer(q
);
14683 destroyPQExpBuffer(delq
);
14684 destroyPQExpBuffer(query
);
14690 * write out a single text search template
14693 dumpTSTemplate(Archive
*fout
, TSTemplateInfo
*tmplinfo
)
14695 DumpOptions
*dopt
= fout
->dopt
;
14700 /* Skip if not to be dumped */
14701 if (!tmplinfo
->dobj
.dump
|| dopt
->dataOnly
)
14704 q
= createPQExpBuffer();
14705 delq
= createPQExpBuffer();
14707 qtmplname
= pg_strdup(fmtId(tmplinfo
->dobj
.name
));
14709 appendPQExpBuffer(q
, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14710 fmtQualifiedDumpable(tmplinfo
));
14712 if (tmplinfo
->tmplinit
!= InvalidOid
)
14713 appendPQExpBuffer(q
, " INIT = %s,\n",
14714 convertTSFunction(fout
, tmplinfo
->tmplinit
));
14715 appendPQExpBuffer(q
, " LEXIZE = %s );\n",
14716 convertTSFunction(fout
, tmplinfo
->tmpllexize
));
14718 appendPQExpBuffer(delq
, "DROP TEXT SEARCH TEMPLATE %s;\n",
14719 fmtQualifiedDumpable(tmplinfo
));
14721 if (dopt
->binary_upgrade
)
14722 binary_upgrade_extension_member(q
, &tmplinfo
->dobj
,
14723 "TEXT SEARCH TEMPLATE", qtmplname
,
14724 tmplinfo
->dobj
.namespace->dobj
.name
);
14726 if (tmplinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14727 ArchiveEntry(fout
, tmplinfo
->dobj
.catId
, tmplinfo
->dobj
.dumpId
,
14728 ARCHIVE_OPTS(.tag
= tmplinfo
->dobj
.name
,
14729 .namespace = tmplinfo
->dobj
.namespace->dobj
.name
,
14730 .description
= "TEXT SEARCH TEMPLATE",
14731 .section
= SECTION_PRE_DATA
,
14732 .createStmt
= q
->data
,
14733 .dropStmt
= delq
->data
));
14735 /* Dump Template Comments */
14736 if (tmplinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14737 dumpComment(fout
, "TEXT SEARCH TEMPLATE", qtmplname
,
14738 tmplinfo
->dobj
.namespace->dobj
.name
, "",
14739 tmplinfo
->dobj
.catId
, 0, tmplinfo
->dobj
.dumpId
);
14741 destroyPQExpBuffer(q
);
14742 destroyPQExpBuffer(delq
);
14748 * write out a single text search configuration
14751 dumpTSConfig(Archive
*fout
, TSConfigInfo
*cfginfo
)
14753 DumpOptions
*dopt
= fout
->dopt
;
14766 /* Skip if not to be dumped */
14767 if (!cfginfo
->dobj
.dump
|| dopt
->dataOnly
)
14770 q
= createPQExpBuffer();
14771 delq
= createPQExpBuffer();
14772 query
= createPQExpBuffer();
14774 qcfgname
= pg_strdup(fmtId(cfginfo
->dobj
.name
));
14776 /* Fetch name and namespace of the config's parser */
14777 appendPQExpBuffer(query
, "SELECT nspname, prsname "
14778 "FROM pg_ts_parser p, pg_namespace n "
14779 "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14780 cfginfo
->cfgparser
);
14781 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
14782 nspname
= PQgetvalue(res
, 0, 0);
14783 prsname
= PQgetvalue(res
, 0, 1);
14785 appendPQExpBuffer(q
, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14786 fmtQualifiedDumpable(cfginfo
));
14788 appendPQExpBuffer(q
, " PARSER = %s.", fmtId(nspname
));
14789 appendPQExpBuffer(q
, "%s );\n", fmtId(prsname
));
14793 resetPQExpBuffer(query
);
14794 appendPQExpBuffer(query
,
14796 " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14797 " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14798 " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14799 "FROM pg_catalog.pg_ts_config_map AS m\n"
14800 "WHERE m.mapcfg = '%u'\n"
14801 "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14802 cfginfo
->cfgparser
, cfginfo
->dobj
.catId
.oid
);
14804 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
14805 ntups
= PQntuples(res
);
14807 i_tokenname
= PQfnumber(res
, "tokenname");
14808 i_dictname
= PQfnumber(res
, "dictname");
14810 for (i
= 0; i
< ntups
; i
++)
14812 char *tokenname
= PQgetvalue(res
, i
, i_tokenname
);
14813 char *dictname
= PQgetvalue(res
, i
, i_dictname
);
14816 strcmp(tokenname
, PQgetvalue(res
, i
- 1, i_tokenname
)) != 0)
14818 /* starting a new token type, so start a new command */
14820 appendPQExpBufferStr(q
, ";\n");
14821 appendPQExpBuffer(q
, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14822 fmtQualifiedDumpable(cfginfo
));
14823 /* tokenname needs quoting, dictname does NOT */
14824 appendPQExpBuffer(q
, " ADD MAPPING FOR %s WITH %s",
14825 fmtId(tokenname
), dictname
);
14828 appendPQExpBuffer(q
, ", %s", dictname
);
14832 appendPQExpBufferStr(q
, ";\n");
14836 appendPQExpBuffer(delq
, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14837 fmtQualifiedDumpable(cfginfo
));
14839 if (dopt
->binary_upgrade
)
14840 binary_upgrade_extension_member(q
, &cfginfo
->dobj
,
14841 "TEXT SEARCH CONFIGURATION", qcfgname
,
14842 cfginfo
->dobj
.namespace->dobj
.name
);
14844 if (cfginfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14845 ArchiveEntry(fout
, cfginfo
->dobj
.catId
, cfginfo
->dobj
.dumpId
,
14846 ARCHIVE_OPTS(.tag
= cfginfo
->dobj
.name
,
14847 .namespace = cfginfo
->dobj
.namespace->dobj
.name
,
14848 .owner
= cfginfo
->rolname
,
14849 .description
= "TEXT SEARCH CONFIGURATION",
14850 .section
= SECTION_PRE_DATA
,
14851 .createStmt
= q
->data
,
14852 .dropStmt
= delq
->data
));
14854 /* Dump Configuration Comments */
14855 if (cfginfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14856 dumpComment(fout
, "TEXT SEARCH CONFIGURATION", qcfgname
,
14857 cfginfo
->dobj
.namespace->dobj
.name
, cfginfo
->rolname
,
14858 cfginfo
->dobj
.catId
, 0, cfginfo
->dobj
.dumpId
);
14860 destroyPQExpBuffer(q
);
14861 destroyPQExpBuffer(delq
);
14862 destroyPQExpBuffer(query
);
14867 * dumpForeignDataWrapper
14868 * write out a single foreign-data wrapper definition
14871 dumpForeignDataWrapper(Archive
*fout
, FdwInfo
*fdwinfo
)
14873 DumpOptions
*dopt
= fout
->dopt
;
14878 /* Skip if not to be dumped */
14879 if (!fdwinfo
->dobj
.dump
|| dopt
->dataOnly
)
14882 q
= createPQExpBuffer();
14883 delq
= createPQExpBuffer();
14885 qfdwname
= pg_strdup(fmtId(fdwinfo
->dobj
.name
));
14887 appendPQExpBuffer(q
, "CREATE FOREIGN DATA WRAPPER %s",
14890 if (strcmp(fdwinfo
->fdwhandler
, "-") != 0)
14891 appendPQExpBuffer(q
, " HANDLER %s", fdwinfo
->fdwhandler
);
14893 if (strcmp(fdwinfo
->fdwvalidator
, "-") != 0)
14894 appendPQExpBuffer(q
, " VALIDATOR %s", fdwinfo
->fdwvalidator
);
14896 if (strlen(fdwinfo
->fdwoptions
) > 0)
14897 appendPQExpBuffer(q
, " OPTIONS (\n %s\n)", fdwinfo
->fdwoptions
);
14899 appendPQExpBufferStr(q
, ";\n");
14901 appendPQExpBuffer(delq
, "DROP FOREIGN DATA WRAPPER %s;\n",
14904 if (dopt
->binary_upgrade
)
14905 binary_upgrade_extension_member(q
, &fdwinfo
->dobj
,
14906 "FOREIGN DATA WRAPPER", qfdwname
,
14909 if (fdwinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14910 ArchiveEntry(fout
, fdwinfo
->dobj
.catId
, fdwinfo
->dobj
.dumpId
,
14911 ARCHIVE_OPTS(.tag
= fdwinfo
->dobj
.name
,
14912 .owner
= fdwinfo
->rolname
,
14913 .description
= "FOREIGN DATA WRAPPER",
14914 .section
= SECTION_PRE_DATA
,
14915 .createStmt
= q
->data
,
14916 .dropStmt
= delq
->data
));
14918 /* Dump Foreign Data Wrapper Comments */
14919 if (fdwinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
14920 dumpComment(fout
, "FOREIGN DATA WRAPPER", qfdwname
,
14921 NULL
, fdwinfo
->rolname
,
14922 fdwinfo
->dobj
.catId
, 0, fdwinfo
->dobj
.dumpId
);
14924 /* Handle the ACL */
14925 if (fdwinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
14926 dumpACL(fout
, fdwinfo
->dobj
.dumpId
, InvalidDumpId
,
14927 "FOREIGN DATA WRAPPER", qfdwname
, NULL
,
14928 NULL
, fdwinfo
->rolname
,
14929 fdwinfo
->fdwacl
, fdwinfo
->rfdwacl
,
14930 fdwinfo
->initfdwacl
, fdwinfo
->initrfdwacl
);
14934 destroyPQExpBuffer(q
);
14935 destroyPQExpBuffer(delq
);
14939 * dumpForeignServer
14940 * write out a foreign server definition
14943 dumpForeignServer(Archive
*fout
, ForeignServerInfo
*srvinfo
)
14945 DumpOptions
*dopt
= fout
->dopt
;
14953 /* Skip if not to be dumped */
14954 if (!srvinfo
->dobj
.dump
|| dopt
->dataOnly
)
14957 q
= createPQExpBuffer();
14958 delq
= createPQExpBuffer();
14959 query
= createPQExpBuffer();
14961 qsrvname
= pg_strdup(fmtId(srvinfo
->dobj
.name
));
14963 /* look up the foreign-data wrapper */
14964 appendPQExpBuffer(query
, "SELECT fdwname "
14965 "FROM pg_foreign_data_wrapper w "
14966 "WHERE w.oid = '%u'",
14968 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
14969 fdwname
= PQgetvalue(res
, 0, 0);
14971 appendPQExpBuffer(q
, "CREATE SERVER %s", qsrvname
);
14972 if (srvinfo
->srvtype
&& strlen(srvinfo
->srvtype
) > 0)
14974 appendPQExpBufferStr(q
, " TYPE ");
14975 appendStringLiteralAH(q
, srvinfo
->srvtype
, fout
);
14977 if (srvinfo
->srvversion
&& strlen(srvinfo
->srvversion
) > 0)
14979 appendPQExpBufferStr(q
, " VERSION ");
14980 appendStringLiteralAH(q
, srvinfo
->srvversion
, fout
);
14983 appendPQExpBufferStr(q
, " FOREIGN DATA WRAPPER ");
14984 appendPQExpBufferStr(q
, fmtId(fdwname
));
14986 if (srvinfo
->srvoptions
&& strlen(srvinfo
->srvoptions
) > 0)
14987 appendPQExpBuffer(q
, " OPTIONS (\n %s\n)", srvinfo
->srvoptions
);
14989 appendPQExpBufferStr(q
, ";\n");
14991 appendPQExpBuffer(delq
, "DROP SERVER %s;\n",
14994 if (dopt
->binary_upgrade
)
14995 binary_upgrade_extension_member(q
, &srvinfo
->dobj
,
14996 "SERVER", qsrvname
, NULL
);
14998 if (srvinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
14999 ArchiveEntry(fout
, srvinfo
->dobj
.catId
, srvinfo
->dobj
.dumpId
,
15000 ARCHIVE_OPTS(.tag
= srvinfo
->dobj
.name
,
15001 .owner
= srvinfo
->rolname
,
15002 .description
= "SERVER",
15003 .section
= SECTION_PRE_DATA
,
15004 .createStmt
= q
->data
,
15005 .dropStmt
= delq
->data
));
15007 /* Dump Foreign Server Comments */
15008 if (srvinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
15009 dumpComment(fout
, "SERVER", qsrvname
,
15010 NULL
, srvinfo
->rolname
,
15011 srvinfo
->dobj
.catId
, 0, srvinfo
->dobj
.dumpId
);
15013 /* Handle the ACL */
15014 if (srvinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
15015 dumpACL(fout
, srvinfo
->dobj
.dumpId
, InvalidDumpId
,
15016 "FOREIGN SERVER", qsrvname
, NULL
,
15017 NULL
, srvinfo
->rolname
,
15018 srvinfo
->srvacl
, srvinfo
->rsrvacl
,
15019 srvinfo
->initsrvacl
, srvinfo
->initrsrvacl
);
15021 /* Dump user mappings */
15022 if (srvinfo
->dobj
.dump
& DUMP_COMPONENT_USERMAP
)
15023 dumpUserMappings(fout
,
15024 srvinfo
->dobj
.name
, NULL
,
15026 srvinfo
->dobj
.catId
, srvinfo
->dobj
.dumpId
);
15030 destroyPQExpBuffer(q
);
15031 destroyPQExpBuffer(delq
);
15032 destroyPQExpBuffer(query
);
15038 * This routine is used to dump any user mappings associated with the
15039 * server handed to this routine. Should be called after ArchiveEntry()
15043 dumpUserMappings(Archive
*fout
,
15044 const char *servername
, const char *namespace,
15046 CatalogId catalogId
, DumpId dumpId
)
15058 q
= createPQExpBuffer();
15059 tag
= createPQExpBuffer();
15060 delq
= createPQExpBuffer();
15061 query
= createPQExpBuffer();
15064 * We read from the publicly accessible view pg_user_mappings, so as not
15065 * to fail if run by a non-superuser. Note that the view will show
15066 * umoptions as null if the user hasn't got privileges for the associated
15067 * server; this means that pg_dump will dump such a mapping, but with no
15068 * OPTIONS clause. A possible alternative is to skip such mappings
15069 * altogether, but it's not clear that that's an improvement.
15071 appendPQExpBuffer(query
,
15073 "array_to_string(ARRAY("
15074 "SELECT quote_ident(option_name) || ' ' || "
15075 "quote_literal(option_value) "
15076 "FROM pg_options_to_table(umoptions) "
15077 "ORDER BY option_name"
15078 "), E',\n ') AS umoptions "
15079 "FROM pg_user_mappings "
15080 "WHERE srvid = '%u' "
15081 "ORDER BY usename",
15084 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
15086 ntups
= PQntuples(res
);
15087 i_usename
= PQfnumber(res
, "usename");
15088 i_umoptions
= PQfnumber(res
, "umoptions");
15090 for (i
= 0; i
< ntups
; i
++)
15095 usename
= PQgetvalue(res
, i
, i_usename
);
15096 umoptions
= PQgetvalue(res
, i
, i_umoptions
);
15098 resetPQExpBuffer(q
);
15099 appendPQExpBuffer(q
, "CREATE USER MAPPING FOR %s", fmtId(usename
));
15100 appendPQExpBuffer(q
, " SERVER %s", fmtId(servername
));
15102 if (umoptions
&& strlen(umoptions
) > 0)
15103 appendPQExpBuffer(q
, " OPTIONS (\n %s\n)", umoptions
);
15105 appendPQExpBufferStr(q
, ";\n");
15107 resetPQExpBuffer(delq
);
15108 appendPQExpBuffer(delq
, "DROP USER MAPPING FOR %s", fmtId(usename
));
15109 appendPQExpBuffer(delq
, " SERVER %s;\n", fmtId(servername
));
15111 resetPQExpBuffer(tag
);
15112 appendPQExpBuffer(tag
, "USER MAPPING %s SERVER %s",
15113 usename
, servername
);
15115 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
15116 ARCHIVE_OPTS(.tag
= tag
->data
,
15117 .namespace = namespace,
15119 .description
= "USER MAPPING",
15120 .section
= SECTION_PRE_DATA
,
15121 .createStmt
= q
->data
,
15122 .dropStmt
= delq
->data
));
15127 destroyPQExpBuffer(query
);
15128 destroyPQExpBuffer(delq
);
15129 destroyPQExpBuffer(tag
);
15130 destroyPQExpBuffer(q
);
15134 * Write out default privileges information
15137 dumpDefaultACL(Archive
*fout
, DefaultACLInfo
*daclinfo
)
15139 DumpOptions
*dopt
= fout
->dopt
;
15144 /* Skip if not to be dumped */
15145 if (!daclinfo
->dobj
.dump
|| dopt
->dataOnly
|| dopt
->aclsSkip
)
15148 q
= createPQExpBuffer();
15149 tag
= createPQExpBuffer();
15151 switch (daclinfo
->defaclobjtype
)
15153 case DEFACLOBJ_RELATION
:
15156 case DEFACLOBJ_SEQUENCE
:
15157 type
= "SEQUENCES";
15159 case DEFACLOBJ_FUNCTION
:
15160 type
= "FUNCTIONS";
15162 case DEFACLOBJ_TYPE
:
15165 case DEFACLOBJ_NAMESPACE
:
15169 /* shouldn't get here */
15170 fatal("unrecognized object type in default privileges: %d",
15171 (int) daclinfo
->defaclobjtype
);
15172 type
= ""; /* keep compiler quiet */
15175 appendPQExpBuffer(tag
, "DEFAULT PRIVILEGES FOR %s", type
);
15177 /* build the actual command(s) for this tuple */
15178 if (!buildDefaultACLCommands(type
,
15179 daclinfo
->dobj
.namespace != NULL
?
15180 daclinfo
->dobj
.namespace->dobj
.name
: NULL
,
15181 daclinfo
->defaclacl
,
15182 daclinfo
->rdefaclacl
,
15183 daclinfo
->initdefaclacl
,
15184 daclinfo
->initrdefaclacl
,
15185 daclinfo
->defaclrole
,
15186 fout
->remoteVersion
,
15188 fatal("could not parse default ACL list (%s)",
15189 daclinfo
->defaclacl
);
15191 if (daclinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
15192 ArchiveEntry(fout
, daclinfo
->dobj
.catId
, daclinfo
->dobj
.dumpId
,
15193 ARCHIVE_OPTS(.tag
= tag
->data
,
15194 .namespace = daclinfo
->dobj
.namespace ?
15195 daclinfo
->dobj
.namespace->dobj
.name
: NULL
,
15196 .owner
= daclinfo
->defaclrole
,
15197 .description
= "DEFAULT ACL",
15198 .section
= SECTION_POST_DATA
,
15199 .createStmt
= q
->data
));
15201 destroyPQExpBuffer(tag
);
15202 destroyPQExpBuffer(q
);
15206 * Write out grant/revoke information
15208 * 'objDumpId' is the dump ID of the underlying object.
15209 * 'altDumpId' can be a second dumpId that the ACL entry must also depend on,
15210 * or InvalidDumpId if there is no need for a second dependency.
15211 * 'type' must be one of
15212 * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
15213 * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
15214 * 'name' is the formatted name of the object. Must be quoted etc. already.
15215 * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
15216 * (Currently we assume that subname is only provided for table columns.)
15217 * 'nspname' is the namespace the object is in (NULL if none).
15218 * 'owner' is the owner, NULL if there is no owner (for languages).
15219 * 'acls' contains the ACL string of the object from the appropriate system
15220 * catalog field; it will be passed to buildACLCommands for building the
15221 * appropriate GRANT commands.
15222 * 'racls' contains the ACL string of any initial-but-now-revoked ACLs of the
15223 * object; it will be passed to buildACLCommands for building the
15224 * appropriate REVOKE commands.
15225 * 'initacls' In binary-upgrade mode, ACL string of the object's initial
15226 * privileges, to be recorded into pg_init_privs
15227 * 'initracls' In binary-upgrade mode, ACL string of the object's
15228 * revoked-from-default privileges, to be recorded into pg_init_privs
15230 * NB: initacls/initracls are needed because extensions can set privileges on
15231 * an object during the extension's script file and we record those into
15232 * pg_init_privs as that object's initial privileges.
15234 * Returns the dump ID assigned to the ACL TocEntry, or InvalidDumpId if
15235 * no ACL entry was created.
15239 dumpACL(Archive
*fout
, DumpId objDumpId
, DumpId altDumpId
,
15240 const char *type
, const char *name
, const char *subname
,
15241 const char *nspname
, const char *owner
,
15242 const char *acls
, const char *racls
,
15243 const char *initacls
, const char *initracls
)
15245 DumpId aclDumpId
= InvalidDumpId
;
15246 DumpOptions
*dopt
= fout
->dopt
;
15249 /* Do nothing if ACL dump is not enabled */
15250 if (dopt
->aclsSkip
)
15251 return InvalidDumpId
;
15253 /* --data-only skips ACLs *except* BLOB ACLs */
15254 if (dopt
->dataOnly
&& strcmp(type
, "LARGE OBJECT") != 0)
15255 return InvalidDumpId
;
15257 sql
= createPQExpBuffer();
15260 * Check to see if this object has had any initial ACLs included for it.
15261 * If so, we are in binary upgrade mode and these are the ACLs to turn
15262 * into GRANT and REVOKE statements to set and record the initial
15263 * privileges for an extension object. Let the backend know that these
15264 * are to be recorded by calling binary_upgrade_set_record_init_privs()
15265 * before and after.
15267 if (strlen(initacls
) != 0 || strlen(initracls
) != 0)
15269 appendPQExpBuffer(sql
, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
15270 if (!buildACLCommands(name
, subname
, nspname
, type
,
15271 initacls
, initracls
, owner
,
15272 "", fout
->remoteVersion
, sql
))
15273 fatal("could not parse initial GRANT ACL list (%s) or initial REVOKE ACL list (%s) for object \"%s\" (%s)",
15274 initacls
, initracls
, name
, type
);
15275 appendPQExpBuffer(sql
, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
15278 if (!buildACLCommands(name
, subname
, nspname
, type
,
15279 acls
, racls
, owner
,
15280 "", fout
->remoteVersion
, sql
))
15281 fatal("could not parse GRANT ACL list (%s) or REVOKE ACL list (%s) for object \"%s\" (%s)",
15282 acls
, racls
, name
, type
);
15286 PQExpBuffer tag
= createPQExpBuffer();
15291 appendPQExpBuffer(tag
, "COLUMN %s.%s", name
, subname
);
15293 appendPQExpBuffer(tag
, "%s %s", type
, name
);
15295 aclDeps
[nDeps
++] = objDumpId
;
15296 if (altDumpId
!= InvalidDumpId
)
15297 aclDeps
[nDeps
++] = altDumpId
;
15299 aclDumpId
= createDumpId();
15301 ArchiveEntry(fout
, nilCatalogId
, aclDumpId
,
15302 ARCHIVE_OPTS(.tag
= tag
->data
,
15303 .namespace = nspname
,
15305 .description
= "ACL",
15306 .section
= SECTION_NONE
,
15307 .createStmt
= sql
->data
,
15311 destroyPQExpBuffer(tag
);
15314 destroyPQExpBuffer(sql
);
15322 * This routine is used to dump any security labels associated with the
15323 * object handed to this routine. The routine takes the object type
15324 * and object name (ready to print, except for schema decoration), plus
15325 * the namespace and owner of the object (for labeling the ArchiveEntry),
15326 * plus catalog ID and subid which are the lookup key for pg_seclabel,
15327 * plus the dump ID for the object (for setting a dependency).
15328 * If a matching pg_seclabel entry is found, it is dumped.
15330 * Note: although this routine takes a dumpId for dependency purposes,
15331 * that purpose is just to mark the dependency in the emitted dump file
15332 * for possible future use by pg_restore. We do NOT use it for determining
15333 * ordering of the label in the dump file, because this routine is called
15334 * after dependency sorting occurs. This routine should be called just after
15335 * calling ArchiveEntry() for the specified object.
15338 dumpSecLabel(Archive
*fout
, const char *type
, const char *name
,
15339 const char *namespace, const char *owner
,
15340 CatalogId catalogId
, int subid
, DumpId dumpId
)
15342 DumpOptions
*dopt
= fout
->dopt
;
15343 SecLabelItem
*labels
;
15348 /* do nothing, if --no-security-labels is supplied */
15349 if (dopt
->no_security_labels
)
15352 /* Security labels are schema not data ... except blob labels are data */
15353 if (strcmp(type
, "LARGE OBJECT") != 0)
15355 if (dopt
->dataOnly
)
15360 /* We do dump blob security labels in binary-upgrade mode */
15361 if (dopt
->schemaOnly
&& !dopt
->binary_upgrade
)
15365 /* Search for security labels associated with catalogId, using table */
15366 nlabels
= findSecLabels(fout
, catalogId
.tableoid
, catalogId
.oid
, &labels
);
15368 query
= createPQExpBuffer();
15370 for (i
= 0; i
< nlabels
; i
++)
15373 * Ignore label entries for which the subid doesn't match.
15375 if (labels
[i
].objsubid
!= subid
)
15378 appendPQExpBuffer(query
,
15379 "SECURITY LABEL FOR %s ON %s ",
15380 fmtId(labels
[i
].provider
), type
);
15381 if (namespace && *namespace)
15382 appendPQExpBuffer(query
, "%s.", fmtId(namespace));
15383 appendPQExpBuffer(query
, "%s IS ", name
);
15384 appendStringLiteralAH(query
, labels
[i
].label
, fout
);
15385 appendPQExpBufferStr(query
, ";\n");
15388 if (query
->len
> 0)
15390 PQExpBuffer tag
= createPQExpBuffer();
15392 appendPQExpBuffer(tag
, "%s %s", type
, name
);
15393 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
15394 ARCHIVE_OPTS(.tag
= tag
->data
,
15395 .namespace = namespace,
15397 .description
= "SECURITY LABEL",
15398 .section
= SECTION_NONE
,
15399 .createStmt
= query
->data
,
15402 destroyPQExpBuffer(tag
);
15405 destroyPQExpBuffer(query
);
15409 * dumpTableSecLabel
15411 * As above, but dump security label for both the specified table (or view)
15415 dumpTableSecLabel(Archive
*fout
, TableInfo
*tbinfo
, const char *reltypename
)
15417 DumpOptions
*dopt
= fout
->dopt
;
15418 SecLabelItem
*labels
;
15422 PQExpBuffer target
;
15424 /* do nothing, if --no-security-labels is supplied */
15425 if (dopt
->no_security_labels
)
15428 /* SecLabel are SCHEMA not data */
15429 if (dopt
->dataOnly
)
15432 /* Search for comments associated with relation, using table */
15433 nlabels
= findSecLabels(fout
,
15434 tbinfo
->dobj
.catId
.tableoid
,
15435 tbinfo
->dobj
.catId
.oid
,
15438 /* If security labels exist, build SECURITY LABEL statements */
15442 query
= createPQExpBuffer();
15443 target
= createPQExpBuffer();
15445 for (i
= 0; i
< nlabels
; i
++)
15447 const char *colname
;
15448 const char *provider
= labels
[i
].provider
;
15449 const char *label
= labels
[i
].label
;
15450 int objsubid
= labels
[i
].objsubid
;
15452 resetPQExpBuffer(target
);
15455 appendPQExpBuffer(target
, "%s %s", reltypename
,
15456 fmtQualifiedDumpable(tbinfo
));
15460 colname
= getAttrName(objsubid
, tbinfo
);
15461 /* first fmtXXX result must be consumed before calling again */
15462 appendPQExpBuffer(target
, "COLUMN %s",
15463 fmtQualifiedDumpable(tbinfo
));
15464 appendPQExpBuffer(target
, ".%s", fmtId(colname
));
15466 appendPQExpBuffer(query
, "SECURITY LABEL FOR %s ON %s IS ",
15467 fmtId(provider
), target
->data
);
15468 appendStringLiteralAH(query
, label
, fout
);
15469 appendPQExpBufferStr(query
, ";\n");
15471 if (query
->len
> 0)
15473 resetPQExpBuffer(target
);
15474 appendPQExpBuffer(target
, "%s %s", reltypename
,
15475 fmtId(tbinfo
->dobj
.name
));
15476 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
15477 ARCHIVE_OPTS(.tag
= target
->data
,
15478 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
15479 .owner
= tbinfo
->rolname
,
15480 .description
= "SECURITY LABEL",
15481 .section
= SECTION_NONE
,
15482 .createStmt
= query
->data
,
15483 .deps
= &(tbinfo
->dobj
.dumpId
),
15486 destroyPQExpBuffer(query
);
15487 destroyPQExpBuffer(target
);
15493 * Find the security label(s), if any, associated with the given object.
15494 * All the objsubid values associated with the given classoid/objoid are
15495 * found with one search.
15498 findSecLabels(Archive
*fout
, Oid classoid
, Oid objoid
, SecLabelItem
**items
)
15500 /* static storage for table of security labels */
15501 static SecLabelItem
*labels
= NULL
;
15502 static int nlabels
= -1;
15504 SecLabelItem
*middle
= NULL
;
15506 SecLabelItem
*high
;
15509 /* Get security labels if we didn't already */
15511 nlabels
= collectSecLabels(fout
, &labels
);
15513 if (nlabels
<= 0) /* no labels, so no match is possible */
15520 * Do binary search to find some item matching the object.
15523 high
= &labels
[nlabels
- 1];
15524 while (low
<= high
)
15526 middle
= low
+ (high
- low
) / 2;
15528 if (classoid
< middle
->classoid
)
15530 else if (classoid
> middle
->classoid
)
15532 else if (objoid
< middle
->objoid
)
15534 else if (objoid
> middle
->objoid
)
15537 break; /* found a match */
15540 if (low
> high
) /* no matches */
15547 * Now determine how many items match the object. The search loop
15548 * invariant still holds: only items between low and high inclusive could
15552 while (middle
> low
)
15554 if (classoid
!= middle
[-1].classoid
||
15555 objoid
!= middle
[-1].objoid
)
15564 while (middle
<= high
)
15566 if (classoid
!= middle
->classoid
||
15567 objoid
!= middle
->objoid
)
15579 * Construct a table of all security labels available for database objects.
15580 * It's much faster to pull them all at once.
15582 * The table is sorted by classoid/objid/objsubid for speed in lookup.
15585 collectSecLabels(Archive
*fout
, SecLabelItem
**items
)
15596 SecLabelItem
*labels
;
15598 query
= createPQExpBuffer();
15600 appendPQExpBufferStr(query
,
15601 "SELECT label, provider, classoid, objoid, objsubid "
15602 "FROM pg_catalog.pg_seclabel "
15603 "ORDER BY classoid, objoid, objsubid");
15605 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
15607 /* Construct lookup table containing OIDs in numeric form */
15608 i_label
= PQfnumber(res
, "label");
15609 i_provider
= PQfnumber(res
, "provider");
15610 i_classoid
= PQfnumber(res
, "classoid");
15611 i_objoid
= PQfnumber(res
, "objoid");
15612 i_objsubid
= PQfnumber(res
, "objsubid");
15614 ntups
= PQntuples(res
);
15616 labels
= (SecLabelItem
*) pg_malloc(ntups
* sizeof(SecLabelItem
));
15618 for (i
= 0; i
< ntups
; i
++)
15620 labels
[i
].label
= PQgetvalue(res
, i
, i_label
);
15621 labels
[i
].provider
= PQgetvalue(res
, i
, i_provider
);
15622 labels
[i
].classoid
= atooid(PQgetvalue(res
, i
, i_classoid
));
15623 labels
[i
].objoid
= atooid(PQgetvalue(res
, i
, i_objoid
));
15624 labels
[i
].objsubid
= atoi(PQgetvalue(res
, i
, i_objsubid
));
15627 /* Do NOT free the PGresult since we are keeping pointers into it */
15628 destroyPQExpBuffer(query
);
15636 * write out to fout the declarations (not data) of a user-defined table
15639 dumpTable(Archive
*fout
, TableInfo
*tbinfo
)
15641 DumpOptions
*dopt
= fout
->dopt
;
15642 DumpId tableAclDumpId
= InvalidDumpId
;
15646 * noop if we are not dumping anything about this table, or if we are
15647 * doing a data-only dump
15649 if (!tbinfo
->dobj
.dump
|| dopt
->dataOnly
)
15652 if (tbinfo
->relkind
== RELKIND_SEQUENCE
)
15653 dumpSequence(fout
, tbinfo
);
15655 dumpTableSchema(fout
, tbinfo
);
15657 /* Handle the ACL here */
15658 namecopy
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
15659 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
15661 const char *objtype
=
15662 (tbinfo
->relkind
== RELKIND_SEQUENCE
) ? "SEQUENCE" : "TABLE";
15665 dumpACL(fout
, tbinfo
->dobj
.dumpId
, InvalidDumpId
,
15666 objtype
, namecopy
, NULL
,
15667 tbinfo
->dobj
.namespace->dobj
.name
, tbinfo
->rolname
,
15668 tbinfo
->relacl
, tbinfo
->rrelacl
,
15669 tbinfo
->initrelacl
, tbinfo
->initrrelacl
);
15673 * Handle column ACLs, if any. Note: we pull these with a separate query
15674 * rather than trying to fetch them during getTableAttrs, so that we won't
15675 * miss ACLs on system columns.
15677 if (fout
->remoteVersion
>= 80400 && tbinfo
->dobj
.dump
& DUMP_COMPONENT_ACL
)
15679 PQExpBuffer query
= createPQExpBuffer();
15683 if (fout
->remoteVersion
>= 90600)
15685 PQExpBuffer acl_subquery
= createPQExpBuffer();
15686 PQExpBuffer racl_subquery
= createPQExpBuffer();
15687 PQExpBuffer initacl_subquery
= createPQExpBuffer();
15688 PQExpBuffer initracl_subquery
= createPQExpBuffer();
15690 buildACLQueries(acl_subquery
, racl_subquery
, initacl_subquery
,
15691 initracl_subquery
, "at.attacl", "c.relowner", "'c'",
15692 dopt
->binary_upgrade
);
15694 appendPQExpBuffer(query
,
15695 "SELECT at.attname, "
15698 "%s AS initattacl, "
15699 "%s AS initrattacl "
15700 "FROM pg_catalog.pg_attribute at "
15701 "JOIN pg_catalog.pg_class c ON (at.attrelid = c.oid) "
15702 "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15703 "(at.attrelid = pip.objoid "
15704 "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15705 "AND at.attnum = pip.objsubid) "
15706 "WHERE at.attrelid = '%u'::pg_catalog.oid AND "
15707 "NOT at.attisdropped "
15709 "%s IS NOT NULL OR "
15710 "%s IS NOT NULL OR "
15711 "%s IS NOT NULL OR "
15713 "ORDER BY at.attnum",
15714 acl_subquery
->data
,
15715 racl_subquery
->data
,
15716 initacl_subquery
->data
,
15717 initracl_subquery
->data
,
15718 tbinfo
->dobj
.catId
.oid
,
15719 acl_subquery
->data
,
15720 racl_subquery
->data
,
15721 initacl_subquery
->data
,
15722 initracl_subquery
->data
);
15724 destroyPQExpBuffer(acl_subquery
);
15725 destroyPQExpBuffer(racl_subquery
);
15726 destroyPQExpBuffer(initacl_subquery
);
15727 destroyPQExpBuffer(initracl_subquery
);
15731 appendPQExpBuffer(query
,
15732 "SELECT attname, attacl, NULL as rattacl, "
15733 "NULL AS initattacl, NULL AS initrattacl "
15734 "FROM pg_catalog.pg_attribute "
15735 "WHERE attrelid = '%u'::pg_catalog.oid AND NOT attisdropped "
15736 "AND attacl IS NOT NULL "
15738 tbinfo
->dobj
.catId
.oid
);
15741 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
15743 for (i
= 0; i
< PQntuples(res
); i
++)
15745 char *attname
= PQgetvalue(res
, i
, 0);
15746 char *attacl
= PQgetvalue(res
, i
, 1);
15747 char *rattacl
= PQgetvalue(res
, i
, 2);
15748 char *initattacl
= PQgetvalue(res
, i
, 3);
15749 char *initrattacl
= PQgetvalue(res
, i
, 4);
15752 attnamecopy
= pg_strdup(fmtId(attname
));
15755 * Column's GRANT type is always TABLE. Each column ACL depends
15756 * on the table-level ACL, since we can restore column ACLs in
15757 * parallel but the table-level ACL has to be done first.
15759 dumpACL(fout
, tbinfo
->dobj
.dumpId
, tableAclDumpId
,
15760 "TABLE", namecopy
, attnamecopy
,
15761 tbinfo
->dobj
.namespace->dobj
.name
, tbinfo
->rolname
,
15762 attacl
, rattacl
, initattacl
, initrattacl
);
15766 destroyPQExpBuffer(query
);
15775 * Create the AS clause for a view or materialized view. The semicolon is
15776 * stripped because a materialized view must add a WITH NO DATA clause.
15778 * This returns a new buffer which must be freed by the caller.
15781 createViewAsClause(Archive
*fout
, TableInfo
*tbinfo
)
15783 PQExpBuffer query
= createPQExpBuffer();
15784 PQExpBuffer result
= createPQExpBuffer();
15788 /* Fetch the view definition */
15789 appendPQExpBuffer(query
,
15790 "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15791 tbinfo
->dobj
.catId
.oid
);
15793 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
15795 if (PQntuples(res
) != 1)
15797 if (PQntuples(res
) < 1)
15798 fatal("query to obtain definition of view \"%s\" returned no data",
15799 tbinfo
->dobj
.name
);
15801 fatal("query to obtain definition of view \"%s\" returned more than one definition",
15802 tbinfo
->dobj
.name
);
15805 len
= PQgetlength(res
, 0, 0);
15808 fatal("definition of view \"%s\" appears to be empty (length zero)",
15809 tbinfo
->dobj
.name
);
15811 /* Strip off the trailing semicolon so that other things may follow. */
15812 Assert(PQgetvalue(res
, 0, 0)[len
- 1] == ';');
15813 appendBinaryPQExpBuffer(result
, PQgetvalue(res
, 0, 0), len
- 1);
15816 destroyPQExpBuffer(query
);
15822 * Create a dummy AS clause for a view. This is used when the real view
15823 * definition has to be postponed because of circular dependencies.
15824 * We must duplicate the view's external properties -- column names and types
15825 * (including collation) -- so that it works for subsequent references.
15827 * This returns a new buffer which must be freed by the caller.
15830 createDummyViewAsClause(Archive
*fout
, TableInfo
*tbinfo
)
15832 PQExpBuffer result
= createPQExpBuffer();
15835 appendPQExpBufferStr(result
, "SELECT");
15837 for (j
= 0; j
< tbinfo
->numatts
; j
++)
15840 appendPQExpBufferChar(result
, ',');
15841 appendPQExpBufferStr(result
, "\n ");
15843 appendPQExpBuffer(result
, "NULL::%s", tbinfo
->atttypnames
[j
]);
15846 * Must add collation if not default for the type, because CREATE OR
15847 * REPLACE VIEW won't change it
15849 if (OidIsValid(tbinfo
->attcollation
[j
]))
15853 coll
= findCollationByOid(tbinfo
->attcollation
[j
]);
15855 appendPQExpBuffer(result
, " COLLATE %s",
15856 fmtQualifiedDumpable(coll
));
15859 appendPQExpBuffer(result
, " AS %s", fmtId(tbinfo
->attnames
[j
]));
15867 * write the declaration (not data) of one user-defined table or view
15870 dumpTableSchema(Archive
*fout
, TableInfo
*tbinfo
)
15872 DumpOptions
*dopt
= fout
->dopt
;
15873 PQExpBuffer q
= createPQExpBuffer();
15874 PQExpBuffer delq
= createPQExpBuffer();
15878 TableInfo
**parents
;
15879 int actual_atts
; /* number of attrs in this CREATE statement */
15880 const char *reltypename
;
15885 /* We had better have loaded per-column details about this table */
15886 Assert(tbinfo
->interesting
);
15888 qrelname
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
15889 qualrelname
= pg_strdup(fmtQualifiedDumpable(tbinfo
));
15891 if (tbinfo
->hasoids
)
15892 pg_log_warning("WITH OIDS is not supported anymore (table \"%s\")",
15895 if (dopt
->binary_upgrade
)
15896 binary_upgrade_set_type_oids_by_rel_oid(fout
, q
,
15897 tbinfo
->dobj
.catId
.oid
);
15899 /* Is it a table or a view? */
15900 if (tbinfo
->relkind
== RELKIND_VIEW
)
15902 PQExpBuffer result
;
15905 * Note: keep this code in sync with the is_view case in dumpRule()
15908 reltypename
= "VIEW";
15910 appendPQExpBuffer(delq
, "DROP VIEW %s;\n", qualrelname
);
15912 if (dopt
->binary_upgrade
)
15913 binary_upgrade_set_pg_class_oids(fout
, q
,
15914 tbinfo
->dobj
.catId
.oid
, false);
15916 appendPQExpBuffer(q
, "CREATE VIEW %s", qualrelname
);
15918 if (tbinfo
->dummy_view
)
15919 result
= createDummyViewAsClause(fout
, tbinfo
);
15922 if (nonemptyReloptions(tbinfo
->reloptions
))
15924 appendPQExpBufferStr(q
, " WITH (");
15925 appendReloptionsArrayAH(q
, tbinfo
->reloptions
, "", fout
);
15926 appendPQExpBufferChar(q
, ')');
15928 result
= createViewAsClause(fout
, tbinfo
);
15930 appendPQExpBuffer(q
, " AS\n%s", result
->data
);
15931 destroyPQExpBuffer(result
);
15933 if (tbinfo
->checkoption
!= NULL
&& !tbinfo
->dummy_view
)
15934 appendPQExpBuffer(q
, "\n WITH %s CHECK OPTION", tbinfo
->checkoption
);
15935 appendPQExpBufferStr(q
, ";\n");
15939 char *partkeydef
= NULL
;
15940 char *ftoptions
= NULL
;
15941 char *srvname
= NULL
;
15944 * Set reltypename, and collect any relkind-specific data that we
15945 * didn't fetch during getTables().
15947 switch (tbinfo
->relkind
)
15949 case RELKIND_PARTITIONED_TABLE
:
15951 PQExpBuffer query
= createPQExpBuffer();
15954 reltypename
= "TABLE";
15956 /* retrieve partition key definition */
15957 appendPQExpBuffer(query
,
15958 "SELECT pg_get_partkeydef('%u')",
15959 tbinfo
->dobj
.catId
.oid
);
15960 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
15961 partkeydef
= pg_strdup(PQgetvalue(res
, 0, 0));
15963 destroyPQExpBuffer(query
);
15966 case RELKIND_FOREIGN_TABLE
:
15968 PQExpBuffer query
= createPQExpBuffer();
15973 reltypename
= "FOREIGN TABLE";
15975 /* retrieve name of foreign server and generic options */
15976 appendPQExpBuffer(query
,
15977 "SELECT fs.srvname, "
15978 "pg_catalog.array_to_string(ARRAY("
15979 "SELECT pg_catalog.quote_ident(option_name) || "
15980 "' ' || pg_catalog.quote_literal(option_value) "
15981 "FROM pg_catalog.pg_options_to_table(ftoptions) "
15982 "ORDER BY option_name"
15983 "), E',\n ') AS ftoptions "
15984 "FROM pg_catalog.pg_foreign_table ft "
15985 "JOIN pg_catalog.pg_foreign_server fs "
15986 "ON (fs.oid = ft.ftserver) "
15987 "WHERE ft.ftrelid = '%u'",
15988 tbinfo
->dobj
.catId
.oid
);
15989 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
15990 i_srvname
= PQfnumber(res
, "srvname");
15991 i_ftoptions
= PQfnumber(res
, "ftoptions");
15992 srvname
= pg_strdup(PQgetvalue(res
, 0, i_srvname
));
15993 ftoptions
= pg_strdup(PQgetvalue(res
, 0, i_ftoptions
));
15995 destroyPQExpBuffer(query
);
15998 case RELKIND_MATVIEW
:
15999 reltypename
= "MATERIALIZED VIEW";
16002 reltypename
= "TABLE";
16006 numParents
= tbinfo
->numParents
;
16007 parents
= tbinfo
->parents
;
16009 appendPQExpBuffer(delq
, "DROP %s %s;\n", reltypename
, qualrelname
);
16011 if (dopt
->binary_upgrade
)
16012 binary_upgrade_set_pg_class_oids(fout
, q
,
16013 tbinfo
->dobj
.catId
.oid
, false);
16015 appendPQExpBuffer(q
, "CREATE %s%s %s",
16016 tbinfo
->relpersistence
== RELPERSISTENCE_UNLOGGED
?
16022 * Attach to type, if reloftype; except in case of a binary upgrade,
16023 * we dump the table normally and attach it to the type afterward.
16025 if (OidIsValid(tbinfo
->reloftype
) && !dopt
->binary_upgrade
)
16026 appendPQExpBuffer(q
, " OF %s",
16027 getFormattedTypeName(fout
, tbinfo
->reloftype
,
16030 if (tbinfo
->relkind
!= RELKIND_MATVIEW
)
16032 /* Dump the attributes */
16034 for (j
= 0; j
< tbinfo
->numatts
; j
++)
16037 * Normally, dump if it's locally defined in this table, and
16038 * not dropped. But for binary upgrade, we'll dump all the
16039 * columns, and then fix up the dropped and nonlocal cases
16042 if (shouldPrintColumn(dopt
, tbinfo
, j
))
16044 bool print_default
;
16045 bool print_notnull
;
16048 * Default value --- suppress if to be printed separately.
16050 print_default
= (tbinfo
->attrdefs
[j
] != NULL
&&
16051 !tbinfo
->attrdefs
[j
]->separate
);
16054 * Not Null constraint --- suppress if inherited, except
16055 * if partition, or in binary-upgrade case where that
16058 print_notnull
= (tbinfo
->notnull
[j
] &&
16059 (!tbinfo
->inhNotNull
[j
] ||
16060 tbinfo
->ispartition
|| dopt
->binary_upgrade
));
16063 * Skip column if fully defined by reloftype, except in
16066 if (OidIsValid(tbinfo
->reloftype
) &&
16067 !print_default
&& !print_notnull
&&
16068 !dopt
->binary_upgrade
)
16071 /* Format properly if not first attr */
16072 if (actual_atts
== 0)
16073 appendPQExpBufferStr(q
, " (");
16075 appendPQExpBufferChar(q
, ',');
16076 appendPQExpBufferStr(q
, "\n ");
16079 /* Attribute name */
16080 appendPQExpBufferStr(q
, fmtId(tbinfo
->attnames
[j
]));
16082 if (tbinfo
->attisdropped
[j
])
16085 * ALTER TABLE DROP COLUMN clears
16086 * pg_attribute.atttypid, so we will not have gotten a
16087 * valid type name; insert INTEGER as a stopgap. We'll
16088 * clean things up later.
16090 appendPQExpBufferStr(q
, " INTEGER /* dummy */");
16091 /* and skip to the next column */
16096 * Attribute type; print it except when creating a typed
16097 * table ('OF type_name'), but in binary-upgrade mode,
16098 * print it in that case too.
16100 if (dopt
->binary_upgrade
|| !OidIsValid(tbinfo
->reloftype
))
16102 appendPQExpBuffer(q
, " %s",
16103 tbinfo
->atttypnames
[j
]);
16108 if (tbinfo
->attgenerated
[j
] == ATTRIBUTE_GENERATED_STORED
)
16109 appendPQExpBuffer(q
, " GENERATED ALWAYS AS (%s) STORED",
16110 tbinfo
->attrdefs
[j
]->adef_expr
);
16112 appendPQExpBuffer(q
, " DEFAULT %s",
16113 tbinfo
->attrdefs
[j
]->adef_expr
);
16118 appendPQExpBufferStr(q
, " NOT NULL");
16120 /* Add collation if not default for the type */
16121 if (OidIsValid(tbinfo
->attcollation
[j
]))
16125 coll
= findCollationByOid(tbinfo
->attcollation
[j
]);
16127 appendPQExpBuffer(q
, " COLLATE %s",
16128 fmtQualifiedDumpable(coll
));
16134 * Add non-inherited CHECK constraints, if any.
16136 * For partitions, we need to include check constraints even if
16137 * they're not defined locally, because the ALTER TABLE ATTACH
16138 * PARTITION that we'll emit later expects the constraint to be
16139 * there. (No need to fix conislocal: ATTACH PARTITION does that)
16141 for (j
= 0; j
< tbinfo
->ncheck
; j
++)
16143 ConstraintInfo
*constr
= &(tbinfo
->checkexprs
[j
]);
16145 if (constr
->separate
||
16146 (!constr
->conislocal
&& !tbinfo
->ispartition
))
16149 if (actual_atts
== 0)
16150 appendPQExpBufferStr(q
, " (\n ");
16152 appendPQExpBufferStr(q
, ",\n ");
16154 appendPQExpBuffer(q
, "CONSTRAINT %s ",
16155 fmtId(constr
->dobj
.name
));
16156 appendPQExpBufferStr(q
, constr
->condef
);
16162 appendPQExpBufferStr(q
, "\n)");
16163 else if (!(OidIsValid(tbinfo
->reloftype
) && !dopt
->binary_upgrade
))
16166 * No attributes? we must have a parenthesized attribute list,
16167 * even though empty, when not using the OF TYPE syntax.
16169 appendPQExpBufferStr(q
, " (\n)");
16173 * Emit the INHERITS clause (not for partitions), except in
16174 * binary-upgrade mode.
16176 if (numParents
> 0 && !tbinfo
->ispartition
&&
16177 !dopt
->binary_upgrade
)
16179 appendPQExpBufferStr(q
, "\nINHERITS (");
16180 for (k
= 0; k
< numParents
; k
++)
16182 TableInfo
*parentRel
= parents
[k
];
16185 appendPQExpBufferStr(q
, ", ");
16186 appendPQExpBufferStr(q
, fmtQualifiedDumpable(parentRel
));
16188 appendPQExpBufferChar(q
, ')');
16191 if (tbinfo
->relkind
== RELKIND_PARTITIONED_TABLE
)
16192 appendPQExpBuffer(q
, "\nPARTITION BY %s", partkeydef
);
16194 if (tbinfo
->relkind
== RELKIND_FOREIGN_TABLE
)
16195 appendPQExpBuffer(q
, "\nSERVER %s", fmtId(srvname
));
16198 if (nonemptyReloptions(tbinfo
->reloptions
) ||
16199 nonemptyReloptions(tbinfo
->toast_reloptions
))
16201 bool addcomma
= false;
16203 appendPQExpBufferStr(q
, "\nWITH (");
16204 if (nonemptyReloptions(tbinfo
->reloptions
))
16207 appendReloptionsArrayAH(q
, tbinfo
->reloptions
, "", fout
);
16209 if (nonemptyReloptions(tbinfo
->toast_reloptions
))
16212 appendPQExpBufferStr(q
, ", ");
16213 appendReloptionsArrayAH(q
, tbinfo
->toast_reloptions
, "toast.",
16216 appendPQExpBufferChar(q
, ')');
16219 /* Dump generic options if any */
16220 if (ftoptions
&& ftoptions
[0])
16221 appendPQExpBuffer(q
, "\nOPTIONS (\n %s\n)", ftoptions
);
16224 * For materialized views, create the AS clause just like a view. At
16225 * this point, we always mark the view as not populated.
16227 if (tbinfo
->relkind
== RELKIND_MATVIEW
)
16229 PQExpBuffer result
;
16231 result
= createViewAsClause(fout
, tbinfo
);
16232 appendPQExpBuffer(q
, " AS\n%s\n WITH NO DATA;\n",
16234 destroyPQExpBuffer(result
);
16237 appendPQExpBufferStr(q
, ";\n");
16239 /* Materialized views can depend on extensions */
16240 if (tbinfo
->relkind
== RELKIND_MATVIEW
)
16241 append_depends_on_extension(fout
, q
, &tbinfo
->dobj
,
16242 "pg_catalog.pg_class",
16243 tbinfo
->relkind
== RELKIND_MATVIEW
?
16244 "MATERIALIZED VIEW" : "INDEX",
16248 * in binary upgrade mode, update the catalog with any missing values
16249 * that might be present.
16251 if (dopt
->binary_upgrade
)
16253 for (j
= 0; j
< tbinfo
->numatts
; j
++)
16255 if (tbinfo
->attmissingval
[j
][0] != '\0')
16257 appendPQExpBufferStr(q
, "\n-- set missing value.\n");
16258 appendPQExpBufferStr(q
,
16259 "SELECT pg_catalog.binary_upgrade_set_missing_value(");
16260 appendStringLiteralAH(q
, qualrelname
, fout
);
16261 appendPQExpBufferStr(q
, "::pg_catalog.regclass,");
16262 appendStringLiteralAH(q
, tbinfo
->attnames
[j
], fout
);
16263 appendPQExpBufferStr(q
, ",");
16264 appendStringLiteralAH(q
, tbinfo
->attmissingval
[j
], fout
);
16265 appendPQExpBufferStr(q
, ");\n\n");
16271 * To create binary-compatible heap files, we have to ensure the same
16272 * physical column order, including dropped columns, as in the
16273 * original. Therefore, we create dropped columns above and drop them
16274 * here, also updating their attlen/attalign values so that the
16275 * dropped column can be skipped properly. (We do not bother with
16276 * restoring the original attbyval setting.) Also, inheritance
16277 * relationships are set up by doing ALTER TABLE INHERIT rather than
16278 * using an INHERITS clause --- the latter would possibly mess up the
16279 * column order. That also means we have to take care about setting
16280 * attislocal correctly, plus fix up any inherited CHECK constraints.
16281 * Analogously, we set up typed tables using ALTER TABLE / OF here.
16283 * We process foreign and partitioned tables here, even though they
16284 * lack heap storage, because they can participate in inheritance
16285 * relationships and we want this stuff to be consistent across the
16286 * inheritance tree. We can exclude indexes, toast tables, sequences
16287 * and matviews, even though they have storage, because we don't
16288 * support altering or dropping columns in them, nor can they be part
16289 * of inheritance trees.
16291 if (dopt
->binary_upgrade
&&
16292 (tbinfo
->relkind
== RELKIND_RELATION
||
16293 tbinfo
->relkind
== RELKIND_FOREIGN_TABLE
||
16294 tbinfo
->relkind
== RELKIND_PARTITIONED_TABLE
))
16296 for (j
= 0; j
< tbinfo
->numatts
; j
++)
16298 if (tbinfo
->attisdropped
[j
])
16300 appendPQExpBufferStr(q
, "\n-- For binary upgrade, recreate dropped column.\n");
16301 appendPQExpBuffer(q
, "UPDATE pg_catalog.pg_attribute\n"
16302 "SET attlen = %d, "
16303 "attalign = '%c', attbyval = false\n"
16304 "WHERE attname = ",
16306 tbinfo
->attalign
[j
]);
16307 appendStringLiteralAH(q
, tbinfo
->attnames
[j
], fout
);
16308 appendPQExpBufferStr(q
, "\n AND attrelid = ");
16309 appendStringLiteralAH(q
, qualrelname
, fout
);
16310 appendPQExpBufferStr(q
, "::pg_catalog.regclass;\n");
16312 if (tbinfo
->relkind
== RELKIND_RELATION
||
16313 tbinfo
->relkind
== RELKIND_PARTITIONED_TABLE
)
16314 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16317 appendPQExpBuffer(q
, "ALTER FOREIGN TABLE ONLY %s ",
16319 appendPQExpBuffer(q
, "DROP COLUMN %s;\n",
16320 fmtId(tbinfo
->attnames
[j
]));
16322 else if (!tbinfo
->attislocal
[j
])
16324 appendPQExpBufferStr(q
, "\n-- For binary upgrade, recreate inherited column.\n");
16325 appendPQExpBufferStr(q
, "UPDATE pg_catalog.pg_attribute\n"
16326 "SET attislocal = false\n"
16327 "WHERE attname = ");
16328 appendStringLiteralAH(q
, tbinfo
->attnames
[j
], fout
);
16329 appendPQExpBufferStr(q
, "\n AND attrelid = ");
16330 appendStringLiteralAH(q
, qualrelname
, fout
);
16331 appendPQExpBufferStr(q
, "::pg_catalog.regclass;\n");
16336 * Add inherited CHECK constraints, if any.
16338 * For partitions, they were already dumped, and conislocal
16339 * doesn't need fixing.
16341 for (k
= 0; k
< tbinfo
->ncheck
; k
++)
16343 ConstraintInfo
*constr
= &(tbinfo
->checkexprs
[k
]);
16345 if (constr
->separate
|| constr
->conislocal
|| tbinfo
->ispartition
)
16348 appendPQExpBufferStr(q
, "\n-- For binary upgrade, set up inherited constraint.\n");
16349 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16351 appendPQExpBuffer(q
, " ADD CONSTRAINT %s ",
16352 fmtId(constr
->dobj
.name
));
16353 appendPQExpBuffer(q
, "%s;\n", constr
->condef
);
16354 appendPQExpBufferStr(q
, "UPDATE pg_catalog.pg_constraint\n"
16355 "SET conislocal = false\n"
16356 "WHERE contype = 'c' AND conname = ");
16357 appendStringLiteralAH(q
, constr
->dobj
.name
, fout
);
16358 appendPQExpBufferStr(q
, "\n AND conrelid = ");
16359 appendStringLiteralAH(q
, qualrelname
, fout
);
16360 appendPQExpBufferStr(q
, "::pg_catalog.regclass;\n");
16363 if (numParents
> 0 && !tbinfo
->ispartition
)
16365 appendPQExpBufferStr(q
, "\n-- For binary upgrade, set up inheritance this way.\n");
16366 for (k
= 0; k
< numParents
; k
++)
16368 TableInfo
*parentRel
= parents
[k
];
16370 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s INHERIT %s;\n",
16372 fmtQualifiedDumpable(parentRel
));
16376 if (OidIsValid(tbinfo
->reloftype
))
16378 appendPQExpBufferStr(q
, "\n-- For binary upgrade, set up typed tables this way.\n");
16379 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s OF %s;\n",
16381 getFormattedTypeName(fout
, tbinfo
->reloftype
,
16387 * For partitioned tables, emit the ATTACH PARTITION clause. Note
16388 * that we always want to create partitions this way instead of using
16389 * CREATE TABLE .. PARTITION OF, mainly to preserve a possible column
16390 * layout discrepancy with the parent, but also to ensure it gets the
16391 * correct tablespace setting if it differs from the parent's.
16393 if (tbinfo
->ispartition
)
16399 /* With partitions there can only be one parent */
16400 if (tbinfo
->numParents
!= 1)
16401 fatal("invalid number of parents %d for table \"%s\"",
16402 tbinfo
->numParents
, tbinfo
->dobj
.name
);
16404 q2
= createPQExpBuffer();
16406 /* Fetch the partition's partbound */
16407 appendPQExpBuffer(q2
,
16408 "SELECT pg_get_expr(c.relpartbound, c.oid) "
16410 "WHERE c.oid = '%u'",
16411 tbinfo
->dobj
.catId
.oid
);
16412 ares
= ExecuteSqlQueryForSingleRow(fout
, q2
->data
);
16413 partbound
= PQgetvalue(ares
, 0, 0);
16415 /* Perform ALTER TABLE on the parent */
16416 appendPQExpBuffer(q
,
16417 "ALTER TABLE ONLY %s ATTACH PARTITION %s %s;\n",
16418 fmtQualifiedDumpable(parents
[0]),
16419 qualrelname
, partbound
);
16422 destroyPQExpBuffer(q2
);
16426 * In binary_upgrade mode, arrange to restore the old relfrozenxid and
16427 * relminmxid of all vacuumable relations. (While vacuum.c processes
16428 * TOAST tables semi-independently, here we see them only as children
16429 * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
16430 * child toast table is handled below.)
16432 if (dopt
->binary_upgrade
&&
16433 (tbinfo
->relkind
== RELKIND_RELATION
||
16434 tbinfo
->relkind
== RELKIND_MATVIEW
))
16436 appendPQExpBufferStr(q
, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
16437 appendPQExpBuffer(q
, "UPDATE pg_catalog.pg_class\n"
16438 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16440 tbinfo
->frozenxid
, tbinfo
->minmxid
);
16441 appendStringLiteralAH(q
, qualrelname
, fout
);
16442 appendPQExpBufferStr(q
, "::pg_catalog.regclass;\n");
16444 if (tbinfo
->toast_oid
)
16447 * The toast table will have the same OID at restore, so we
16448 * can safely target it by OID.
16450 appendPQExpBufferStr(q
, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
16451 appendPQExpBuffer(q
, "UPDATE pg_catalog.pg_class\n"
16452 "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16453 "WHERE oid = '%u';\n",
16454 tbinfo
->toast_frozenxid
,
16455 tbinfo
->toast_minmxid
, tbinfo
->toast_oid
);
16460 * In binary_upgrade mode, restore matviews' populated status by
16461 * poking pg_class directly. This is pretty ugly, but we can't use
16462 * REFRESH MATERIALIZED VIEW since it's possible that some underlying
16463 * matview is not populated even though this matview is; in any case,
16464 * we want to transfer the matview's heap storage, not run REFRESH.
16466 if (dopt
->binary_upgrade
&& tbinfo
->relkind
== RELKIND_MATVIEW
&&
16467 tbinfo
->relispopulated
)
16469 appendPQExpBufferStr(q
, "\n-- For binary upgrade, mark materialized view as populated\n");
16470 appendPQExpBufferStr(q
, "UPDATE pg_catalog.pg_class\n"
16471 "SET relispopulated = 't'\n"
16473 appendStringLiteralAH(q
, qualrelname
, fout
);
16474 appendPQExpBufferStr(q
, "::pg_catalog.regclass;\n");
16478 * Dump additional per-column properties that we can't handle in the
16479 * main CREATE TABLE command.
16481 for (j
= 0; j
< tbinfo
->numatts
; j
++)
16483 /* None of this applies to dropped columns */
16484 if (tbinfo
->attisdropped
[j
])
16488 * If we didn't dump the column definition explicitly above, and
16489 * it is NOT NULL and did not inherit that property from a parent,
16490 * we have to mark it separately.
16492 if (!shouldPrintColumn(dopt
, tbinfo
, j
) &&
16493 tbinfo
->notnull
[j
] && !tbinfo
->inhNotNull
[j
])
16495 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16497 appendPQExpBuffer(q
, "ALTER COLUMN %s SET NOT NULL;\n",
16498 fmtId(tbinfo
->attnames
[j
]));
16502 * Dump per-column statistics information. We only issue an ALTER
16503 * TABLE statement if the attstattarget entry for this column is
16504 * non-negative (i.e. it's not the default value)
16506 if (tbinfo
->attstattarget
[j
] >= 0)
16508 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16510 appendPQExpBuffer(q
, "ALTER COLUMN %s ",
16511 fmtId(tbinfo
->attnames
[j
]));
16512 appendPQExpBuffer(q
, "SET STATISTICS %d;\n",
16513 tbinfo
->attstattarget
[j
]);
16517 * Dump per-column storage information. The statement is only
16518 * dumped if the storage has been changed from the type's default.
16520 if (tbinfo
->attstorage
[j
] != tbinfo
->typstorage
[j
])
16522 switch (tbinfo
->attstorage
[j
])
16528 storage
= "EXTERNAL";
16534 storage
= "EXTENDED";
16541 * Only dump the statement if it's a storage type we recognize
16543 if (storage
!= NULL
)
16545 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16547 appendPQExpBuffer(q
, "ALTER COLUMN %s ",
16548 fmtId(tbinfo
->attnames
[j
]));
16549 appendPQExpBuffer(q
, "SET STORAGE %s;\n",
16555 * Dump per-column attributes.
16557 if (tbinfo
->attoptions
[j
][0] != '\0')
16559 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16561 appendPQExpBuffer(q
, "ALTER COLUMN %s ",
16562 fmtId(tbinfo
->attnames
[j
]));
16563 appendPQExpBuffer(q
, "SET (%s);\n",
16564 tbinfo
->attoptions
[j
]);
16568 * Dump per-column fdw options.
16570 if (tbinfo
->relkind
== RELKIND_FOREIGN_TABLE
&&
16571 tbinfo
->attfdwoptions
[j
][0] != '\0')
16573 appendPQExpBuffer(q
, "ALTER FOREIGN TABLE %s ",
16575 appendPQExpBuffer(q
, "ALTER COLUMN %s ",
16576 fmtId(tbinfo
->attnames
[j
]));
16577 appendPQExpBuffer(q
, "OPTIONS (\n %s\n);\n",
16578 tbinfo
->attfdwoptions
[j
]);
16591 * dump properties we only have ALTER TABLE syntax for
16593 if ((tbinfo
->relkind
== RELKIND_RELATION
||
16594 tbinfo
->relkind
== RELKIND_PARTITIONED_TABLE
||
16595 tbinfo
->relkind
== RELKIND_MATVIEW
) &&
16596 tbinfo
->relreplident
!= REPLICA_IDENTITY_DEFAULT
)
16598 if (tbinfo
->relreplident
== REPLICA_IDENTITY_INDEX
)
16600 /* nothing to do, will be set when the index is dumped */
16602 else if (tbinfo
->relreplident
== REPLICA_IDENTITY_NOTHING
)
16604 appendPQExpBuffer(q
, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16607 else if (tbinfo
->relreplident
== REPLICA_IDENTITY_FULL
)
16609 appendPQExpBuffer(q
, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16614 if (tbinfo
->forcerowsec
)
16615 appendPQExpBuffer(q
, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16618 if (dopt
->binary_upgrade
)
16619 binary_upgrade_extension_member(q
, &tbinfo
->dobj
,
16620 reltypename
, qrelname
,
16621 tbinfo
->dobj
.namespace->dobj
.name
);
16623 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
16625 char *tableam
= NULL
;
16627 if (tbinfo
->relkind
== RELKIND_RELATION
||
16628 tbinfo
->relkind
== RELKIND_MATVIEW
)
16629 tableam
= tbinfo
->amname
;
16631 ArchiveEntry(fout
, tbinfo
->dobj
.catId
, tbinfo
->dobj
.dumpId
,
16632 ARCHIVE_OPTS(.tag
= tbinfo
->dobj
.name
,
16633 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
16634 .tablespace
= (tbinfo
->relkind
== RELKIND_VIEW
) ?
16635 NULL
: tbinfo
->reltablespace
,
16636 .tableam
= tableam
,
16637 .owner
= tbinfo
->rolname
,
16638 .description
= reltypename
,
16639 .section
= tbinfo
->postponed_def
?
16640 SECTION_POST_DATA
: SECTION_PRE_DATA
,
16641 .createStmt
= q
->data
,
16642 .dropStmt
= delq
->data
));
16645 /* Dump Table Comments */
16646 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
16647 dumpTableComment(fout
, tbinfo
, reltypename
);
16649 /* Dump Table Security Labels */
16650 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
16651 dumpTableSecLabel(fout
, tbinfo
, reltypename
);
16653 /* Dump comments on inlined table constraints */
16654 for (j
= 0; j
< tbinfo
->ncheck
; j
++)
16656 ConstraintInfo
*constr
= &(tbinfo
->checkexprs
[j
]);
16658 if (constr
->separate
|| !constr
->conislocal
)
16661 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
16662 dumpTableConstraintComment(fout
, constr
);
16665 destroyPQExpBuffer(q
);
16666 destroyPQExpBuffer(delq
);
16672 * dumpAttrDef --- dump an attribute's default-value declaration
16675 dumpAttrDef(Archive
*fout
, AttrDefInfo
*adinfo
)
16677 DumpOptions
*dopt
= fout
->dopt
;
16678 TableInfo
*tbinfo
= adinfo
->adtable
;
16679 int adnum
= adinfo
->adnum
;
16685 /* Skip if table definition not to be dumped */
16686 if (!tbinfo
->dobj
.dump
|| dopt
->dataOnly
)
16689 /* Skip if not "separate"; it was dumped in the table's definition */
16690 if (!adinfo
->separate
)
16693 q
= createPQExpBuffer();
16694 delq
= createPQExpBuffer();
16696 qualrelname
= pg_strdup(fmtQualifiedDumpable(tbinfo
));
16698 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s ",
16700 appendPQExpBuffer(q
, "ALTER COLUMN %s SET DEFAULT %s;\n",
16701 fmtId(tbinfo
->attnames
[adnum
- 1]),
16702 adinfo
->adef_expr
);
16704 appendPQExpBuffer(delq
, "ALTER TABLE %s ",
16706 appendPQExpBuffer(delq
, "ALTER COLUMN %s DROP DEFAULT;\n",
16707 fmtId(tbinfo
->attnames
[adnum
- 1]));
16709 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, tbinfo
->attnames
[adnum
- 1]);
16711 if (adinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
16712 ArchiveEntry(fout
, adinfo
->dobj
.catId
, adinfo
->dobj
.dumpId
,
16713 ARCHIVE_OPTS(.tag
= tag
,
16714 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
16715 .owner
= tbinfo
->rolname
,
16716 .description
= "DEFAULT",
16717 .section
= SECTION_PRE_DATA
,
16718 .createStmt
= q
->data
,
16719 .dropStmt
= delq
->data
));
16722 destroyPQExpBuffer(q
);
16723 destroyPQExpBuffer(delq
);
16728 * getAttrName: extract the correct name for an attribute
16730 * The array tblInfo->attnames[] only provides names of user attributes;
16731 * if a system attribute number is supplied, we have to fake it.
16732 * We also do a little bit of bounds checking for safety's sake.
16734 static const char *
16735 getAttrName(int attrnum
, TableInfo
*tblInfo
)
16737 if (attrnum
> 0 && attrnum
<= tblInfo
->numatts
)
16738 return tblInfo
->attnames
[attrnum
- 1];
16741 case SelfItemPointerAttributeNumber
:
16743 case MinTransactionIdAttributeNumber
:
16745 case MinCommandIdAttributeNumber
:
16747 case MaxTransactionIdAttributeNumber
:
16749 case MaxCommandIdAttributeNumber
:
16751 case TableOidAttributeNumber
:
16754 fatal("invalid column number %d for table \"%s\"",
16755 attrnum
, tblInfo
->dobj
.name
);
16756 return NULL
; /* keep compiler quiet */
16761 * write out to fout a user-defined index
16764 dumpIndex(Archive
*fout
, IndxInfo
*indxinfo
)
16766 DumpOptions
*dopt
= fout
->dopt
;
16767 TableInfo
*tbinfo
= indxinfo
->indextable
;
16768 bool is_constraint
= (indxinfo
->indexconstraint
!= 0);
16774 if (dopt
->dataOnly
)
16777 q
= createPQExpBuffer();
16778 delq
= createPQExpBuffer();
16780 qindxname
= pg_strdup(fmtId(indxinfo
->dobj
.name
));
16781 qqindxname
= pg_strdup(fmtQualifiedDumpable(indxinfo
));
16784 * If there's an associated constraint, don't dump the index per se, but
16785 * do dump any comment for it. (This is safe because dependency ordering
16786 * will have ensured the constraint is emitted first.) Note that the
16787 * emitted comment has to be shown as depending on the constraint, not the
16788 * index, in such cases.
16790 if (!is_constraint
)
16792 char *indstatcols
= indxinfo
->indstatcols
;
16793 char *indstatvals
= indxinfo
->indstatvals
;
16794 char **indstatcolsarray
= NULL
;
16795 char **indstatvalsarray
= NULL
;
16799 if (dopt
->binary_upgrade
)
16800 binary_upgrade_set_pg_class_oids(fout
, q
,
16801 indxinfo
->dobj
.catId
.oid
, true);
16803 /* Plain secondary index */
16804 appendPQExpBuffer(q
, "%s;\n", indxinfo
->indexdef
);
16807 * Append ALTER TABLE commands as needed to set properties that we
16808 * only have ALTER TABLE syntax for. Keep this in sync with the
16809 * similar code in dumpConstraint!
16812 /* If the index is clustered, we need to record that. */
16813 if (indxinfo
->indisclustered
)
16815 appendPQExpBuffer(q
, "\nALTER TABLE %s CLUSTER",
16816 fmtQualifiedDumpable(tbinfo
));
16817 /* index name is not qualified in this syntax */
16818 appendPQExpBuffer(q
, " ON %s;\n",
16823 * If the index has any statistics on some of its columns, generate
16824 * the associated ALTER INDEX queries.
16826 if (parsePGArray(indstatcols
, &indstatcolsarray
, &nstatcols
) &&
16827 parsePGArray(indstatvals
, &indstatvalsarray
, &nstatvals
) &&
16828 nstatcols
== nstatvals
)
16832 for (j
= 0; j
< nstatcols
; j
++)
16834 appendPQExpBuffer(q
, "ALTER INDEX %s ", qqindxname
);
16837 * Note that this is a column number, so no quotes should be
16840 appendPQExpBuffer(q
, "ALTER COLUMN %s ",
16841 indstatcolsarray
[j
]);
16842 appendPQExpBuffer(q
, "SET STATISTICS %s;\n",
16843 indstatvalsarray
[j
]);
16847 /* Indexes can depend on extensions */
16848 append_depends_on_extension(fout
, q
, &indxinfo
->dobj
,
16849 "pg_catalog.pg_class",
16850 "INDEX", qqindxname
);
16852 /* If the index defines identity, we need to record that. */
16853 if (indxinfo
->indisreplident
)
16855 appendPQExpBuffer(q
, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
16856 fmtQualifiedDumpable(tbinfo
));
16857 /* index name is not qualified in this syntax */
16858 appendPQExpBuffer(q
, " INDEX %s;\n",
16862 appendPQExpBuffer(delq
, "DROP INDEX %s;\n", qqindxname
);
16864 if (indxinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
16865 ArchiveEntry(fout
, indxinfo
->dobj
.catId
, indxinfo
->dobj
.dumpId
,
16866 ARCHIVE_OPTS(.tag
= indxinfo
->dobj
.name
,
16867 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
16868 .tablespace
= indxinfo
->tablespace
,
16869 .owner
= tbinfo
->rolname
,
16870 .description
= "INDEX",
16871 .section
= SECTION_POST_DATA
,
16872 .createStmt
= q
->data
,
16873 .dropStmt
= delq
->data
));
16875 if (indstatcolsarray
)
16876 free(indstatcolsarray
);
16877 if (indstatvalsarray
)
16878 free(indstatvalsarray
);
16881 /* Dump Index Comments */
16882 if (indxinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
16883 dumpComment(fout
, "INDEX", qindxname
,
16884 tbinfo
->dobj
.namespace->dobj
.name
,
16886 indxinfo
->dobj
.catId
, 0,
16887 is_constraint
? indxinfo
->indexconstraint
:
16888 indxinfo
->dobj
.dumpId
);
16890 destroyPQExpBuffer(q
);
16891 destroyPQExpBuffer(delq
);
16898 * write out to fout a partitioned-index attachment clause
16901 dumpIndexAttach(Archive
*fout
, IndexAttachInfo
*attachinfo
)
16903 if (fout
->dopt
->dataOnly
)
16906 if (attachinfo
->partitionIdx
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
16908 PQExpBuffer q
= createPQExpBuffer();
16910 appendPQExpBuffer(q
, "ALTER INDEX %s ",
16911 fmtQualifiedDumpable(attachinfo
->parentIdx
));
16912 appendPQExpBuffer(q
, "ATTACH PARTITION %s;\n",
16913 fmtQualifiedDumpable(attachinfo
->partitionIdx
));
16916 * There is no point in creating a drop query as the drop is done by
16917 * index drop. (If you think to change this, see also
16918 * _printTocEntry().) Although this object doesn't really have
16919 * ownership as such, set the owner field anyway to ensure that the
16920 * command is run by the correct role at restore time.
16922 ArchiveEntry(fout
, attachinfo
->dobj
.catId
, attachinfo
->dobj
.dumpId
,
16923 ARCHIVE_OPTS(.tag
= attachinfo
->dobj
.name
,
16924 .namespace = attachinfo
->dobj
.namespace->dobj
.name
,
16925 .owner
= attachinfo
->parentIdx
->indextable
->rolname
,
16926 .description
= "INDEX ATTACH",
16927 .section
= SECTION_POST_DATA
,
16928 .createStmt
= q
->data
));
16930 destroyPQExpBuffer(q
);
16935 * dumpStatisticsExt
16936 * write out to fout an extended statistics object
16939 dumpStatisticsExt(Archive
*fout
, StatsExtInfo
*statsextinfo
)
16941 DumpOptions
*dopt
= fout
->dopt
;
16945 char *qstatsextname
;
16949 /* Skip if not to be dumped */
16950 if (!statsextinfo
->dobj
.dump
|| dopt
->dataOnly
)
16953 q
= createPQExpBuffer();
16954 delq
= createPQExpBuffer();
16955 query
= createPQExpBuffer();
16957 qstatsextname
= pg_strdup(fmtId(statsextinfo
->dobj
.name
));
16959 appendPQExpBuffer(query
, "SELECT "
16960 "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
16961 statsextinfo
->dobj
.catId
.oid
);
16963 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
16965 stxdef
= PQgetvalue(res
, 0, 0);
16967 /* Result of pg_get_statisticsobjdef is complete except for semicolon */
16968 appendPQExpBuffer(q
, "%s;\n", stxdef
);
16970 appendPQExpBuffer(delq
, "DROP STATISTICS %s;\n",
16971 fmtQualifiedDumpable(statsextinfo
));
16973 if (statsextinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
16974 ArchiveEntry(fout
, statsextinfo
->dobj
.catId
,
16975 statsextinfo
->dobj
.dumpId
,
16976 ARCHIVE_OPTS(.tag
= statsextinfo
->dobj
.name
,
16977 .namespace = statsextinfo
->dobj
.namespace->dobj
.name
,
16978 .owner
= statsextinfo
->rolname
,
16979 .description
= "STATISTICS",
16980 .section
= SECTION_POST_DATA
,
16981 .createStmt
= q
->data
,
16982 .dropStmt
= delq
->data
));
16984 /* Dump Statistics Comments */
16985 if (statsextinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
16986 dumpComment(fout
, "STATISTICS", qstatsextname
,
16987 statsextinfo
->dobj
.namespace->dobj
.name
,
16988 statsextinfo
->rolname
,
16989 statsextinfo
->dobj
.catId
, 0,
16990 statsextinfo
->dobj
.dumpId
);
16993 destroyPQExpBuffer(q
);
16994 destroyPQExpBuffer(delq
);
16995 destroyPQExpBuffer(query
);
16996 free(qstatsextname
);
17001 * write out to fout a user-defined constraint
17004 dumpConstraint(Archive
*fout
, ConstraintInfo
*coninfo
)
17006 DumpOptions
*dopt
= fout
->dopt
;
17007 TableInfo
*tbinfo
= coninfo
->contable
;
17012 /* Skip if not to be dumped */
17013 if (!coninfo
->dobj
.dump
|| dopt
->dataOnly
)
17016 q
= createPQExpBuffer();
17017 delq
= createPQExpBuffer();
17019 if (coninfo
->contype
== 'p' ||
17020 coninfo
->contype
== 'u' ||
17021 coninfo
->contype
== 'x')
17023 /* Index-related constraint */
17024 IndxInfo
*indxinfo
;
17027 indxinfo
= (IndxInfo
*) findObjectByDumpId(coninfo
->conindex
);
17029 if (indxinfo
== NULL
)
17030 fatal("missing index for constraint \"%s\"",
17031 coninfo
->dobj
.name
);
17033 if (dopt
->binary_upgrade
)
17034 binary_upgrade_set_pg_class_oids(fout
, q
,
17035 indxinfo
->dobj
.catId
.oid
, true);
17037 appendPQExpBuffer(q
, "ALTER TABLE ONLY %s\n",
17038 fmtQualifiedDumpable(tbinfo
));
17039 appendPQExpBuffer(q
, " ADD CONSTRAINT %s ",
17040 fmtId(coninfo
->dobj
.name
));
17042 if (coninfo
->condef
)
17044 /* pg_get_constraintdef should have provided everything */
17045 appendPQExpBuffer(q
, "%s;\n", coninfo
->condef
);
17049 appendPQExpBuffer(q
, "%s (",
17050 coninfo
->contype
== 'p' ? "PRIMARY KEY" : "UNIQUE");
17051 for (k
= 0; k
< indxinfo
->indnkeyattrs
; k
++)
17053 int indkey
= (int) indxinfo
->indkeys
[k
];
17054 const char *attname
;
17056 if (indkey
== InvalidAttrNumber
)
17058 attname
= getAttrName(indkey
, tbinfo
);
17060 appendPQExpBuffer(q
, "%s%s",
17061 (k
== 0) ? "" : ", ",
17065 if (indxinfo
->indnkeyattrs
< indxinfo
->indnattrs
)
17066 appendPQExpBuffer(q
, ") INCLUDE (");
17068 for (k
= indxinfo
->indnkeyattrs
; k
< indxinfo
->indnattrs
; k
++)
17070 int indkey
= (int) indxinfo
->indkeys
[k
];
17071 const char *attname
;
17073 if (indkey
== InvalidAttrNumber
)
17075 attname
= getAttrName(indkey
, tbinfo
);
17077 appendPQExpBuffer(q
, "%s%s",
17078 (k
== indxinfo
->indnkeyattrs
) ? "" : ", ",
17082 appendPQExpBufferChar(q
, ')');
17084 if (nonemptyReloptions(indxinfo
->indreloptions
))
17086 appendPQExpBufferStr(q
, " WITH (");
17087 appendReloptionsArrayAH(q
, indxinfo
->indreloptions
, "", fout
);
17088 appendPQExpBufferChar(q
, ')');
17091 if (coninfo
->condeferrable
)
17093 appendPQExpBufferStr(q
, " DEFERRABLE");
17094 if (coninfo
->condeferred
)
17095 appendPQExpBufferStr(q
, " INITIALLY DEFERRED");
17098 appendPQExpBufferStr(q
, ";\n");
17102 * Append ALTER TABLE commands as needed to set properties that we
17103 * only have ALTER TABLE syntax for. Keep this in sync with the
17104 * similar code in dumpIndex!
17107 /* If the index is clustered, we need to record that. */
17108 if (indxinfo
->indisclustered
)
17110 appendPQExpBuffer(q
, "\nALTER TABLE %s CLUSTER",
17111 fmtQualifiedDumpable(tbinfo
));
17112 /* index name is not qualified in this syntax */
17113 appendPQExpBuffer(q
, " ON %s;\n",
17114 fmtId(indxinfo
->dobj
.name
));
17117 /* If the index defines identity, we need to record that. */
17118 if (indxinfo
->indisreplident
)
17120 appendPQExpBuffer(q
, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
17121 fmtQualifiedDumpable(tbinfo
));
17122 /* index name is not qualified in this syntax */
17123 appendPQExpBuffer(q
, " INDEX %s;\n",
17124 fmtId(indxinfo
->dobj
.name
));
17127 /* Indexes can depend on extensions */
17128 append_depends_on_extension(fout
, q
, &indxinfo
->dobj
,
17129 "pg_catalog.pg_class", "INDEX",
17130 fmtQualifiedDumpable(indxinfo
));
17132 appendPQExpBuffer(delq
, "ALTER TABLE ONLY %s ",
17133 fmtQualifiedDumpable(tbinfo
));
17134 appendPQExpBuffer(delq
, "DROP CONSTRAINT %s;\n",
17135 fmtId(coninfo
->dobj
.name
));
17137 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, coninfo
->dobj
.name
);
17139 if (coninfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17140 ArchiveEntry(fout
, coninfo
->dobj
.catId
, coninfo
->dobj
.dumpId
,
17141 ARCHIVE_OPTS(.tag
= tag
,
17142 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17143 .tablespace
= indxinfo
->tablespace
,
17144 .owner
= tbinfo
->rolname
,
17145 .description
= "CONSTRAINT",
17146 .section
= SECTION_POST_DATA
,
17147 .createStmt
= q
->data
,
17148 .dropStmt
= delq
->data
));
17150 else if (coninfo
->contype
== 'f')
17155 * Foreign keys on partitioned tables are always declared as
17156 * inheriting to partitions; for all other cases, emit them as
17157 * applying ONLY directly to the named table, because that's how they
17158 * work for regular inherited tables.
17160 only
= tbinfo
->relkind
== RELKIND_PARTITIONED_TABLE
? "" : "ONLY ";
17163 * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
17164 * current table data is not processed
17166 appendPQExpBuffer(q
, "ALTER TABLE %s%s\n",
17167 only
, fmtQualifiedDumpable(tbinfo
));
17168 appendPQExpBuffer(q
, " ADD CONSTRAINT %s %s;\n",
17169 fmtId(coninfo
->dobj
.name
),
17172 appendPQExpBuffer(delq
, "ALTER TABLE %s%s ",
17173 only
, fmtQualifiedDumpable(tbinfo
));
17174 appendPQExpBuffer(delq
, "DROP CONSTRAINT %s;\n",
17175 fmtId(coninfo
->dobj
.name
));
17177 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, coninfo
->dobj
.name
);
17179 if (coninfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17180 ArchiveEntry(fout
, coninfo
->dobj
.catId
, coninfo
->dobj
.dumpId
,
17181 ARCHIVE_OPTS(.tag
= tag
,
17182 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17183 .owner
= tbinfo
->rolname
,
17184 .description
= "FK CONSTRAINT",
17185 .section
= SECTION_POST_DATA
,
17186 .createStmt
= q
->data
,
17187 .dropStmt
= delq
->data
));
17189 else if (coninfo
->contype
== 'c' && tbinfo
)
17191 /* CHECK constraint on a table */
17193 /* Ignore if not to be dumped separately, or if it was inherited */
17194 if (coninfo
->separate
&& coninfo
->conislocal
)
17196 /* not ONLY since we want it to propagate to children */
17197 appendPQExpBuffer(q
, "ALTER TABLE %s\n",
17198 fmtQualifiedDumpable(tbinfo
));
17199 appendPQExpBuffer(q
, " ADD CONSTRAINT %s %s;\n",
17200 fmtId(coninfo
->dobj
.name
),
17203 appendPQExpBuffer(delq
, "ALTER TABLE %s ",
17204 fmtQualifiedDumpable(tbinfo
));
17205 appendPQExpBuffer(delq
, "DROP CONSTRAINT %s;\n",
17206 fmtId(coninfo
->dobj
.name
));
17208 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, coninfo
->dobj
.name
);
17210 if (coninfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17211 ArchiveEntry(fout
, coninfo
->dobj
.catId
, coninfo
->dobj
.dumpId
,
17212 ARCHIVE_OPTS(.tag
= tag
,
17213 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17214 .owner
= tbinfo
->rolname
,
17215 .description
= "CHECK CONSTRAINT",
17216 .section
= SECTION_POST_DATA
,
17217 .createStmt
= q
->data
,
17218 .dropStmt
= delq
->data
));
17221 else if (coninfo
->contype
== 'c' && tbinfo
== NULL
)
17223 /* CHECK constraint on a domain */
17224 TypeInfo
*tyinfo
= coninfo
->condomain
;
17226 /* Ignore if not to be dumped separately */
17227 if (coninfo
->separate
)
17229 appendPQExpBuffer(q
, "ALTER DOMAIN %s\n",
17230 fmtQualifiedDumpable(tyinfo
));
17231 appendPQExpBuffer(q
, " ADD CONSTRAINT %s %s;\n",
17232 fmtId(coninfo
->dobj
.name
),
17235 appendPQExpBuffer(delq
, "ALTER DOMAIN %s ",
17236 fmtQualifiedDumpable(tyinfo
));
17237 appendPQExpBuffer(delq
, "DROP CONSTRAINT %s;\n",
17238 fmtId(coninfo
->dobj
.name
));
17240 tag
= psprintf("%s %s", tyinfo
->dobj
.name
, coninfo
->dobj
.name
);
17242 if (coninfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17243 ArchiveEntry(fout
, coninfo
->dobj
.catId
, coninfo
->dobj
.dumpId
,
17244 ARCHIVE_OPTS(.tag
= tag
,
17245 .namespace = tyinfo
->dobj
.namespace->dobj
.name
,
17246 .owner
= tyinfo
->rolname
,
17247 .description
= "CHECK CONSTRAINT",
17248 .section
= SECTION_POST_DATA
,
17249 .createStmt
= q
->data
,
17250 .dropStmt
= delq
->data
));
17255 fatal("unrecognized constraint type: %c",
17259 /* Dump Constraint Comments --- only works for table constraints */
17260 if (tbinfo
&& coninfo
->separate
&&
17261 coninfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
17262 dumpTableConstraintComment(fout
, coninfo
);
17265 destroyPQExpBuffer(q
);
17266 destroyPQExpBuffer(delq
);
17270 * dumpTableConstraintComment --- dump a constraint's comment if any
17272 * This is split out because we need the function in two different places
17273 * depending on whether the constraint is dumped as part of CREATE TABLE
17274 * or as a separate ALTER command.
17277 dumpTableConstraintComment(Archive
*fout
, ConstraintInfo
*coninfo
)
17279 TableInfo
*tbinfo
= coninfo
->contable
;
17280 PQExpBuffer conprefix
= createPQExpBuffer();
17283 qtabname
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
17285 appendPQExpBuffer(conprefix
, "CONSTRAINT %s ON",
17286 fmtId(coninfo
->dobj
.name
));
17288 if (coninfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
17289 dumpComment(fout
, conprefix
->data
, qtabname
,
17290 tbinfo
->dobj
.namespace->dobj
.name
,
17292 coninfo
->dobj
.catId
, 0,
17293 coninfo
->separate
? coninfo
->dobj
.dumpId
: tbinfo
->dobj
.dumpId
);
17295 destroyPQExpBuffer(conprefix
);
17300 * findLastBuiltinOid_V71 -
17302 * find the last built in oid
17304 * For 7.1 through 8.0, we do this by retrieving datlastsysoid from the
17305 * pg_database entry for the current database. (Note: current_database()
17306 * requires 7.3; pg_dump requires 8.0 now.)
17309 findLastBuiltinOid_V71(Archive
*fout
)
17314 res
= ExecuteSqlQueryForSingleRow(fout
,
17315 "SELECT datlastsysoid FROM pg_database WHERE datname = current_database()");
17316 last_oid
= atooid(PQgetvalue(res
, 0, PQfnumber(res
, "datlastsysoid")));
17324 * write the declaration (not data) of one user-defined sequence
17327 dumpSequence(Archive
*fout
, TableInfo
*tbinfo
)
17329 DumpOptions
*dopt
= fout
->dopt
;
17339 int64 default_minv
,
17343 PQExpBuffer query
= createPQExpBuffer();
17344 PQExpBuffer delqry
= createPQExpBuffer();
17347 qseqname
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
17349 if (fout
->remoteVersion
>= 100000)
17351 appendPQExpBuffer(query
,
17352 "SELECT format_type(seqtypid, NULL), "
17353 "seqstart, seqincrement, "
17355 "seqcache, seqcycle "
17356 "FROM pg_catalog.pg_sequence "
17357 "WHERE seqrelid = '%u'::oid",
17358 tbinfo
->dobj
.catId
.oid
);
17360 else if (fout
->remoteVersion
>= 80400)
17363 * Before PostgreSQL 10, sequence metadata is in the sequence itself.
17365 * Note: it might seem that 'bigint' potentially needs to be
17366 * schema-qualified, but actually that's a keyword.
17368 appendPQExpBuffer(query
,
17369 "SELECT 'bigint' AS sequence_type, "
17370 "start_value, increment_by, max_value, min_value, "
17371 "cache_value, is_cycled FROM %s",
17372 fmtQualifiedDumpable(tbinfo
));
17376 appendPQExpBuffer(query
,
17377 "SELECT 'bigint' AS sequence_type, "
17378 "0 AS start_value, increment_by, max_value, min_value, "
17379 "cache_value, is_cycled FROM %s",
17380 fmtQualifiedDumpable(tbinfo
));
17383 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
17385 if (PQntuples(res
) != 1)
17387 pg_log_error(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17388 "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17390 tbinfo
->dobj
.name
, PQntuples(res
));
17394 seqtype
= PQgetvalue(res
, 0, 0);
17395 startv
= PQgetvalue(res
, 0, 1);
17396 incby
= PQgetvalue(res
, 0, 2);
17397 maxv
= PQgetvalue(res
, 0, 3);
17398 minv
= PQgetvalue(res
, 0, 4);
17399 cache
= PQgetvalue(res
, 0, 5);
17400 cycled
= (strcmp(PQgetvalue(res
, 0, 6), "t") == 0);
17402 /* Calculate default limits for a sequence of this type */
17403 is_ascending
= (incby
[0] != '-');
17404 if (strcmp(seqtype
, "smallint") == 0)
17406 default_minv
= is_ascending
? 1 : PG_INT16_MIN
;
17407 default_maxv
= is_ascending
? PG_INT16_MAX
: -1;
17409 else if (strcmp(seqtype
, "integer") == 0)
17411 default_minv
= is_ascending
? 1 : PG_INT32_MIN
;
17412 default_maxv
= is_ascending
? PG_INT32_MAX
: -1;
17414 else if (strcmp(seqtype
, "bigint") == 0)
17416 default_minv
= is_ascending
? 1 : PG_INT64_MIN
;
17417 default_maxv
= is_ascending
? PG_INT64_MAX
: -1;
17421 fatal("unrecognized sequence type: %s", seqtype
);
17422 default_minv
= default_maxv
= 0; /* keep compiler quiet */
17426 * 64-bit strtol() isn't very portable, so convert the limits to strings
17427 * and compare that way.
17429 snprintf(bufm
, sizeof(bufm
), INT64_FORMAT
, default_minv
);
17430 snprintf(bufx
, sizeof(bufx
), INT64_FORMAT
, default_maxv
);
17432 /* Don't print minv/maxv if they match the respective default limit */
17433 if (strcmp(minv
, bufm
) == 0)
17435 if (strcmp(maxv
, bufx
) == 0)
17439 * Identity sequences are not to be dropped separately.
17441 if (!tbinfo
->is_identity_sequence
)
17443 appendPQExpBuffer(delqry
, "DROP SEQUENCE %s;\n",
17444 fmtQualifiedDumpable(tbinfo
));
17447 resetPQExpBuffer(query
);
17449 if (dopt
->binary_upgrade
)
17451 binary_upgrade_set_pg_class_oids(fout
, query
,
17452 tbinfo
->dobj
.catId
.oid
, false);
17453 binary_upgrade_set_type_oids_by_rel_oid(fout
, query
,
17454 tbinfo
->dobj
.catId
.oid
);
17457 if (tbinfo
->is_identity_sequence
)
17459 TableInfo
*owning_tab
= findTableByOid(tbinfo
->owning_tab
);
17461 appendPQExpBuffer(query
,
17463 fmtQualifiedDumpable(owning_tab
));
17464 appendPQExpBuffer(query
,
17465 "ALTER COLUMN %s ADD GENERATED ",
17466 fmtId(owning_tab
->attnames
[tbinfo
->owning_col
- 1]));
17467 if (owning_tab
->attidentity
[tbinfo
->owning_col
- 1] == ATTRIBUTE_IDENTITY_ALWAYS
)
17468 appendPQExpBuffer(query
, "ALWAYS");
17469 else if (owning_tab
->attidentity
[tbinfo
->owning_col
- 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT
)
17470 appendPQExpBuffer(query
, "BY DEFAULT");
17471 appendPQExpBuffer(query
, " AS IDENTITY (\n SEQUENCE NAME %s\n",
17472 fmtQualifiedDumpable(tbinfo
));
17476 appendPQExpBuffer(query
,
17477 "CREATE SEQUENCE %s\n",
17478 fmtQualifiedDumpable(tbinfo
));
17480 if (strcmp(seqtype
, "bigint") != 0)
17481 appendPQExpBuffer(query
, " AS %s\n", seqtype
);
17484 if (fout
->remoteVersion
>= 80400)
17485 appendPQExpBuffer(query
, " START WITH %s\n", startv
);
17487 appendPQExpBuffer(query
, " INCREMENT BY %s\n", incby
);
17490 appendPQExpBuffer(query
, " MINVALUE %s\n", minv
);
17492 appendPQExpBufferStr(query
, " NO MINVALUE\n");
17495 appendPQExpBuffer(query
, " MAXVALUE %s\n", maxv
);
17497 appendPQExpBufferStr(query
, " NO MAXVALUE\n");
17499 appendPQExpBuffer(query
,
17501 cache
, (cycled
? "\n CYCLE" : ""));
17503 if (tbinfo
->is_identity_sequence
)
17504 appendPQExpBufferStr(query
, "\n);\n");
17506 appendPQExpBufferStr(query
, ";\n");
17508 /* binary_upgrade: no need to clear TOAST table oid */
17510 if (dopt
->binary_upgrade
)
17511 binary_upgrade_extension_member(query
, &tbinfo
->dobj
,
17512 "SEQUENCE", qseqname
,
17513 tbinfo
->dobj
.namespace->dobj
.name
);
17515 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17516 ArchiveEntry(fout
, tbinfo
->dobj
.catId
, tbinfo
->dobj
.dumpId
,
17517 ARCHIVE_OPTS(.tag
= tbinfo
->dobj
.name
,
17518 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17519 .owner
= tbinfo
->rolname
,
17520 .description
= "SEQUENCE",
17521 .section
= SECTION_PRE_DATA
,
17522 .createStmt
= query
->data
,
17523 .dropStmt
= delqry
->data
));
17526 * If the sequence is owned by a table column, emit the ALTER for it as a
17527 * separate TOC entry immediately following the sequence's own entry. It's
17528 * OK to do this rather than using full sorting logic, because the
17529 * dependency that tells us it's owned will have forced the table to be
17530 * created first. We can't just include the ALTER in the TOC entry
17531 * because it will fail if we haven't reassigned the sequence owner to
17532 * match the table's owner.
17534 * We need not schema-qualify the table reference because both sequence
17535 * and table must be in the same schema.
17537 if (OidIsValid(tbinfo
->owning_tab
) && !tbinfo
->is_identity_sequence
)
17539 TableInfo
*owning_tab
= findTableByOid(tbinfo
->owning_tab
);
17541 if (owning_tab
== NULL
)
17542 fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
17543 tbinfo
->owning_tab
, tbinfo
->dobj
.catId
.oid
);
17545 if (owning_tab
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17547 resetPQExpBuffer(query
);
17548 appendPQExpBuffer(query
, "ALTER SEQUENCE %s",
17549 fmtQualifiedDumpable(tbinfo
));
17550 appendPQExpBuffer(query
, " OWNED BY %s",
17551 fmtQualifiedDumpable(owning_tab
));
17552 appendPQExpBuffer(query
, ".%s;\n",
17553 fmtId(owning_tab
->attnames
[tbinfo
->owning_col
- 1]));
17555 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17556 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
17557 ARCHIVE_OPTS(.tag
= tbinfo
->dobj
.name
,
17558 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17559 .owner
= tbinfo
->rolname
,
17560 .description
= "SEQUENCE OWNED BY",
17561 .section
= SECTION_PRE_DATA
,
17562 .createStmt
= query
->data
,
17563 .deps
= &(tbinfo
->dobj
.dumpId
),
17568 /* Dump Sequence Comments and Security Labels */
17569 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
17570 dumpComment(fout
, "SEQUENCE", qseqname
,
17571 tbinfo
->dobj
.namespace->dobj
.name
, tbinfo
->rolname
,
17572 tbinfo
->dobj
.catId
, 0, tbinfo
->dobj
.dumpId
);
17574 if (tbinfo
->dobj
.dump
& DUMP_COMPONENT_SECLABEL
)
17575 dumpSecLabel(fout
, "SEQUENCE", qseqname
,
17576 tbinfo
->dobj
.namespace->dobj
.name
, tbinfo
->rolname
,
17577 tbinfo
->dobj
.catId
, 0, tbinfo
->dobj
.dumpId
);
17581 destroyPQExpBuffer(query
);
17582 destroyPQExpBuffer(delqry
);
17588 * write the data of one user-defined sequence
17591 dumpSequenceData(Archive
*fout
, TableDataInfo
*tdinfo
)
17593 TableInfo
*tbinfo
= tdinfo
->tdtable
;
17597 PQExpBuffer query
= createPQExpBuffer();
17599 appendPQExpBuffer(query
,
17600 "SELECT last_value, is_called FROM %s",
17601 fmtQualifiedDumpable(tbinfo
));
17603 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
17605 if (PQntuples(res
) != 1)
17607 pg_log_error(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17608 "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17610 tbinfo
->dobj
.name
, PQntuples(res
));
17614 last
= PQgetvalue(res
, 0, 0);
17615 called
= (strcmp(PQgetvalue(res
, 0, 1), "t") == 0);
17617 resetPQExpBuffer(query
);
17618 appendPQExpBufferStr(query
, "SELECT pg_catalog.setval(");
17619 appendStringLiteralAH(query
, fmtQualifiedDumpable(tbinfo
), fout
);
17620 appendPQExpBuffer(query
, ", %s, %s);\n",
17621 last
, (called
? "true" : "false"));
17623 if (tdinfo
->dobj
.dump
& DUMP_COMPONENT_DATA
)
17624 ArchiveEntry(fout
, nilCatalogId
, createDumpId(),
17625 ARCHIVE_OPTS(.tag
= tbinfo
->dobj
.name
,
17626 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17627 .owner
= tbinfo
->rolname
,
17628 .description
= "SEQUENCE SET",
17629 .section
= SECTION_DATA
,
17630 .createStmt
= query
->data
,
17631 .deps
= &(tbinfo
->dobj
.dumpId
),
17636 destroyPQExpBuffer(query
);
17641 * write the declaration of one user-defined table trigger
17644 dumpTrigger(Archive
*fout
, TriggerInfo
*tginfo
)
17646 DumpOptions
*dopt
= fout
->dopt
;
17647 TableInfo
*tbinfo
= tginfo
->tgtable
;
17649 PQExpBuffer delqry
;
17650 PQExpBuffer trigprefix
;
17651 PQExpBuffer trigidentity
;
17660 * we needn't check dobj.dump because TriggerInfo wouldn't have been
17661 * created in the first place for non-dumpable triggers
17663 if (dopt
->dataOnly
)
17666 query
= createPQExpBuffer();
17667 delqry
= createPQExpBuffer();
17668 trigprefix
= createPQExpBuffer();
17669 trigidentity
= createPQExpBuffer();
17671 qtabname
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
17673 appendPQExpBuffer(trigidentity
, "%s ", fmtId(tginfo
->dobj
.name
));
17674 appendPQExpBuffer(trigidentity
, "ON %s", fmtQualifiedDumpable(tbinfo
));
17676 appendPQExpBuffer(delqry
, "DROP TRIGGER %s;\n", trigidentity
->data
);
17680 appendPQExpBuffer(query
, "%s;\n", tginfo
->tgdef
);
17684 if (tginfo
->tgisconstraint
)
17686 appendPQExpBufferStr(query
, "CREATE CONSTRAINT TRIGGER ");
17687 appendPQExpBufferStr(query
, fmtId(tginfo
->tgconstrname
));
17691 appendPQExpBufferStr(query
, "CREATE TRIGGER ");
17692 appendPQExpBufferStr(query
, fmtId(tginfo
->dobj
.name
));
17694 appendPQExpBufferStr(query
, "\n ");
17697 if (TRIGGER_FOR_BEFORE(tginfo
->tgtype
))
17698 appendPQExpBufferStr(query
, "BEFORE");
17699 else if (TRIGGER_FOR_AFTER(tginfo
->tgtype
))
17700 appendPQExpBufferStr(query
, "AFTER");
17701 else if (TRIGGER_FOR_INSTEAD(tginfo
->tgtype
))
17702 appendPQExpBufferStr(query
, "INSTEAD OF");
17705 pg_log_error("unexpected tgtype value: %d", tginfo
->tgtype
);
17710 if (TRIGGER_FOR_INSERT(tginfo
->tgtype
))
17712 appendPQExpBufferStr(query
, " INSERT");
17715 if (TRIGGER_FOR_DELETE(tginfo
->tgtype
))
17718 appendPQExpBufferStr(query
, " OR DELETE");
17720 appendPQExpBufferStr(query
, " DELETE");
17723 if (TRIGGER_FOR_UPDATE(tginfo
->tgtype
))
17726 appendPQExpBufferStr(query
, " OR UPDATE");
17728 appendPQExpBufferStr(query
, " UPDATE");
17731 if (TRIGGER_FOR_TRUNCATE(tginfo
->tgtype
))
17734 appendPQExpBufferStr(query
, " OR TRUNCATE");
17736 appendPQExpBufferStr(query
, " TRUNCATE");
17739 appendPQExpBuffer(query
, " ON %s\n",
17740 fmtQualifiedDumpable(tbinfo
));
17742 if (tginfo
->tgisconstraint
)
17744 if (OidIsValid(tginfo
->tgconstrrelid
))
17746 /* regclass output is already quoted */
17747 appendPQExpBuffer(query
, " FROM %s\n ",
17748 tginfo
->tgconstrrelname
);
17750 if (!tginfo
->tgdeferrable
)
17751 appendPQExpBufferStr(query
, "NOT ");
17752 appendPQExpBufferStr(query
, "DEFERRABLE INITIALLY ");
17753 if (tginfo
->tginitdeferred
)
17754 appendPQExpBufferStr(query
, "DEFERRED\n");
17756 appendPQExpBufferStr(query
, "IMMEDIATE\n");
17759 if (TRIGGER_FOR_ROW(tginfo
->tgtype
))
17760 appendPQExpBufferStr(query
, " FOR EACH ROW\n ");
17762 appendPQExpBufferStr(query
, " FOR EACH STATEMENT\n ");
17764 /* regproc output is already sufficiently quoted */
17765 appendPQExpBuffer(query
, "EXECUTE FUNCTION %s(",
17768 tgargs
= (char *) PQunescapeBytea((unsigned char *) tginfo
->tgargs
,
17771 for (findx
= 0; findx
< tginfo
->tgnargs
; findx
++)
17773 /* find the embedded null that terminates this trigger argument */
17774 size_t tlen
= strlen(p
);
17776 if (p
+ tlen
>= tgargs
+ lentgargs
)
17778 /* hm, not found before end of bytea value... */
17779 pg_log_error("invalid argument string (%s) for trigger \"%s\" on table \"%s\"",
17782 tbinfo
->dobj
.name
);
17787 appendPQExpBufferStr(query
, ", ");
17788 appendStringLiteralAH(query
, p
, fout
);
17792 appendPQExpBufferStr(query
, ");\n");
17795 /* Triggers can depend on extensions */
17796 append_depends_on_extension(fout
, query
, &tginfo
->dobj
,
17797 "pg_catalog.pg_trigger", "TRIGGER",
17798 trigidentity
->data
);
17800 if (tginfo
->tgisinternal
)
17803 * Triggers marked internal only appear here because their 'tgenabled'
17804 * flag differs from its parent's. The trigger is created already, so
17805 * remove the CREATE and replace it with an ALTER. (Clear out the
17806 * DROP query too, so that pg_dump --create does not cause errors.)
17808 resetPQExpBuffer(query
);
17809 resetPQExpBuffer(delqry
);
17810 appendPQExpBuffer(query
, "\nALTER %sTABLE %s ",
17811 tbinfo
->relkind
== RELKIND_FOREIGN_TABLE
? "FOREIGN " : "",
17812 fmtQualifiedDumpable(tbinfo
));
17813 switch (tginfo
->tgenabled
)
17817 appendPQExpBufferStr(query
, "DISABLE");
17821 appendPQExpBufferStr(query
, "ENABLE");
17824 appendPQExpBufferStr(query
, "ENABLE REPLICA");
17827 appendPQExpBufferStr(query
, "ENABLE ALWAYS");
17830 appendPQExpBuffer(query
, " TRIGGER %s;\n",
17831 fmtId(tginfo
->dobj
.name
));
17833 else if (tginfo
->tgenabled
!= 't' && tginfo
->tgenabled
!= 'O')
17835 appendPQExpBuffer(query
, "\nALTER TABLE %s ",
17836 fmtQualifiedDumpable(tbinfo
));
17837 switch (tginfo
->tgenabled
)
17841 appendPQExpBufferStr(query
, "DISABLE");
17844 appendPQExpBufferStr(query
, "ENABLE ALWAYS");
17847 appendPQExpBufferStr(query
, "ENABLE REPLICA");
17850 appendPQExpBufferStr(query
, "ENABLE");
17853 appendPQExpBuffer(query
, " TRIGGER %s;\n",
17854 fmtId(tginfo
->dobj
.name
));
17857 appendPQExpBuffer(trigprefix
, "TRIGGER %s ON",
17858 fmtId(tginfo
->dobj
.name
));
17860 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, tginfo
->dobj
.name
);
17862 if (tginfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17863 ArchiveEntry(fout
, tginfo
->dobj
.catId
, tginfo
->dobj
.dumpId
,
17864 ARCHIVE_OPTS(.tag
= tag
,
17865 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
17866 .owner
= tbinfo
->rolname
,
17867 .description
= "TRIGGER",
17868 .section
= SECTION_POST_DATA
,
17869 .createStmt
= query
->data
,
17870 .dropStmt
= delqry
->data
));
17872 if (tginfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
17873 dumpComment(fout
, trigprefix
->data
, qtabname
,
17874 tbinfo
->dobj
.namespace->dobj
.name
, tbinfo
->rolname
,
17875 tginfo
->dobj
.catId
, 0, tginfo
->dobj
.dumpId
);
17878 destroyPQExpBuffer(query
);
17879 destroyPQExpBuffer(delqry
);
17880 destroyPQExpBuffer(trigprefix
);
17881 destroyPQExpBuffer(trigidentity
);
17887 * write the declaration of one user-defined event trigger
17890 dumpEventTrigger(Archive
*fout
, EventTriggerInfo
*evtinfo
)
17892 DumpOptions
*dopt
= fout
->dopt
;
17894 PQExpBuffer delqry
;
17897 /* Skip if not to be dumped */
17898 if (!evtinfo
->dobj
.dump
|| dopt
->dataOnly
)
17901 query
= createPQExpBuffer();
17902 delqry
= createPQExpBuffer();
17904 qevtname
= pg_strdup(fmtId(evtinfo
->dobj
.name
));
17906 appendPQExpBufferStr(query
, "CREATE EVENT TRIGGER ");
17907 appendPQExpBufferStr(query
, qevtname
);
17908 appendPQExpBufferStr(query
, " ON ");
17909 appendPQExpBufferStr(query
, fmtId(evtinfo
->evtevent
));
17911 if (strcmp("", evtinfo
->evttags
) != 0)
17913 appendPQExpBufferStr(query
, "\n WHEN TAG IN (");
17914 appendPQExpBufferStr(query
, evtinfo
->evttags
);
17915 appendPQExpBufferChar(query
, ')');
17918 appendPQExpBufferStr(query
, "\n EXECUTE FUNCTION ");
17919 appendPQExpBufferStr(query
, evtinfo
->evtfname
);
17920 appendPQExpBufferStr(query
, "();\n");
17922 if (evtinfo
->evtenabled
!= 'O')
17924 appendPQExpBuffer(query
, "\nALTER EVENT TRIGGER %s ",
17926 switch (evtinfo
->evtenabled
)
17929 appendPQExpBufferStr(query
, "DISABLE");
17932 appendPQExpBufferStr(query
, "ENABLE ALWAYS");
17935 appendPQExpBufferStr(query
, "ENABLE REPLICA");
17938 appendPQExpBufferStr(query
, "ENABLE");
17941 appendPQExpBufferStr(query
, ";\n");
17944 appendPQExpBuffer(delqry
, "DROP EVENT TRIGGER %s;\n",
17947 if (dopt
->binary_upgrade
)
17948 binary_upgrade_extension_member(query
, &evtinfo
->dobj
,
17949 "EVENT TRIGGER", qevtname
, NULL
);
17951 if (evtinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
17952 ArchiveEntry(fout
, evtinfo
->dobj
.catId
, evtinfo
->dobj
.dumpId
,
17953 ARCHIVE_OPTS(.tag
= evtinfo
->dobj
.name
,
17954 .owner
= evtinfo
->evtowner
,
17955 .description
= "EVENT TRIGGER",
17956 .section
= SECTION_POST_DATA
,
17957 .createStmt
= query
->data
,
17958 .dropStmt
= delqry
->data
));
17960 if (evtinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
17961 dumpComment(fout
, "EVENT TRIGGER", qevtname
,
17962 NULL
, evtinfo
->evtowner
,
17963 evtinfo
->dobj
.catId
, 0, evtinfo
->dobj
.dumpId
);
17965 destroyPQExpBuffer(query
);
17966 destroyPQExpBuffer(delqry
);
17975 dumpRule(Archive
*fout
, RuleInfo
*rinfo
)
17977 DumpOptions
*dopt
= fout
->dopt
;
17978 TableInfo
*tbinfo
= rinfo
->ruletable
;
17982 PQExpBuffer delcmd
;
17983 PQExpBuffer ruleprefix
;
17988 /* Skip if not to be dumped */
17989 if (!rinfo
->dobj
.dump
|| dopt
->dataOnly
)
17993 * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
17994 * we do not want to dump it as a separate object.
17996 if (!rinfo
->separate
)
18000 * If it's an ON SELECT rule, we want to print it as a view definition,
18001 * instead of a rule.
18003 is_view
= (rinfo
->ev_type
== '1' && rinfo
->is_instead
);
18005 query
= createPQExpBuffer();
18006 cmd
= createPQExpBuffer();
18007 delcmd
= createPQExpBuffer();
18008 ruleprefix
= createPQExpBuffer();
18010 qtabname
= pg_strdup(fmtId(tbinfo
->dobj
.name
));
18014 PQExpBuffer result
;
18017 * We need OR REPLACE here because we'll be replacing a dummy view.
18018 * Otherwise this should look largely like the regular view dump code.
18020 appendPQExpBuffer(cmd
, "CREATE OR REPLACE VIEW %s",
18021 fmtQualifiedDumpable(tbinfo
));
18022 if (nonemptyReloptions(tbinfo
->reloptions
))
18024 appendPQExpBufferStr(cmd
, " WITH (");
18025 appendReloptionsArrayAH(cmd
, tbinfo
->reloptions
, "", fout
);
18026 appendPQExpBufferChar(cmd
, ')');
18028 result
= createViewAsClause(fout
, tbinfo
);
18029 appendPQExpBuffer(cmd
, " AS\n%s", result
->data
);
18030 destroyPQExpBuffer(result
);
18031 if (tbinfo
->checkoption
!= NULL
)
18032 appendPQExpBuffer(cmd
, "\n WITH %s CHECK OPTION",
18033 tbinfo
->checkoption
);
18034 appendPQExpBufferStr(cmd
, ";\n");
18038 /* In the rule case, just print pg_get_ruledef's result verbatim */
18039 appendPQExpBuffer(query
,
18040 "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
18041 rinfo
->dobj
.catId
.oid
);
18043 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
18045 if (PQntuples(res
) != 1)
18047 pg_log_error("query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
18048 rinfo
->dobj
.name
, tbinfo
->dobj
.name
);
18052 printfPQExpBuffer(cmd
, "%s\n", PQgetvalue(res
, 0, 0));
18058 * Add the command to alter the rules replication firing semantics if it
18059 * differs from the default.
18061 if (rinfo
->ev_enabled
!= 'O')
18063 appendPQExpBuffer(cmd
, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo
));
18064 switch (rinfo
->ev_enabled
)
18067 appendPQExpBuffer(cmd
, "ENABLE ALWAYS RULE %s;\n",
18068 fmtId(rinfo
->dobj
.name
));
18071 appendPQExpBuffer(cmd
, "ENABLE REPLICA RULE %s;\n",
18072 fmtId(rinfo
->dobj
.name
));
18075 appendPQExpBuffer(cmd
, "DISABLE RULE %s;\n",
18076 fmtId(rinfo
->dobj
.name
));
18084 * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
18085 * REPLACE VIEW to replace the rule with something with minimal
18088 PQExpBuffer result
;
18090 appendPQExpBuffer(delcmd
, "CREATE OR REPLACE VIEW %s",
18091 fmtQualifiedDumpable(tbinfo
));
18092 result
= createDummyViewAsClause(fout
, tbinfo
);
18093 appendPQExpBuffer(delcmd
, " AS\n%s;\n", result
->data
);
18094 destroyPQExpBuffer(result
);
18098 appendPQExpBuffer(delcmd
, "DROP RULE %s ",
18099 fmtId(rinfo
->dobj
.name
));
18100 appendPQExpBuffer(delcmd
, "ON %s;\n",
18101 fmtQualifiedDumpable(tbinfo
));
18104 appendPQExpBuffer(ruleprefix
, "RULE %s ON",
18105 fmtId(rinfo
->dobj
.name
));
18107 tag
= psprintf("%s %s", tbinfo
->dobj
.name
, rinfo
->dobj
.name
);
18109 if (rinfo
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
)
18110 ArchiveEntry(fout
, rinfo
->dobj
.catId
, rinfo
->dobj
.dumpId
,
18111 ARCHIVE_OPTS(.tag
= tag
,
18112 .namespace = tbinfo
->dobj
.namespace->dobj
.name
,
18113 .owner
= tbinfo
->rolname
,
18114 .description
= "RULE",
18115 .section
= SECTION_POST_DATA
,
18116 .createStmt
= cmd
->data
,
18117 .dropStmt
= delcmd
->data
));
18119 /* Dump rule comments */
18120 if (rinfo
->dobj
.dump
& DUMP_COMPONENT_COMMENT
)
18121 dumpComment(fout
, ruleprefix
->data
, qtabname
,
18122 tbinfo
->dobj
.namespace->dobj
.name
,
18124 rinfo
->dobj
.catId
, 0, rinfo
->dobj
.dumpId
);
18127 destroyPQExpBuffer(query
);
18128 destroyPQExpBuffer(cmd
);
18129 destroyPQExpBuffer(delcmd
);
18130 destroyPQExpBuffer(ruleprefix
);
18135 * getExtensionMembership --- obtain extension membership data
18137 * We need to identify objects that are extension members as soon as they're
18138 * loaded, so that we can correctly determine whether they need to be dumped.
18139 * Generally speaking, extension member objects will get marked as *not* to
18140 * be dumped, as they will be recreated by the single CREATE EXTENSION
18141 * command. However, in binary upgrade mode we still need to dump the members
18145 getExtensionMembership(Archive
*fout
, ExtensionInfo extinfo
[],
18156 ExtensionMemberId
*extmembers
;
18157 ExtensionInfo
*ext
;
18159 /* Nothing to do if no extensions */
18160 if (numExtensions
== 0)
18163 query
= createPQExpBuffer();
18165 /* refclassid constraint is redundant but may speed the search */
18166 appendPQExpBufferStr(query
, "SELECT "
18167 "classid, objid, refobjid "
18169 "WHERE refclassid = 'pg_extension'::regclass "
18170 "AND deptype = 'e' "
18173 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
18175 ntups
= PQntuples(res
);
18177 i_classid
= PQfnumber(res
, "classid");
18178 i_objid
= PQfnumber(res
, "objid");
18179 i_refobjid
= PQfnumber(res
, "refobjid");
18181 extmembers
= (ExtensionMemberId
*) pg_malloc(ntups
* sizeof(ExtensionMemberId
));
18185 * Accumulate data into extmembers[].
18187 * Since we ordered the SELECT by referenced ID, we can expect that
18188 * multiple entries for the same extension will appear together; this
18189 * saves on searches.
18193 for (i
= 0; i
< ntups
; i
++)
18198 objId
.tableoid
= atooid(PQgetvalue(res
, i
, i_classid
));
18199 objId
.oid
= atooid(PQgetvalue(res
, i
, i_objid
));
18200 extId
= atooid(PQgetvalue(res
, i
, i_refobjid
));
18203 ext
->dobj
.catId
.oid
!= extId
)
18204 ext
= findExtensionByOid(extId
);
18208 /* shouldn't happen */
18209 pg_log_warning("could not find referenced extension %u", extId
);
18213 extmembers
[nextmembers
].catId
= objId
;
18214 extmembers
[nextmembers
].ext
= ext
;
18220 /* Remember the data for use later */
18221 setExtensionMembership(extmembers
, nextmembers
);
18223 destroyPQExpBuffer(query
);
18227 * processExtensionTables --- deal with extension configuration tables
18229 * There are two parts to this process:
18231 * 1. Identify and create dump records for extension configuration tables.
18233 * Extensions can mark tables as "configuration", which means that the user
18234 * is able and expected to modify those tables after the extension has been
18235 * loaded. For these tables, we dump out only the data- the structure is
18236 * expected to be handled at CREATE EXTENSION time, including any indexes or
18237 * foreign keys, which brings us to-
18239 * 2. Record FK dependencies between configuration tables.
18241 * Due to the FKs being created at CREATE EXTENSION time and therefore before
18242 * the data is loaded, we have to work out what the best order for reloading
18243 * the data is, to avoid FK violations when the tables are restored. This is
18244 * not perfect- we can't handle circular dependencies and if any exist they
18245 * will cause an invalid dump to be produced (though at least all of the data
18246 * is included for a user to manually restore). This is currently documented
18247 * but perhaps we can provide a better solution in the future.
18250 processExtensionTables(Archive
*fout
, ExtensionInfo extinfo
[],
18253 DumpOptions
*dopt
= fout
->dopt
;
18261 /* Nothing to do if no extensions */
18262 if (numExtensions
== 0)
18266 * Identify extension configuration tables and create TableDataInfo
18267 * objects for them, ensuring their data will be dumped even though the
18268 * tables themselves won't be.
18270 * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
18271 * user data in a configuration table is treated like schema data. This
18272 * seems appropriate since system data in a config table would get
18273 * reloaded by CREATE EXTENSION.
18275 for (i
= 0; i
< numExtensions
; i
++)
18277 ExtensionInfo
*curext
= &(extinfo
[i
]);
18278 char *extconfig
= curext
->extconfig
;
18279 char *extcondition
= curext
->extcondition
;
18280 char **extconfigarray
= NULL
;
18281 char **extconditionarray
= NULL
;
18283 int nconditionitems
;
18285 if (parsePGArray(extconfig
, &extconfigarray
, &nconfigitems
) &&
18286 parsePGArray(extcondition
, &extconditionarray
, &nconditionitems
) &&
18287 nconfigitems
== nconditionitems
)
18291 for (j
= 0; j
< nconfigitems
; j
++)
18293 TableInfo
*configtbl
;
18294 Oid configtbloid
= atooid(extconfigarray
[j
]);
18296 curext
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
;
18298 configtbl
= findTableByOid(configtbloid
);
18299 if (configtbl
== NULL
)
18303 * Tables of not-to-be-dumped extensions shouldn't be dumped
18304 * unless the table or its schema is explicitly included
18306 if (!(curext
->dobj
.dump
& DUMP_COMPONENT_DEFINITION
))
18308 /* check table explicitly requested */
18309 if (table_include_oids
.head
!= NULL
&&
18310 simple_oid_list_member(&table_include_oids
,
18314 /* check table's schema explicitly requested */
18315 if (configtbl
->dobj
.namespace->dobj
.dump
&
18316 DUMP_COMPONENT_DATA
)
18320 /* check table excluded by an exclusion switch */
18321 if (table_exclude_oids
.head
!= NULL
&&
18322 simple_oid_list_member(&table_exclude_oids
,
18326 /* check schema excluded by an exclusion switch */
18327 if (simple_oid_list_member(&schema_exclude_oids
,
18328 configtbl
->dobj
.namespace->dobj
.catId
.oid
))
18333 makeTableDataInfo(dopt
, configtbl
);
18334 if (configtbl
->dataObj
!= NULL
)
18336 if (strlen(extconditionarray
[j
]) > 0)
18337 configtbl
->dataObj
->filtercond
= pg_strdup(extconditionarray
[j
]);
18342 if (extconfigarray
)
18343 free(extconfigarray
);
18344 if (extconditionarray
)
18345 free(extconditionarray
);
18349 * Now that all the TableInfoData objects have been created for all the
18350 * extensions, check their FK dependencies and register them to try and
18351 * dump the data out in an order that they can be restored in.
18353 * Note that this is not a problem for user tables as their FKs are
18354 * recreated after the data has been loaded.
18357 query
= createPQExpBuffer();
18359 printfPQExpBuffer(query
,
18360 "SELECT conrelid, confrelid "
18361 "FROM pg_constraint "
18362 "JOIN pg_depend ON (objid = confrelid) "
18363 "WHERE contype = 'f' "
18364 "AND refclassid = 'pg_extension'::regclass "
18365 "AND classid = 'pg_class'::regclass;");
18367 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
18368 ntups
= PQntuples(res
);
18370 i_conrelid
= PQfnumber(res
, "conrelid");
18371 i_confrelid
= PQfnumber(res
, "confrelid");
18373 /* Now get the dependencies and register them */
18374 for (i
= 0; i
< ntups
; i
++)
18378 TableInfo
*reftable
,
18381 conrelid
= atooid(PQgetvalue(res
, i
, i_conrelid
));
18382 confrelid
= atooid(PQgetvalue(res
, i
, i_confrelid
));
18383 contable
= findTableByOid(conrelid
);
18384 reftable
= findTableByOid(confrelid
);
18386 if (reftable
== NULL
||
18387 reftable
->dataObj
== NULL
||
18388 contable
== NULL
||
18389 contable
->dataObj
== NULL
)
18393 * Make referencing TABLE_DATA object depend on the referenced table's
18394 * TABLE_DATA object.
18396 addObjectDependency(&contable
->dataObj
->dobj
,
18397 reftable
->dataObj
->dobj
.dumpId
);
18400 destroyPQExpBuffer(query
);
18404 * getDependencies --- obtain available dependency data
18407 getDependencies(Archive
*fout
)
18418 DumpableObject
*dobj
,
18421 pg_log_info("reading dependency data");
18423 query
= createPQExpBuffer();
18426 * Messy query to collect the dependency data we need. Note that we
18427 * ignore the sub-object column, so that dependencies of or on a column
18428 * look the same as dependencies of or on a whole table.
18430 * PIN dependencies aren't interesting, and EXTENSION dependencies were
18431 * already processed by getExtensionMembership.
18433 appendPQExpBufferStr(query
, "SELECT "
18434 "classid, objid, refclassid, refobjid, deptype "
18436 "WHERE deptype != 'p' AND deptype != 'e'\n");
18439 * Since we don't treat pg_amop entries as separate DumpableObjects, we
18440 * have to translate their dependencies into dependencies of their parent
18441 * opfamily. Ignore internal dependencies though, as those will point to
18442 * their parent opclass, which we needn't consider here (and if we did,
18443 * it'd just result in circular dependencies). Also, "loose" opfamily
18444 * entries will have dependencies on their parent opfamily, which we
18445 * should drop since they'd likewise become useless self-dependencies.
18446 * (But be sure to keep deps on *other* opfamilies; see amopsortfamily.)
18448 * Skip this for pre-8.3 source servers: pg_opfamily doesn't exist there,
18449 * and the (known) cases where it would matter to have these dependencies
18450 * can't arise anyway.
18452 if (fout
->remoteVersion
>= 80300)
18454 appendPQExpBufferStr(query
, "UNION ALL\n"
18455 "SELECT 'pg_opfamily'::regclass AS classid, amopfamily AS objid, refclassid, refobjid, deptype "
18456 "FROM pg_depend d, pg_amop o "
18457 "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18458 "classid = 'pg_amop'::regclass AND objid = o.oid "
18459 "AND NOT (refclassid = 'pg_opfamily'::regclass AND amopfamily = refobjid)\n");
18461 /* Likewise for pg_amproc entries */
18462 appendPQExpBufferStr(query
, "UNION ALL\n"
18463 "SELECT 'pg_opfamily'::regclass AS classid, amprocfamily AS objid, refclassid, refobjid, deptype "
18464 "FROM pg_depend d, pg_amproc p "
18465 "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18466 "classid = 'pg_amproc'::regclass AND objid = p.oid "
18467 "AND NOT (refclassid = 'pg_opfamily'::regclass AND amprocfamily = refobjid)\n");
18470 /* Sort the output for efficiency below */
18471 appendPQExpBufferStr(query
, "ORDER BY 1,2");
18473 res
= ExecuteSqlQuery(fout
, query
->data
, PGRES_TUPLES_OK
);
18475 ntups
= PQntuples(res
);
18477 i_classid
= PQfnumber(res
, "classid");
18478 i_objid
= PQfnumber(res
, "objid");
18479 i_refclassid
= PQfnumber(res
, "refclassid");
18480 i_refobjid
= PQfnumber(res
, "refobjid");
18481 i_deptype
= PQfnumber(res
, "deptype");
18484 * Since we ordered the SELECT by referencing ID, we can expect that
18485 * multiple entries for the same object will appear together; this saves
18490 for (i
= 0; i
< ntups
; i
++)
18493 CatalogId refobjId
;
18496 objId
.tableoid
= atooid(PQgetvalue(res
, i
, i_classid
));
18497 objId
.oid
= atooid(PQgetvalue(res
, i
, i_objid
));
18498 refobjId
.tableoid
= atooid(PQgetvalue(res
, i
, i_refclassid
));
18499 refobjId
.oid
= atooid(PQgetvalue(res
, i
, i_refobjid
));
18500 deptype
= *(PQgetvalue(res
, i
, i_deptype
));
18502 if (dobj
== NULL
||
18503 dobj
->catId
.tableoid
!= objId
.tableoid
||
18504 dobj
->catId
.oid
!= objId
.oid
)
18505 dobj
= findObjectByCatalogId(objId
);
18508 * Failure to find objects mentioned in pg_depend is not unexpected,
18509 * since for example we don't collect info about TOAST tables.
18514 pg_log_warning("no referencing object %u %u",
18515 objId
.tableoid
, objId
.oid
);
18520 refdobj
= findObjectByCatalogId(refobjId
);
18522 if (refdobj
== NULL
)
18525 pg_log_warning("no referenced object %u %u",
18526 refobjId
.tableoid
, refobjId
.oid
);
18532 * For 'x' dependencies, mark the object for later; we still add the
18533 * normal dependency, for possible ordering purposes. Currently
18534 * pg_dump_sort.c knows to put extensions ahead of all object types
18535 * that could possibly depend on them, but this is safer.
18537 if (deptype
== 'x')
18538 dobj
->depends_on_ext
= true;
18541 * Ordinarily, table rowtypes have implicit dependencies on their
18542 * tables. However, for a composite type the implicit dependency goes
18543 * the other way in pg_depend; which is the right thing for DROP but
18544 * it doesn't produce the dependency ordering we need. So in that one
18545 * case, we reverse the direction of the dependency.
18547 if (deptype
== 'i' &&
18548 dobj
->objType
== DO_TABLE
&&
18549 refdobj
->objType
== DO_TYPE
)
18550 addObjectDependency(refdobj
, dobj
->dumpId
);
18553 addObjectDependency(dobj
, refdobj
->dumpId
);
18558 destroyPQExpBuffer(query
);
18563 * createBoundaryObjects - create dummy DumpableObjects to represent
18564 * dump section boundaries.
18566 static DumpableObject
*
18567 createBoundaryObjects(void)
18569 DumpableObject
*dobjs
;
18571 dobjs
= (DumpableObject
*) pg_malloc(2 * sizeof(DumpableObject
));
18573 dobjs
[0].objType
= DO_PRE_DATA_BOUNDARY
;
18574 dobjs
[0].catId
= nilCatalogId
;
18575 AssignDumpId(dobjs
+ 0);
18576 dobjs
[0].name
= pg_strdup("PRE-DATA BOUNDARY");
18578 dobjs
[1].objType
= DO_POST_DATA_BOUNDARY
;
18579 dobjs
[1].catId
= nilCatalogId
;
18580 AssignDumpId(dobjs
+ 1);
18581 dobjs
[1].name
= pg_strdup("POST-DATA BOUNDARY");
18587 * addBoundaryDependencies - add dependencies as needed to enforce the dump
18588 * section boundaries.
18591 addBoundaryDependencies(DumpableObject
**dobjs
, int numObjs
,
18592 DumpableObject
*boundaryObjs
)
18594 DumpableObject
*preDataBound
= boundaryObjs
+ 0;
18595 DumpableObject
*postDataBound
= boundaryObjs
+ 1;
18598 for (i
= 0; i
< numObjs
; i
++)
18600 DumpableObject
*dobj
= dobjs
[i
];
18603 * The classification of object types here must match the SECTION_xxx
18604 * values assigned during subsequent ArchiveEntry calls!
18606 switch (dobj
->objType
)
18611 case DO_SHELL_TYPE
:
18615 case DO_ACCESS_METHOD
:
18619 case DO_CONVERSION
:
18624 case DO_DUMMY_TYPE
:
18627 case DO_TSTEMPLATE
:
18630 case DO_FOREIGN_SERVER
:
18633 /* Pre-data objects: must come before the pre-data boundary */
18634 addObjectDependency(preDataBound
, dobj
->dumpId
);
18636 case DO_TABLE_DATA
:
18637 case DO_SEQUENCE_SET
:
18639 /* Data objects: must come between the boundaries */
18640 addObjectDependency(dobj
, preDataBound
->dumpId
);
18641 addObjectDependency(postDataBound
, dobj
->dumpId
);
18644 case DO_INDEX_ATTACH
:
18646 case DO_REFRESH_MATVIEW
:
18648 case DO_EVENT_TRIGGER
:
18649 case DO_DEFAULT_ACL
:
18651 case DO_PUBLICATION
:
18652 case DO_PUBLICATION_REL
:
18653 case DO_SUBSCRIPTION
:
18654 /* Post-data objects: must come after the post-data boundary */
18655 addObjectDependency(dobj
, postDataBound
->dumpId
);
18658 /* Rules are post-data, but only if dumped separately */
18659 if (((RuleInfo
*) dobj
)->separate
)
18660 addObjectDependency(dobj
, postDataBound
->dumpId
);
18662 case DO_CONSTRAINT
:
18663 case DO_FK_CONSTRAINT
:
18664 /* Constraints are post-data, but only if dumped separately */
18665 if (((ConstraintInfo
*) dobj
)->separate
)
18666 addObjectDependency(dobj
, postDataBound
->dumpId
);
18668 case DO_PRE_DATA_BOUNDARY
:
18669 /* nothing to do */
18671 case DO_POST_DATA_BOUNDARY
:
18672 /* must come after the pre-data boundary */
18673 addObjectDependency(dobj
, preDataBound
->dumpId
);
18681 * BuildArchiveDependencies - create dependency data for archive TOC entries
18683 * The raw dependency data obtained by getDependencies() is not terribly
18684 * useful in an archive dump, because in many cases there are dependency
18685 * chains linking through objects that don't appear explicitly in the dump.
18686 * For example, a view will depend on its _RETURN rule while the _RETURN rule
18687 * will depend on other objects --- but the rule will not appear as a separate
18688 * object in the dump. We need to adjust the view's dependencies to include
18689 * whatever the rule depends on that is included in the dump.
18691 * Just to make things more complicated, there are also "special" dependencies
18692 * such as the dependency of a TABLE DATA item on its TABLE, which we must
18693 * not rearrange because pg_restore knows that TABLE DATA only depends on
18694 * its table. In these cases we must leave the dependencies strictly as-is
18695 * even if they refer to not-to-be-dumped objects.
18697 * To handle this, the convention is that "special" dependencies are created
18698 * during ArchiveEntry calls, and an archive TOC item that has any such
18699 * entries will not be touched here. Otherwise, we recursively search the
18700 * DumpableObject data structures to build the correct dependencies for each
18701 * archive TOC item.
18704 BuildArchiveDependencies(Archive
*fout
)
18706 ArchiveHandle
*AH
= (ArchiveHandle
*) fout
;
18709 /* Scan all TOC entries in the archive */
18710 for (te
= AH
->toc
->next
; te
!= AH
->toc
; te
= te
->next
)
18712 DumpableObject
*dobj
;
18713 DumpId
*dependencies
;
18717 /* No need to process entries that will not be dumped */
18720 /* Ignore entries that already have "special" dependencies */
18723 /* Otherwise, look up the item's original DumpableObject, if any */
18724 dobj
= findObjectByDumpId(te
->dumpId
);
18727 /* No work if it has no dependencies */
18728 if (dobj
->nDeps
<= 0)
18730 /* Set up work array */
18732 dependencies
= (DumpId
*) pg_malloc(allocDeps
* sizeof(DumpId
));
18734 /* Recursively find all dumpable dependencies */
18735 findDumpableDependencies(AH
, dobj
,
18736 &dependencies
, &nDeps
, &allocDeps
);
18737 /* And save 'em ... */
18740 dependencies
= (DumpId
*) pg_realloc(dependencies
,
18741 nDeps
* sizeof(DumpId
));
18742 te
->dependencies
= dependencies
;
18746 free(dependencies
);
18750 /* Recursive search subroutine for BuildArchiveDependencies */
18752 findDumpableDependencies(ArchiveHandle
*AH
, DumpableObject
*dobj
,
18753 DumpId
**dependencies
, int *nDeps
, int *allocDeps
)
18758 * Ignore section boundary objects: if we search through them, we'll
18759 * report lots of bogus dependencies.
18761 if (dobj
->objType
== DO_PRE_DATA_BOUNDARY
||
18762 dobj
->objType
== DO_POST_DATA_BOUNDARY
)
18765 for (i
= 0; i
< dobj
->nDeps
; i
++)
18767 DumpId depid
= dobj
->dependencies
[i
];
18769 if (TocIDRequired(AH
, depid
) != 0)
18771 /* Object will be dumped, so just reference it as a dependency */
18772 if (*nDeps
>= *allocDeps
)
18775 *dependencies
= (DumpId
*) pg_realloc(*dependencies
,
18776 *allocDeps
* sizeof(DumpId
));
18778 (*dependencies
)[*nDeps
] = depid
;
18784 * Object will not be dumped, so recursively consider its deps. We
18785 * rely on the assumption that sortDumpableObjects already broke
18786 * any dependency loops, else we might recurse infinitely.
18788 DumpableObject
*otherdobj
= findObjectByDumpId(depid
);
18791 findDumpableDependencies(AH
, otherdobj
,
18792 dependencies
, nDeps
, allocDeps
);
18799 * getFormattedTypeName - retrieve a nicely-formatted type name for the
18802 * This does not guarantee to schema-qualify the output, so it should not
18803 * be used to create the target object name for CREATE or ALTER commands.
18805 * Note that the result is cached and must not be freed by the caller.
18807 static const char *
18808 getFormattedTypeName(Archive
*fout
, Oid oid
, OidOptions opts
)
18810 TypeInfo
*typeInfo
;
18817 if ((opts
& zeroAsOpaque
) != 0)
18818 return g_opaque_type
;
18819 else if ((opts
& zeroAsAny
) != 0)
18821 else if ((opts
& zeroAsStar
) != 0)
18823 else if ((opts
& zeroAsNone
) != 0)
18827 /* see if we have the result cached in the type's TypeInfo record */
18828 typeInfo
= findTypeByOid(oid
);
18829 if (typeInfo
&& typeInfo
->ftypname
)
18830 return typeInfo
->ftypname
;
18832 query
= createPQExpBuffer();
18833 appendPQExpBuffer(query
, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
18836 res
= ExecuteSqlQueryForSingleRow(fout
, query
->data
);
18838 /* result of format_type is already quoted */
18839 result
= pg_strdup(PQgetvalue(res
, 0, 0));
18842 destroyPQExpBuffer(query
);
18845 * Cache the result for re-use in later requests, if possible. If we
18846 * don't have a TypeInfo for the type, the string will be leaked once the
18847 * caller is done with it ... but that case really should not happen, so
18848 * leaking if it does seems acceptable.
18851 typeInfo
->ftypname
= result
;
18857 * Return a column list clause for the given relation.
18859 * Special case: if there are no undropped columns in the relation, return
18860 * "", not an invalid "()" column list.
18862 static const char *
18863 fmtCopyColumnList(const TableInfo
*ti
, PQExpBuffer buffer
)
18865 int numatts
= ti
->numatts
;
18866 char **attnames
= ti
->attnames
;
18867 bool *attisdropped
= ti
->attisdropped
;
18868 char *attgenerated
= ti
->attgenerated
;
18872 appendPQExpBufferChar(buffer
, '(');
18874 for (i
= 0; i
< numatts
; i
++)
18876 if (attisdropped
[i
])
18878 if (attgenerated
[i
])
18881 appendPQExpBufferStr(buffer
, ", ");
18882 appendPQExpBufferStr(buffer
, fmtId(attnames
[i
]));
18887 return ""; /* no undropped columns */
18889 appendPQExpBufferChar(buffer
, ')');
18890 return buffer
->data
;
18894 * Check if a reloptions array is nonempty.
18897 nonemptyReloptions(const char *reloptions
)
18899 /* Don't want to print it if it's just "{}" */
18900 return (reloptions
!= NULL
&& strlen(reloptions
) > 2);
18904 * Format a reloptions array and append it to the given buffer.
18906 * "prefix" is prepended to the option names; typically it's "" or "toast.".
18909 appendReloptionsArrayAH(PQExpBuffer buffer
, const char *reloptions
,
18910 const char *prefix
, Archive
*fout
)
18914 res
= appendReloptionsArray(buffer
, reloptions
, prefix
, fout
->encoding
,
18915 fout
->std_strings
);
18917 pg_log_warning("could not parse reloptions array");