Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * pg_dump.c
4 : * pg_dump is a utility for dumping out a postgres database
5 : * into a script file.
6 : *
7 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
8 : * Portions Copyright (c) 1994, Regents of the University of California
9 : *
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
12 : * by PostgreSQL
13 : *
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,
23 : * but it can happen.
24 : *
25 : * http://archives.postgresql.org/pgsql-bugs/2010-02/msg00187.php
26 : *
27 : * IDENTIFICATION
28 : * src/bin/pg_dump/pg_dump.c
29 : *
30 : *-------------------------------------------------------------------------
31 : */
32 : #include "postgres_fe.h"
33 :
34 : #include <unistd.h>
35 : #include <ctype.h>
36 : #include <limits.h>
37 : #ifdef HAVE_TERMIOS_H
38 : #include <termios.h>
39 : #endif
40 :
41 : #include "access/attnum.h"
42 : #include "access/sysattr.h"
43 : #include "access/transam.h"
44 : #include "catalog/pg_aggregate_d.h"
45 : #include "catalog/pg_am_d.h"
46 : #include "catalog/pg_attribute_d.h"
47 : #include "catalog/pg_authid_d.h"
48 : #include "catalog/pg_cast_d.h"
49 : #include "catalog/pg_class_d.h"
50 : #include "catalog/pg_default_acl_d.h"
51 : #include "catalog/pg_largeobject_d.h"
52 : #include "catalog/pg_proc_d.h"
53 : #include "catalog/pg_subscription.h"
54 : #include "catalog/pg_type_d.h"
55 : #include "common/connect.h"
56 : #include "common/int.h"
57 : #include "common/relpath.h"
58 : #include "compress_io.h"
59 : #include "dumputils.h"
60 : #include "fe_utils/option_utils.h"
61 : #include "fe_utils/string_utils.h"
62 : #include "filter.h"
63 : #include "getopt_long.h"
64 : #include "libpq/libpq-fs.h"
65 : #include "parallel.h"
66 : #include "pg_backup_db.h"
67 : #include "pg_backup_utils.h"
68 : #include "pg_dump.h"
69 : #include "storage/block.h"
70 :
71 : typedef struct
72 : {
73 : Oid roleoid; /* role's OID */
74 : const char *rolename; /* role's name */
75 : } RoleNameItem;
76 :
77 : typedef struct
78 : {
79 : const char *descr; /* comment for an object */
80 : Oid classoid; /* object class (catalog OID) */
81 : Oid objoid; /* object OID */
82 : int objsubid; /* subobject (table column #) */
83 : } CommentItem;
84 :
85 : typedef struct
86 : {
87 : const char *provider; /* label provider of this security label */
88 : const char *label; /* security label for an object */
89 : Oid classoid; /* object class (catalog OID) */
90 : Oid objoid; /* object OID */
91 : int objsubid; /* subobject (table column #) */
92 : } SecLabelItem;
93 :
94 : typedef struct
95 : {
96 : Oid oid; /* object OID */
97 : char relkind; /* object kind */
98 : RelFileNumber relfilenumber; /* object filenode */
99 : Oid toast_oid; /* toast table OID */
100 : RelFileNumber toast_relfilenumber; /* toast table filenode */
101 : Oid toast_index_oid; /* toast table index OID */
102 : RelFileNumber toast_index_relfilenumber; /* toast table index filenode */
103 : } BinaryUpgradeClassOidItem;
104 :
105 : /* sequence types */
106 : typedef enum SeqType
107 : {
108 : SEQTYPE_SMALLINT,
109 : SEQTYPE_INTEGER,
110 : SEQTYPE_BIGINT,
111 : } SeqType;
112 :
113 : static const char *const SeqTypeNames[] =
114 : {
115 : [SEQTYPE_SMALLINT] = "smallint",
116 : [SEQTYPE_INTEGER] = "integer",
117 : [SEQTYPE_BIGINT] = "bigint",
118 : };
119 :
120 : StaticAssertDecl(lengthof(SeqTypeNames) == (SEQTYPE_BIGINT + 1),
121 : "array length mismatch");
122 :
123 : typedef struct
124 : {
125 : Oid oid; /* sequence OID */
126 : SeqType seqtype; /* data type of sequence */
127 : bool cycled; /* whether sequence cycles */
128 : int64 minv; /* minimum value */
129 : int64 maxv; /* maximum value */
130 : int64 startv; /* start value */
131 : int64 incby; /* increment value */
132 : int64 cache; /* cache size */
133 : int64 last_value; /* last value of sequence */
134 : bool is_called; /* whether nextval advances before returning */
135 : } SequenceItem;
136 :
137 : typedef enum OidOptions
138 : {
139 : zeroIsError = 1,
140 : zeroAsStar = 2,
141 : zeroAsNone = 4,
142 : } OidOptions;
143 :
144 : /* global decls */
145 : static bool dosync = true; /* Issue fsync() to make dump durable on disk. */
146 :
147 : static Oid g_last_builtin_oid; /* value of the last builtin oid */
148 :
149 : /* The specified names/patterns should to match at least one entity */
150 : static int strict_names = 0;
151 :
152 : static pg_compress_algorithm compression_algorithm = PG_COMPRESSION_NONE;
153 :
154 : /*
155 : * Object inclusion/exclusion lists
156 : *
157 : * The string lists record the patterns given by command-line switches,
158 : * which we then convert to lists of OIDs of matching objects.
159 : */
160 : static SimpleStringList schema_include_patterns = {NULL, NULL};
161 : static SimpleOidList schema_include_oids = {NULL, NULL};
162 : static SimpleStringList schema_exclude_patterns = {NULL, NULL};
163 : static SimpleOidList schema_exclude_oids = {NULL, NULL};
164 :
165 : static SimpleStringList table_include_patterns = {NULL, NULL};
166 : static SimpleStringList table_include_patterns_and_children = {NULL, NULL};
167 : static SimpleOidList table_include_oids = {NULL, NULL};
168 : static SimpleStringList table_exclude_patterns = {NULL, NULL};
169 : static SimpleStringList table_exclude_patterns_and_children = {NULL, NULL};
170 : static SimpleOidList table_exclude_oids = {NULL, NULL};
171 : static SimpleStringList tabledata_exclude_patterns = {NULL, NULL};
172 : static SimpleStringList tabledata_exclude_patterns_and_children = {NULL, NULL};
173 : static SimpleOidList tabledata_exclude_oids = {NULL, NULL};
174 :
175 : static SimpleStringList foreign_servers_include_patterns = {NULL, NULL};
176 : static SimpleOidList foreign_servers_include_oids = {NULL, NULL};
177 :
178 : static SimpleStringList extension_include_patterns = {NULL, NULL};
179 : static SimpleOidList extension_include_oids = {NULL, NULL};
180 :
181 : static SimpleStringList extension_exclude_patterns = {NULL, NULL};
182 : static SimpleOidList extension_exclude_oids = {NULL, NULL};
183 :
184 : static const CatalogId nilCatalogId = {0, 0};
185 :
186 : /* override for standard extra_float_digits setting */
187 : static bool have_extra_float_digits = false;
188 : static int extra_float_digits;
189 :
190 : /* sorted table of role names */
191 : static RoleNameItem *rolenames = NULL;
192 : static int nrolenames = 0;
193 :
194 : /* sorted table of comments */
195 : static CommentItem *comments = NULL;
196 : static int ncomments = 0;
197 :
198 : /* sorted table of security labels */
199 : static SecLabelItem *seclabels = NULL;
200 : static int nseclabels = 0;
201 :
202 : /* sorted table of pg_class information for binary upgrade */
203 : static BinaryUpgradeClassOidItem *binaryUpgradeClassOids = NULL;
204 : static int nbinaryUpgradeClassOids = 0;
205 :
206 : /* sorted table of sequences */
207 : static SequenceItem *sequences = NULL;
208 : static int nsequences = 0;
209 :
210 : /*
211 : * The default number of rows per INSERT when
212 : * --inserts is specified without --rows-per-insert
213 : */
214 : #define DUMP_DEFAULT_ROWS_PER_INSERT 1
215 :
216 : /*
217 : * Maximum number of large objects to group into a single ArchiveEntry.
218 : * At some point we might want to make this user-controllable, but for now
219 : * a hard-wired setting will suffice.
220 : */
221 : #define MAX_BLOBS_PER_ARCHIVE_ENTRY 1000
222 :
223 : /*
224 : * Macro for producing quoted, schema-qualified name of a dumpable object.
225 : */
226 : #define fmtQualifiedDumpable(obj) \
227 : fmtQualifiedId((obj)->dobj.namespace->dobj.name, \
228 : (obj)->dobj.name)
229 :
230 : static void help(const char *progname);
231 : static void setup_connection(Archive *AH,
232 : const char *dumpencoding, const char *dumpsnapshot,
233 : char *use_role);
234 : static ArchiveFormat parseArchiveFormat(const char *format, ArchiveMode *mode);
235 : static void expand_schema_name_patterns(Archive *fout,
236 : SimpleStringList *patterns,
237 : SimpleOidList *oids,
238 : bool strict_names);
239 : static void expand_extension_name_patterns(Archive *fout,
240 : SimpleStringList *patterns,
241 : SimpleOidList *oids,
242 : bool strict_names);
243 : static void expand_foreign_server_name_patterns(Archive *fout,
244 : SimpleStringList *patterns,
245 : SimpleOidList *oids);
246 : static void expand_table_name_patterns(Archive *fout,
247 : SimpleStringList *patterns,
248 : SimpleOidList *oids,
249 : bool strict_names,
250 : bool with_child_tables);
251 : static void prohibit_crossdb_refs(PGconn *conn, const char *dbname,
252 : const char *pattern);
253 :
254 : static NamespaceInfo *findNamespace(Oid nsoid);
255 : static void dumpTableData(Archive *fout, const TableDataInfo *tdinfo);
256 : static void refreshMatViewData(Archive *fout, const TableDataInfo *tdinfo);
257 : static const char *getRoleName(const char *roleoid_str);
258 : static void collectRoleNames(Archive *fout);
259 : static void getAdditionalACLs(Archive *fout);
260 : static void dumpCommentExtended(Archive *fout, const char *type,
261 : const char *name, const char *namespace,
262 : const char *owner, CatalogId catalogId,
263 : int subid, DumpId dumpId,
264 : const char *initdb_comment);
265 : static inline void dumpComment(Archive *fout, const char *type,
266 : const char *name, const char *namespace,
267 : const char *owner, CatalogId catalogId,
268 : int subid, DumpId dumpId);
269 : static int findComments(Oid classoid, Oid objoid, CommentItem **items);
270 : static void collectComments(Archive *fout);
271 : static void dumpSecLabel(Archive *fout, const char *type, const char *name,
272 : const char *namespace, const char *owner,
273 : CatalogId catalogId, int subid, DumpId dumpId);
274 : static int findSecLabels(Oid classoid, Oid objoid, SecLabelItem **items);
275 : static void collectSecLabels(Archive *fout);
276 : static void dumpDumpableObject(Archive *fout, DumpableObject *dobj);
277 : static void dumpNamespace(Archive *fout, const NamespaceInfo *nspinfo);
278 : static void dumpExtension(Archive *fout, const ExtensionInfo *extinfo);
279 : static void dumpType(Archive *fout, const TypeInfo *tyinfo);
280 : static void dumpBaseType(Archive *fout, const TypeInfo *tyinfo);
281 : static void dumpEnumType(Archive *fout, const TypeInfo *tyinfo);
282 : static void dumpRangeType(Archive *fout, const TypeInfo *tyinfo);
283 : static void dumpUndefinedType(Archive *fout, const TypeInfo *tyinfo);
284 : static void dumpDomain(Archive *fout, const TypeInfo *tyinfo);
285 : static void dumpCompositeType(Archive *fout, const TypeInfo *tyinfo);
286 : static void dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
287 : PGresult *res);
288 : static void dumpShellType(Archive *fout, const ShellTypeInfo *stinfo);
289 : static void dumpProcLang(Archive *fout, const ProcLangInfo *plang);
290 : static void dumpFunc(Archive *fout, const FuncInfo *finfo);
291 : static void dumpCast(Archive *fout, const CastInfo *cast);
292 : static void dumpTransform(Archive *fout, const TransformInfo *transform);
293 : static void dumpOpr(Archive *fout, const OprInfo *oprinfo);
294 : static void dumpAccessMethod(Archive *fout, const AccessMethodInfo *aminfo);
295 : static void dumpOpclass(Archive *fout, const OpclassInfo *opcinfo);
296 : static void dumpOpfamily(Archive *fout, const OpfamilyInfo *opfinfo);
297 : static void dumpCollation(Archive *fout, const CollInfo *collinfo);
298 : static void dumpConversion(Archive *fout, const ConvInfo *convinfo);
299 : static void dumpRule(Archive *fout, const RuleInfo *rinfo);
300 : static void dumpAgg(Archive *fout, const AggInfo *agginfo);
301 : static void dumpTrigger(Archive *fout, const TriggerInfo *tginfo);
302 : static void dumpEventTrigger(Archive *fout, const EventTriggerInfo *evtinfo);
303 : static void dumpTable(Archive *fout, const TableInfo *tbinfo);
304 : static void dumpTableSchema(Archive *fout, const TableInfo *tbinfo);
305 : static void dumpTableAttach(Archive *fout, const TableAttachInfo *attachinfo);
306 : static void dumpAttrDef(Archive *fout, const AttrDefInfo *adinfo);
307 : static void collectSequences(Archive *fout);
308 : static void dumpSequence(Archive *fout, const TableInfo *tbinfo);
309 : static void dumpSequenceData(Archive *fout, const TableDataInfo *tdinfo);
310 : static void dumpIndex(Archive *fout, const IndxInfo *indxinfo);
311 : static void dumpIndexAttach(Archive *fout, const IndexAttachInfo *attachinfo);
312 : static void dumpStatisticsExt(Archive *fout, const StatsExtInfo *statsextinfo);
313 : static void dumpConstraint(Archive *fout, const ConstraintInfo *coninfo);
314 : static void dumpTableConstraintComment(Archive *fout, const ConstraintInfo *coninfo);
315 : static void dumpTSParser(Archive *fout, const TSParserInfo *prsinfo);
316 : static void dumpTSDictionary(Archive *fout, const TSDictInfo *dictinfo);
317 : static void dumpTSTemplate(Archive *fout, const TSTemplateInfo *tmplinfo);
318 : static void dumpTSConfig(Archive *fout, const TSConfigInfo *cfginfo);
319 : static void dumpForeignDataWrapper(Archive *fout, const FdwInfo *fdwinfo);
320 : static void dumpForeignServer(Archive *fout, const ForeignServerInfo *srvinfo);
321 : static void dumpUserMappings(Archive *fout,
322 : const char *servername, const char *namespace,
323 : const char *owner, CatalogId catalogId, DumpId dumpId);
324 : static void dumpDefaultACL(Archive *fout, const DefaultACLInfo *daclinfo);
325 :
326 : static DumpId dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId,
327 : const char *type, const char *name, const char *subname,
328 : const char *nspname, const char *tag, const char *owner,
329 : const DumpableAcl *dacl);
330 :
331 : static void getDependencies(Archive *fout);
332 : static void BuildArchiveDependencies(Archive *fout);
333 : static void findDumpableDependencies(ArchiveHandle *AH, const DumpableObject *dobj,
334 : DumpId **dependencies, int *nDeps, int *allocDeps);
335 :
336 : static DumpableObject *createBoundaryObjects(void);
337 : static void addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
338 : DumpableObject *boundaryObjs);
339 :
340 : static void addConstrChildIdxDeps(DumpableObject *dobj, const IndxInfo *refidx);
341 : static void getDomainConstraints(Archive *fout, TypeInfo *tyinfo);
342 : static void getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind);
343 : static void makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo);
344 : static void buildMatViewRefreshDependencies(Archive *fout);
345 : static void getTableDataFKConstraints(void);
346 : static void determineNotNullFlags(Archive *fout, PGresult *res, int r,
347 : TableInfo *tbinfo, int j,
348 : int i_notnull_name, int i_notnull_noinherit,
349 : int i_notnull_islocal);
350 : static char *format_function_arguments(const FuncInfo *finfo, const char *funcargs,
351 : bool is_agg);
352 : static char *format_function_signature(Archive *fout,
353 : const FuncInfo *finfo, bool honor_quotes);
354 : static char *convertRegProcReference(const char *proc);
355 : static char *getFormattedOperatorName(const char *oproid);
356 : static char *convertTSFunction(Archive *fout, Oid funcOid);
357 : static const char *getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts);
358 : static void getLOs(Archive *fout);
359 : static void dumpLO(Archive *fout, const LoInfo *loinfo);
360 : static int dumpLOs(Archive *fout, const void *arg);
361 : static void dumpPolicy(Archive *fout, const PolicyInfo *polinfo);
362 : static void dumpPublication(Archive *fout, const PublicationInfo *pubinfo);
363 : static void dumpPublicationTable(Archive *fout, const PublicationRelInfo *pubrinfo);
364 : static void dumpSubscription(Archive *fout, const SubscriptionInfo *subinfo);
365 : static void dumpSubscriptionTable(Archive *fout, const SubRelInfo *subrinfo);
366 : static void dumpDatabase(Archive *fout);
367 : static void dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
368 : const char *dbname, Oid dboid);
369 : static void dumpEncoding(Archive *AH);
370 : static void dumpStdStrings(Archive *AH);
371 : static void dumpSearchPath(Archive *AH);
372 : static void binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
373 : PQExpBuffer upgrade_buffer,
374 : Oid pg_type_oid,
375 : bool force_array_type,
376 : bool include_multirange_type);
377 : static void binary_upgrade_set_type_oids_by_rel(Archive *fout,
378 : PQExpBuffer upgrade_buffer,
379 : const TableInfo *tbinfo);
380 : static void collectBinaryUpgradeClassOids(Archive *fout);
381 : static void binary_upgrade_set_pg_class_oids(Archive *fout,
382 : PQExpBuffer upgrade_buffer,
383 : Oid pg_class_oid);
384 : static void binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
385 : const DumpableObject *dobj,
386 : const char *objtype,
387 : const char *objname,
388 : const char *objnamespace);
389 : static const char *getAttrName(int attrnum, const TableInfo *tblInfo);
390 : static const char *fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer);
391 : static bool nonemptyReloptions(const char *reloptions);
392 : static void appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
393 : const char *prefix, Archive *fout);
394 : static char *get_synchronized_snapshot(Archive *fout);
395 : static void set_restrict_relation_kind(Archive *AH, const char *value);
396 : static void setupDumpWorker(Archive *AH);
397 : static TableInfo *getRootTableInfo(const TableInfo *tbinfo);
398 : static bool forcePartitionRootLoad(const TableInfo *tbinfo);
399 : static void read_dump_filters(const char *filename, DumpOptions *dopt);
400 :
401 :
402 : int
403 486 : main(int argc, char **argv)
404 : {
405 : int c;
406 486 : const char *filename = NULL;
407 486 : const char *format = "p";
408 : TableInfo *tblinfo;
409 : int numTables;
410 : DumpableObject **dobjs;
411 : int numObjs;
412 : DumpableObject *boundaryObjs;
413 : int i;
414 : int optindex;
415 : RestoreOptions *ropt;
416 : Archive *fout; /* the script file */
417 486 : bool g_verbose = false;
418 486 : const char *dumpencoding = NULL;
419 486 : const char *dumpsnapshot = NULL;
420 486 : char *use_role = NULL;
421 486 : int numWorkers = 1;
422 486 : int plainText = 0;
423 486 : ArchiveFormat archiveFormat = archUnknown;
424 : ArchiveMode archiveMode;
425 486 : pg_compress_specification compression_spec = {0};
426 486 : char *compression_detail = NULL;
427 486 : char *compression_algorithm_str = "none";
428 486 : char *error_detail = NULL;
429 486 : bool user_compression_defined = false;
430 486 : DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC;
431 :
432 : static DumpOptions dopt;
433 :
434 : static struct option long_options[] = {
435 : {"data-only", no_argument, NULL, 'a'},
436 : {"blobs", no_argument, NULL, 'b'},
437 : {"large-objects", no_argument, NULL, 'b'},
438 : {"no-blobs", no_argument, NULL, 'B'},
439 : {"no-large-objects", no_argument, NULL, 'B'},
440 : {"clean", no_argument, NULL, 'c'},
441 : {"create", no_argument, NULL, 'C'},
442 : {"dbname", required_argument, NULL, 'd'},
443 : {"extension", required_argument, NULL, 'e'},
444 : {"file", required_argument, NULL, 'f'},
445 : {"format", required_argument, NULL, 'F'},
446 : {"host", required_argument, NULL, 'h'},
447 : {"jobs", 1, NULL, 'j'},
448 : {"no-reconnect", no_argument, NULL, 'R'},
449 : {"no-owner", no_argument, NULL, 'O'},
450 : {"port", required_argument, NULL, 'p'},
451 : {"schema", required_argument, NULL, 'n'},
452 : {"exclude-schema", required_argument, NULL, 'N'},
453 : {"schema-only", no_argument, NULL, 's'},
454 : {"superuser", required_argument, NULL, 'S'},
455 : {"table", required_argument, NULL, 't'},
456 : {"exclude-table", required_argument, NULL, 'T'},
457 : {"no-password", no_argument, NULL, 'w'},
458 : {"password", no_argument, NULL, 'W'},
459 : {"username", required_argument, NULL, 'U'},
460 : {"verbose", no_argument, NULL, 'v'},
461 : {"no-privileges", no_argument, NULL, 'x'},
462 : {"no-acl", no_argument, NULL, 'x'},
463 : {"compress", required_argument, NULL, 'Z'},
464 : {"encoding", required_argument, NULL, 'E'},
465 : {"help", no_argument, NULL, '?'},
466 : {"version", no_argument, NULL, 'V'},
467 :
468 : /*
469 : * the following options don't have an equivalent short option letter
470 : */
471 : {"attribute-inserts", no_argument, &dopt.column_inserts, 1},
472 : {"binary-upgrade", no_argument, &dopt.binary_upgrade, 1},
473 : {"column-inserts", no_argument, &dopt.column_inserts, 1},
474 : {"disable-dollar-quoting", no_argument, &dopt.disable_dollar_quoting, 1},
475 : {"disable-triggers", no_argument, &dopt.disable_triggers, 1},
476 : {"enable-row-security", no_argument, &dopt.enable_row_security, 1},
477 : {"exclude-table-data", required_argument, NULL, 4},
478 : {"extra-float-digits", required_argument, NULL, 8},
479 : {"if-exists", no_argument, &dopt.if_exists, 1},
480 : {"inserts", no_argument, NULL, 9},
481 : {"lock-wait-timeout", required_argument, NULL, 2},
482 : {"no-table-access-method", no_argument, &dopt.outputNoTableAm, 1},
483 : {"no-tablespaces", no_argument, &dopt.outputNoTablespaces, 1},
484 : {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
485 : {"load-via-partition-root", no_argument, &dopt.load_via_partition_root, 1},
486 : {"role", required_argument, NULL, 3},
487 : {"section", required_argument, NULL, 5},
488 : {"serializable-deferrable", no_argument, &dopt.serializable_deferrable, 1},
489 : {"snapshot", required_argument, NULL, 6},
490 : {"strict-names", no_argument, &strict_names, 1},
491 : {"use-set-session-authorization", no_argument, &dopt.use_setsessauth, 1},
492 : {"no-comments", no_argument, &dopt.no_comments, 1},
493 : {"no-publications", no_argument, &dopt.no_publications, 1},
494 : {"no-security-labels", no_argument, &dopt.no_security_labels, 1},
495 : {"no-subscriptions", no_argument, &dopt.no_subscriptions, 1},
496 : {"no-toast-compression", no_argument, &dopt.no_toast_compression, 1},
497 : {"no-unlogged-table-data", no_argument, &dopt.no_unlogged_table_data, 1},
498 : {"no-sync", no_argument, NULL, 7},
499 : {"on-conflict-do-nothing", no_argument, &dopt.do_nothing, 1},
500 : {"rows-per-insert", required_argument, NULL, 10},
501 : {"include-foreign-data", required_argument, NULL, 11},
502 : {"table-and-children", required_argument, NULL, 12},
503 : {"exclude-table-and-children", required_argument, NULL, 13},
504 : {"exclude-table-data-and-children", required_argument, NULL, 14},
505 : {"sync-method", required_argument, NULL, 15},
506 : {"filter", required_argument, NULL, 16},
507 : {"exclude-extension", required_argument, NULL, 17},
508 :
509 : {NULL, 0, NULL, 0}
510 : };
511 :
512 486 : pg_logging_init(argv[0]);
513 486 : pg_logging_set_level(PG_LOG_WARNING);
514 486 : set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
515 :
516 : /*
517 : * Initialize what we need for parallel execution, especially for thread
518 : * support on Windows.
519 : */
520 486 : init_parallel_dump_utils();
521 :
522 486 : progname = get_progname(argv[0]);
523 :
524 486 : if (argc > 1)
525 : {
526 486 : if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
527 : {
528 2 : help(progname);
529 2 : exit_nicely(0);
530 : }
531 484 : if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
532 : {
533 94 : puts("pg_dump (PostgreSQL) " PG_VERSION);
534 94 : exit_nicely(0);
535 : }
536 : }
537 :
538 390 : InitDumpOptions(&dopt);
539 :
540 1712 : while ((c = getopt_long(argc, argv, "abBcCd:e:E:f:F:h:j:n:N:Op:RsS:t:T:U:vwWxZ:",
541 : long_options, &optindex)) != -1)
542 : {
543 1338 : switch (c)
544 : {
545 16 : case 'a': /* Dump data only */
546 16 : dopt.dataOnly = true;
547 16 : break;
548 :
549 2 : case 'b': /* Dump LOs */
550 2 : dopt.outputLOs = true;
551 2 : break;
552 :
553 4 : case 'B': /* Don't dump LOs */
554 4 : dopt.dontOutputLOs = true;
555 4 : break;
556 :
557 12 : case 'c': /* clean (i.e., drop) schema prior to create */
558 12 : dopt.outputClean = 1;
559 12 : break;
560 :
561 58 : case 'C': /* Create DB */
562 58 : dopt.outputCreateDB = 1;
563 58 : break;
564 :
565 10 : case 'd': /* database name */
566 10 : dopt.cparams.dbname = pg_strdup(optarg);
567 10 : break;
568 :
569 8 : case 'e': /* include extension(s) */
570 8 : simple_string_list_append(&extension_include_patterns, optarg);
571 8 : dopt.include_everything = false;
572 8 : break;
573 :
574 4 : case 'E': /* Dump encoding */
575 4 : dumpencoding = pg_strdup(optarg);
576 4 : break;
577 :
578 306 : case 'f':
579 306 : filename = pg_strdup(optarg);
580 306 : break;
581 :
582 170 : case 'F':
583 170 : format = pg_strdup(optarg);
584 170 : break;
585 :
586 24 : case 'h': /* server host */
587 24 : dopt.cparams.pghost = pg_strdup(optarg);
588 24 : break;
589 :
590 22 : case 'j': /* number of dump jobs */
591 22 : if (!option_parse_int(optarg, "-j/--jobs", 1,
592 : PG_MAX_JOBS,
593 : &numWorkers))
594 2 : exit_nicely(1);
595 20 : break;
596 :
597 34 : case 'n': /* include schema(s) */
598 34 : simple_string_list_append(&schema_include_patterns, optarg);
599 34 : dopt.include_everything = false;
600 34 : break;
601 :
602 2 : case 'N': /* exclude schema(s) */
603 2 : simple_string_list_append(&schema_exclude_patterns, optarg);
604 2 : break;
605 :
606 4 : case 'O': /* Don't reconnect to match owner */
607 4 : dopt.outputNoOwner = 1;
608 4 : break;
609 :
610 100 : case 'p': /* server port */
611 100 : dopt.cparams.pgport = pg_strdup(optarg);
612 100 : break;
613 :
614 4 : case 'R':
615 : /* no-op, still accepted for backwards compatibility */
616 4 : break;
617 :
618 36 : case 's': /* dump schema only */
619 36 : dopt.schemaOnly = true;
620 36 : break;
621 :
622 2 : case 'S': /* Username for superuser in plain text output */
623 2 : dopt.outputSuperuser = pg_strdup(optarg);
624 2 : break;
625 :
626 16 : case 't': /* include table(s) */
627 16 : simple_string_list_append(&table_include_patterns, optarg);
628 16 : dopt.include_everything = false;
629 16 : break;
630 :
631 8 : case 'T': /* exclude table(s) */
632 8 : simple_string_list_append(&table_exclude_patterns, optarg);
633 8 : break;
634 :
635 28 : case 'U':
636 28 : dopt.cparams.username = pg_strdup(optarg);
637 28 : break;
638 :
639 12 : case 'v': /* verbose */
640 12 : g_verbose = true;
641 12 : pg_logging_increase_verbosity();
642 12 : break;
643 :
644 2 : case 'w':
645 2 : dopt.cparams.promptPassword = TRI_NO;
646 2 : break;
647 :
648 0 : case 'W':
649 0 : dopt.cparams.promptPassword = TRI_YES;
650 0 : break;
651 :
652 4 : case 'x': /* skip ACL dump */
653 4 : dopt.aclsSkip = true;
654 4 : break;
655 :
656 24 : case 'Z': /* Compression */
657 24 : parse_compress_options(optarg, &compression_algorithm_str,
658 : &compression_detail);
659 24 : user_compression_defined = true;
660 24 : break;
661 :
662 100 : case 0:
663 : /* This covers the long options. */
664 100 : break;
665 :
666 4 : case 2: /* lock-wait-timeout */
667 4 : dopt.lockWaitTimeout = pg_strdup(optarg);
668 4 : break;
669 :
670 6 : case 3: /* SET ROLE */
671 6 : use_role = pg_strdup(optarg);
672 6 : break;
673 :
674 2 : case 4: /* exclude table(s) data */
675 2 : simple_string_list_append(&tabledata_exclude_patterns, optarg);
676 2 : break;
677 :
678 12 : case 5: /* section */
679 12 : set_dump_section(optarg, &dopt.dumpSections);
680 12 : break;
681 :
682 0 : case 6: /* snapshot */
683 0 : dumpsnapshot = pg_strdup(optarg);
684 0 : break;
685 :
686 222 : case 7: /* no-sync */
687 222 : dosync = false;
688 222 : break;
689 :
690 2 : case 8:
691 2 : have_extra_float_digits = true;
692 2 : if (!option_parse_int(optarg, "--extra-float-digits", -15, 3,
693 : &extra_float_digits))
694 2 : exit_nicely(1);
695 0 : break;
696 :
697 4 : case 9: /* inserts */
698 :
699 : /*
700 : * dump_inserts also stores --rows-per-insert, careful not to
701 : * overwrite that.
702 : */
703 4 : if (dopt.dump_inserts == 0)
704 4 : dopt.dump_inserts = DUMP_DEFAULT_ROWS_PER_INSERT;
705 4 : break;
706 :
707 4 : case 10: /* rows per insert */
708 4 : if (!option_parse_int(optarg, "--rows-per-insert", 1, INT_MAX,
709 : &dopt.dump_inserts))
710 2 : exit_nicely(1);
711 2 : break;
712 :
713 8 : case 11: /* include foreign data */
714 8 : simple_string_list_append(&foreign_servers_include_patterns,
715 : optarg);
716 8 : break;
717 :
718 2 : case 12: /* include table(s) and their children */
719 2 : simple_string_list_append(&table_include_patterns_and_children,
720 : optarg);
721 2 : dopt.include_everything = false;
722 2 : break;
723 :
724 2 : case 13: /* exclude table(s) and their children */
725 2 : simple_string_list_append(&table_exclude_patterns_and_children,
726 : optarg);
727 2 : break;
728 :
729 2 : case 14: /* exclude data of table(s) and children */
730 2 : simple_string_list_append(&tabledata_exclude_patterns_and_children,
731 : optarg);
732 2 : break;
733 :
734 0 : case 15:
735 0 : if (!parse_sync_method(optarg, &sync_method))
736 0 : exit_nicely(1);
737 0 : break;
738 :
739 52 : case 16: /* read object filters from file */
740 52 : read_dump_filters(optarg, &dopt);
741 44 : break;
742 :
743 2 : case 17: /* exclude extension(s) */
744 2 : simple_string_list_append(&extension_exclude_patterns,
745 : optarg);
746 2 : break;
747 :
748 2 : default:
749 : /* getopt_long already emitted a complaint */
750 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
751 2 : exit_nicely(1);
752 : }
753 : }
754 :
755 : /*
756 : * Non-option argument specifies database name as long as it wasn't
757 : * already specified with -d / --dbname
758 : */
759 374 : if (optind < argc && dopt.cparams.dbname == NULL)
760 310 : dopt.cparams.dbname = argv[optind++];
761 :
762 : /* Complain if any arguments remain */
763 374 : if (optind < argc)
764 : {
765 2 : pg_log_error("too many command-line arguments (first is \"%s\")",
766 : argv[optind]);
767 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
768 2 : exit_nicely(1);
769 : }
770 :
771 : /* --column-inserts implies --inserts */
772 372 : if (dopt.column_inserts && dopt.dump_inserts == 0)
773 2 : dopt.dump_inserts = DUMP_DEFAULT_ROWS_PER_INSERT;
774 :
775 : /*
776 : * Binary upgrade mode implies dumping sequence data even in schema-only
777 : * mode. This is not exposed as a separate option, but kept separate
778 : * internally for clarity.
779 : */
780 372 : if (dopt.binary_upgrade)
781 28 : dopt.sequence_data = 1;
782 :
783 372 : if (dopt.dataOnly && dopt.schemaOnly)
784 2 : pg_fatal("options -s/--schema-only and -a/--data-only cannot be used together");
785 :
786 370 : if (dopt.schemaOnly && foreign_servers_include_patterns.head != NULL)
787 2 : pg_fatal("options -s/--schema-only and --include-foreign-data cannot be used together");
788 :
789 368 : if (numWorkers > 1 && foreign_servers_include_patterns.head != NULL)
790 2 : pg_fatal("option --include-foreign-data is not supported with parallel backup");
791 :
792 366 : if (dopt.dataOnly && dopt.outputClean)
793 2 : pg_fatal("options -c/--clean and -a/--data-only cannot be used together");
794 :
795 364 : if (dopt.if_exists && !dopt.outputClean)
796 2 : pg_fatal("option --if-exists requires option -c/--clean");
797 :
798 : /*
799 : * --inserts are already implied above if --column-inserts or
800 : * --rows-per-insert were specified.
801 : */
802 362 : if (dopt.do_nothing && dopt.dump_inserts == 0)
803 2 : pg_fatal("option --on-conflict-do-nothing requires option --inserts, --rows-per-insert, or --column-inserts");
804 :
805 : /* Identify archive format to emit */
806 360 : archiveFormat = parseArchiveFormat(format, &archiveMode);
807 :
808 : /* archiveFormat specific setup */
809 358 : if (archiveFormat == archNull)
810 294 : plainText = 1;
811 :
812 : /*
813 : * Custom and directory formats are compressed by default with gzip when
814 : * available, not the others. If gzip is not available, no compression is
815 : * done by default.
816 : */
817 358 : if ((archiveFormat == archCustom || archiveFormat == archDirectory) &&
818 58 : !user_compression_defined)
819 : {
820 : #ifdef HAVE_LIBZ
821 48 : compression_algorithm_str = "gzip";
822 : #else
823 : compression_algorithm_str = "none";
824 : #endif
825 : }
826 :
827 : /*
828 : * Compression options
829 : */
830 358 : if (!parse_compress_algorithm(compression_algorithm_str,
831 : &compression_algorithm))
832 2 : pg_fatal("unrecognized compression algorithm: \"%s\"",
833 : compression_algorithm_str);
834 :
835 356 : parse_compress_specification(compression_algorithm, compression_detail,
836 : &compression_spec);
837 356 : error_detail = validate_compress_specification(&compression_spec);
838 356 : if (error_detail != NULL)
839 6 : pg_fatal("invalid compression specification: %s",
840 : error_detail);
841 :
842 350 : error_detail = supports_compression(compression_spec);
843 350 : if (error_detail != NULL)
844 0 : pg_fatal("%s", error_detail);
845 :
846 : /*
847 : * Disable support for zstd workers for now - these are based on
848 : * threading, and it's unclear how it interacts with parallel dumps on
849 : * platforms where that relies on threads too (e.g. Windows).
850 : */
851 350 : if (compression_spec.options & PG_COMPRESSION_OPTION_WORKERS)
852 0 : pg_log_warning("compression option \"%s\" is not currently supported by pg_dump",
853 : "workers");
854 :
855 : /*
856 : * If emitting an archive format, we always want to emit a DATABASE item,
857 : * in case --create is specified at pg_restore time.
858 : */
859 350 : if (!plainText)
860 64 : dopt.outputCreateDB = 1;
861 :
862 : /* Parallel backup only in the directory archive format so far */
863 350 : if (archiveFormat != archDirectory && numWorkers > 1)
864 2 : pg_fatal("parallel backup only supported by the directory format");
865 :
866 : /* Open the output file */
867 348 : fout = CreateArchive(filename, archiveFormat, compression_spec,
868 : dosync, archiveMode, setupDumpWorker, sync_method);
869 :
870 : /* Make dump options accessible right away */
871 346 : SetArchiveOptions(fout, &dopt, NULL);
872 :
873 : /* Register the cleanup hook */
874 346 : on_exit_close_archive(fout);
875 :
876 : /* Let the archiver know how noisy to be */
877 346 : fout->verbose = g_verbose;
878 :
879 :
880 : /*
881 : * We allow the server to be back to 9.2, and up to any minor release of
882 : * our own major version. (See also version check in pg_dumpall.c.)
883 : */
884 346 : fout->minRemoteVersion = 90200;
885 346 : fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
886 :
887 346 : fout->numWorkers = numWorkers;
888 :
889 : /*
890 : * Open the database using the Archiver, so it knows about it. Errors mean
891 : * death.
892 : */
893 346 : ConnectDatabase(fout, &dopt.cparams, false);
894 342 : setup_connection(fout, dumpencoding, dumpsnapshot, use_role);
895 :
896 : /*
897 : * On hot standbys, never try to dump unlogged table data, since it will
898 : * just throw an error.
899 : */
900 342 : if (fout->isStandby)
901 8 : dopt.no_unlogged_table_data = true;
902 :
903 : /*
904 : * Find the last built-in OID, if needed (prior to 8.1)
905 : *
906 : * With 8.1 and above, we can just use FirstNormalObjectId - 1.
907 : */
908 342 : g_last_builtin_oid = FirstNormalObjectId - 1;
909 :
910 342 : pg_log_info("last built-in OID is %u", g_last_builtin_oid);
911 :
912 : /* Expand schema selection patterns into OID lists */
913 342 : if (schema_include_patterns.head != NULL)
914 : {
915 36 : expand_schema_name_patterns(fout, &schema_include_patterns,
916 : &schema_include_oids,
917 : strict_names);
918 24 : if (schema_include_oids.head == NULL)
919 2 : pg_fatal("no matching schemas were found");
920 : }
921 328 : expand_schema_name_patterns(fout, &schema_exclude_patterns,
922 : &schema_exclude_oids,
923 : false);
924 : /* non-matching exclusion patterns aren't an error */
925 :
926 : /* Expand table selection patterns into OID lists */
927 328 : expand_table_name_patterns(fout, &table_include_patterns,
928 : &table_include_oids,
929 : strict_names, false);
930 318 : expand_table_name_patterns(fout, &table_include_patterns_and_children,
931 : &table_include_oids,
932 : strict_names, true);
933 318 : if ((table_include_patterns.head != NULL ||
934 296 : table_include_patterns_and_children.head != NULL) &&
935 26 : table_include_oids.head == NULL)
936 4 : pg_fatal("no matching tables were found");
937 :
938 314 : expand_table_name_patterns(fout, &table_exclude_patterns,
939 : &table_exclude_oids,
940 : false, false);
941 314 : expand_table_name_patterns(fout, &table_exclude_patterns_and_children,
942 : &table_exclude_oids,
943 : false, true);
944 :
945 314 : expand_table_name_patterns(fout, &tabledata_exclude_patterns,
946 : &tabledata_exclude_oids,
947 : false, false);
948 314 : expand_table_name_patterns(fout, &tabledata_exclude_patterns_and_children,
949 : &tabledata_exclude_oids,
950 : false, true);
951 :
952 314 : expand_foreign_server_name_patterns(fout, &foreign_servers_include_patterns,
953 : &foreign_servers_include_oids);
954 :
955 : /* non-matching exclusion patterns aren't an error */
956 :
957 : /* Expand extension selection patterns into OID lists */
958 312 : if (extension_include_patterns.head != NULL)
959 : {
960 10 : expand_extension_name_patterns(fout, &extension_include_patterns,
961 : &extension_include_oids,
962 : strict_names);
963 10 : if (extension_include_oids.head == NULL)
964 2 : pg_fatal("no matching extensions were found");
965 : }
966 310 : expand_extension_name_patterns(fout, &extension_exclude_patterns,
967 : &extension_exclude_oids,
968 : false);
969 : /* non-matching exclusion patterns aren't an error */
970 :
971 : /*
972 : * Dumping LOs is the default for dumps where an inclusion switch is not
973 : * used (an "include everything" dump). -B can be used to exclude LOs
974 : * from those dumps. -b can be used to include LOs even when an inclusion
975 : * switch is used.
976 : *
977 : * -s means "schema only" and LOs are data, not schema, so we never
978 : * include LOs when -s is used.
979 : */
980 310 : if (dopt.include_everything && !dopt.schemaOnly && !dopt.dontOutputLOs)
981 228 : dopt.outputLOs = true;
982 :
983 : /*
984 : * Collect role names so we can map object owner OIDs to names.
985 : */
986 310 : collectRoleNames(fout);
987 :
988 : /*
989 : * Now scan the database and create DumpableObject structs for all the
990 : * objects we intend to dump.
991 : */
992 310 : tblinfo = getSchemaData(fout, &numTables);
993 :
994 308 : if (!dopt.schemaOnly)
995 : {
996 276 : getTableData(&dopt, tblinfo, numTables, 0);
997 276 : buildMatViewRefreshDependencies(fout);
998 276 : if (dopt.dataOnly)
999 12 : getTableDataFKConstraints();
1000 : }
1001 :
1002 308 : if (dopt.schemaOnly && dopt.sequence_data)
1003 28 : getTableData(&dopt, tblinfo, numTables, RELKIND_SEQUENCE);
1004 :
1005 : /*
1006 : * In binary-upgrade mode, we do not have to worry about the actual LO
1007 : * data or the associated metadata that resides in the pg_largeobject and
1008 : * pg_largeobject_metadata tables, respectively.
1009 : *
1010 : * However, we do need to collect LO information as there may be comments
1011 : * or other information on LOs that we do need to dump out.
1012 : */
1013 308 : if (dopt.outputLOs || dopt.binary_upgrade)
1014 256 : getLOs(fout);
1015 :
1016 : /*
1017 : * Collect dependency data to assist in ordering the objects.
1018 : */
1019 308 : getDependencies(fout);
1020 :
1021 : /*
1022 : * Collect ACLs, comments, and security labels, if wanted.
1023 : */
1024 308 : if (!dopt.aclsSkip)
1025 304 : getAdditionalACLs(fout);
1026 308 : if (!dopt.no_comments)
1027 308 : collectComments(fout);
1028 308 : if (!dopt.no_security_labels)
1029 308 : collectSecLabels(fout);
1030 :
1031 : /* For binary upgrade mode, collect required pg_class information. */
1032 308 : if (dopt.binary_upgrade)
1033 28 : collectBinaryUpgradeClassOids(fout);
1034 :
1035 : /* Collect sequence information. */
1036 308 : collectSequences(fout);
1037 :
1038 : /* Lastly, create dummy objects to represent the section boundaries */
1039 308 : boundaryObjs = createBoundaryObjects();
1040 :
1041 : /* Get pointers to all the known DumpableObjects */
1042 308 : getDumpableObjects(&dobjs, &numObjs);
1043 :
1044 : /*
1045 : * Add dummy dependencies to enforce the dump section ordering.
1046 : */
1047 308 : addBoundaryDependencies(dobjs, numObjs, boundaryObjs);
1048 :
1049 : /*
1050 : * Sort the objects into a safe dump order (no forward references).
1051 : *
1052 : * We rely on dependency information to help us determine a safe order, so
1053 : * the initial sort is mostly for cosmetic purposes: we sort by name to
1054 : * ensure that logically identical schemas will dump identically.
1055 : */
1056 308 : sortDumpableObjectsByTypeName(dobjs, numObjs);
1057 :
1058 308 : sortDumpableObjects(dobjs, numObjs,
1059 308 : boundaryObjs[0].dumpId, boundaryObjs[1].dumpId);
1060 :
1061 : /*
1062 : * Create archive TOC entries for all the objects to be dumped, in a safe
1063 : * order.
1064 : */
1065 :
1066 : /*
1067 : * First the special entries for ENCODING, STDSTRINGS, and SEARCHPATH.
1068 : */
1069 308 : dumpEncoding(fout);
1070 308 : dumpStdStrings(fout);
1071 308 : dumpSearchPath(fout);
1072 :
1073 : /* The database items are always next, unless we don't want them at all */
1074 308 : if (dopt.outputCreateDB)
1075 120 : dumpDatabase(fout);
1076 :
1077 : /* Now the rearrangeable objects. */
1078 1126092 : for (i = 0; i < numObjs; i++)
1079 1125784 : dumpDumpableObject(fout, dobjs[i]);
1080 :
1081 : /*
1082 : * Set up options info to ensure we dump what we want.
1083 : */
1084 308 : ropt = NewRestoreOptions();
1085 308 : ropt->filename = filename;
1086 :
1087 : /* if you change this list, see dumpOptionsFromRestoreOptions */
1088 308 : ropt->cparams.dbname = dopt.cparams.dbname ? pg_strdup(dopt.cparams.dbname) : NULL;
1089 308 : ropt->cparams.pgport = dopt.cparams.pgport ? pg_strdup(dopt.cparams.pgport) : NULL;
1090 308 : ropt->cparams.pghost = dopt.cparams.pghost ? pg_strdup(dopt.cparams.pghost) : NULL;
1091 308 : ropt->cparams.username = dopt.cparams.username ? pg_strdup(dopt.cparams.username) : NULL;
1092 308 : ropt->cparams.promptPassword = dopt.cparams.promptPassword;
1093 308 : ropt->dropSchema = dopt.outputClean;
1094 308 : ropt->dataOnly = dopt.dataOnly;
1095 308 : ropt->schemaOnly = dopt.schemaOnly;
1096 308 : ropt->if_exists = dopt.if_exists;
1097 308 : ropt->column_inserts = dopt.column_inserts;
1098 308 : ropt->dumpSections = dopt.dumpSections;
1099 308 : ropt->aclsSkip = dopt.aclsSkip;
1100 308 : ropt->superuser = dopt.outputSuperuser;
1101 308 : ropt->createDB = dopt.outputCreateDB;
1102 308 : ropt->noOwner = dopt.outputNoOwner;
1103 308 : ropt->noTableAm = dopt.outputNoTableAm;
1104 308 : ropt->noTablespace = dopt.outputNoTablespaces;
1105 308 : ropt->disable_triggers = dopt.disable_triggers;
1106 308 : ropt->use_setsessauth = dopt.use_setsessauth;
1107 308 : ropt->disable_dollar_quoting = dopt.disable_dollar_quoting;
1108 308 : ropt->dump_inserts = dopt.dump_inserts;
1109 308 : ropt->no_comments = dopt.no_comments;
1110 308 : ropt->no_publications = dopt.no_publications;
1111 308 : ropt->no_security_labels = dopt.no_security_labels;
1112 308 : ropt->no_subscriptions = dopt.no_subscriptions;
1113 308 : ropt->lockWaitTimeout = dopt.lockWaitTimeout;
1114 308 : ropt->include_everything = dopt.include_everything;
1115 308 : ropt->enable_row_security = dopt.enable_row_security;
1116 308 : ropt->sequence_data = dopt.sequence_data;
1117 308 : ropt->binary_upgrade = dopt.binary_upgrade;
1118 :
1119 308 : ropt->compression_spec = compression_spec;
1120 :
1121 308 : ropt->suppressDumpWarnings = true; /* We've already shown them */
1122 :
1123 308 : SetArchiveOptions(fout, &dopt, ropt);
1124 :
1125 : /* Mark which entries should be output */
1126 308 : ProcessArchiveRestoreOptions(fout);
1127 :
1128 : /*
1129 : * The archive's TOC entries are now marked as to which ones will actually
1130 : * be output, so we can set up their dependency lists properly. This isn't
1131 : * necessary for plain-text output, though.
1132 : */
1133 308 : if (!plainText)
1134 62 : BuildArchiveDependencies(fout);
1135 :
1136 : /*
1137 : * And finally we can do the actual output.
1138 : *
1139 : * Note: for non-plain-text output formats, the output file is written
1140 : * inside CloseArchive(). This is, um, bizarre; but not worth changing
1141 : * right now.
1142 : */
1143 308 : if (plainText)
1144 246 : RestoreArchive(fout);
1145 :
1146 306 : CloseArchive(fout);
1147 :
1148 306 : exit_nicely(0);
1149 : }
1150 :
1151 :
1152 : static void
1153 2 : help(const char *progname)
1154 : {
1155 2 : printf(_("%s dumps a database as a text file or to other formats.\n\n"), progname);
1156 2 : printf(_("Usage:\n"));
1157 2 : printf(_(" %s [OPTION]... [DBNAME]\n"), progname);
1158 :
1159 2 : printf(_("\nGeneral options:\n"));
1160 2 : printf(_(" -f, --file=FILENAME output file or directory name\n"));
1161 2 : printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
1162 : " plain text (default))\n"));
1163 2 : printf(_(" -j, --jobs=NUM use this many parallel jobs to dump\n"));
1164 2 : printf(_(" -v, --verbose verbose mode\n"));
1165 2 : printf(_(" -V, --version output version information, then exit\n"));
1166 2 : printf(_(" -Z, --compress=METHOD[:DETAIL]\n"
1167 : " compress as specified\n"));
1168 2 : printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
1169 2 : printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
1170 2 : printf(_(" --sync-method=METHOD set method for syncing files to disk\n"));
1171 2 : printf(_(" -?, --help show this help, then exit\n"));
1172 :
1173 2 : printf(_("\nOptions controlling the output content:\n"));
1174 2 : printf(_(" -a, --data-only dump only the data, not the schema\n"));
1175 2 : printf(_(" -b, --large-objects include large objects in dump\n"));
1176 2 : printf(_(" --blobs (same as --large-objects, deprecated)\n"));
1177 2 : printf(_(" -B, --no-large-objects exclude large objects in dump\n"));
1178 2 : printf(_(" --no-blobs (same as --no-large-objects, deprecated)\n"));
1179 2 : printf(_(" -c, --clean clean (drop) database objects before recreating\n"));
1180 2 : printf(_(" -C, --create include commands to create database in dump\n"));
1181 2 : printf(_(" -e, --extension=PATTERN dump the specified extension(s) only\n"));
1182 2 : printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
1183 2 : printf(_(" -n, --schema=PATTERN dump the specified schema(s) only\n"));
1184 2 : printf(_(" -N, --exclude-schema=PATTERN do NOT dump the specified schema(s)\n"));
1185 2 : printf(_(" -O, --no-owner skip restoration of object ownership in\n"
1186 : " plain-text format\n"));
1187 2 : printf(_(" -s, --schema-only dump only the schema, no data\n"));
1188 2 : printf(_(" -S, --superuser=NAME superuser user name to use in plain-text format\n"));
1189 2 : printf(_(" -t, --table=PATTERN dump only the specified table(s)\n"));
1190 2 : printf(_(" -T, --exclude-table=PATTERN do NOT dump the specified table(s)\n"));
1191 2 : printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
1192 2 : printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
1193 2 : printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
1194 2 : printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
1195 2 : printf(_(" --disable-triggers disable triggers during data-only restore\n"));
1196 2 : printf(_(" --enable-row-security enable row security (dump only content user has\n"
1197 : " access to)\n"));
1198 2 : printf(_(" --exclude-extension=PATTERN do NOT dump the specified extension(s)\n"));
1199 2 : printf(_(" --exclude-table-and-children=PATTERN\n"
1200 : " do NOT dump the specified table(s), including\n"
1201 : " child and partition tables\n"));
1202 2 : printf(_(" --exclude-table-data=PATTERN do NOT dump data for the specified table(s)\n"));
1203 2 : printf(_(" --exclude-table-data-and-children=PATTERN\n"
1204 : " do NOT dump data for the specified table(s),\n"
1205 : " including child and partition tables\n"));
1206 2 : printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
1207 2 : printf(_(" --filter=FILENAME include or exclude objects and data from dump\n"
1208 : " based on expressions in FILENAME\n"));
1209 2 : printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
1210 2 : printf(_(" --include-foreign-data=PATTERN\n"
1211 : " include data of foreign tables on foreign\n"
1212 : " servers matching PATTERN\n"));
1213 2 : printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
1214 2 : printf(_(" --load-via-partition-root load partitions via the root table\n"));
1215 2 : printf(_(" --no-comments do not dump comment commands\n"));
1216 2 : printf(_(" --no-publications do not dump publications\n"));
1217 2 : printf(_(" --no-security-labels do not dump security label assignments\n"));
1218 2 : printf(_(" --no-subscriptions do not dump subscriptions\n"));
1219 2 : printf(_(" --no-table-access-method do not dump table access methods\n"));
1220 2 : printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
1221 2 : printf(_(" --no-toast-compression do not dump TOAST compression methods\n"));
1222 2 : printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
1223 2 : printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
1224 2 : printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
1225 2 : printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
1226 2 : printf(_(" --section=SECTION dump named section (pre-data, data, or post-data)\n"));
1227 2 : printf(_(" --serializable-deferrable wait until the dump can run without anomalies\n"));
1228 2 : printf(_(" --snapshot=SNAPSHOT use given snapshot for the dump\n"));
1229 2 : printf(_(" --strict-names require table and/or schema include patterns to\n"
1230 : " match at least one entity each\n"));
1231 2 : printf(_(" --table-and-children=PATTERN dump only the specified table(s), including\n"
1232 : " child and partition tables\n"));
1233 2 : printf(_(" --use-set-session-authorization\n"
1234 : " use SET SESSION AUTHORIZATION commands instead of\n"
1235 : " ALTER OWNER commands to set ownership\n"));
1236 :
1237 2 : printf(_("\nConnection options:\n"));
1238 2 : printf(_(" -d, --dbname=DBNAME database to dump\n"));
1239 2 : printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
1240 2 : printf(_(" -p, --port=PORT database server port number\n"));
1241 2 : printf(_(" -U, --username=NAME connect as specified database user\n"));
1242 2 : printf(_(" -w, --no-password never prompt for password\n"));
1243 2 : printf(_(" -W, --password force password prompt (should happen automatically)\n"));
1244 2 : printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
1245 :
1246 2 : printf(_("\nIf no database name is supplied, then the PGDATABASE environment\n"
1247 : "variable value is used.\n\n"));
1248 2 : printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
1249 2 : printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1250 2 : }
1251 :
1252 : static void
1253 374 : setup_connection(Archive *AH, const char *dumpencoding,
1254 : const char *dumpsnapshot, char *use_role)
1255 : {
1256 374 : DumpOptions *dopt = AH->dopt;
1257 374 : PGconn *conn = GetConnection(AH);
1258 : const char *std_strings;
1259 :
1260 374 : PQclear(ExecuteSqlQueryForSingleRow(AH, ALWAYS_SECURE_SEARCH_PATH_SQL));
1261 :
1262 : /*
1263 : * Set the client encoding if requested.
1264 : */
1265 374 : if (dumpencoding)
1266 : {
1267 36 : if (PQsetClientEncoding(conn, dumpencoding) < 0)
1268 0 : pg_fatal("invalid client encoding \"%s\" specified",
1269 : dumpencoding);
1270 : }
1271 :
1272 : /*
1273 : * Get the active encoding and the standard_conforming_strings setting, so
1274 : * we know how to escape strings.
1275 : */
1276 374 : AH->encoding = PQclientEncoding(conn);
1277 :
1278 374 : std_strings = PQparameterStatus(conn, "standard_conforming_strings");
1279 374 : AH->std_strings = (std_strings && strcmp(std_strings, "on") == 0);
1280 :
1281 : /*
1282 : * Set the role if requested. In a parallel dump worker, we'll be passed
1283 : * use_role == NULL, but AH->use_role is already set (if user specified it
1284 : * originally) and we should use that.
1285 : */
1286 374 : if (!use_role && AH->use_role)
1287 4 : use_role = AH->use_role;
1288 :
1289 : /* Set the role if requested */
1290 374 : if (use_role)
1291 : {
1292 10 : PQExpBuffer query = createPQExpBuffer();
1293 :
1294 10 : appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
1295 10 : ExecuteSqlStatement(AH, query->data);
1296 10 : destroyPQExpBuffer(query);
1297 :
1298 : /* save it for possible later use by parallel workers */
1299 10 : if (!AH->use_role)
1300 6 : AH->use_role = pg_strdup(use_role);
1301 : }
1302 :
1303 : /* Set the datestyle to ISO to ensure the dump's portability */
1304 374 : ExecuteSqlStatement(AH, "SET DATESTYLE = ISO");
1305 :
1306 : /* Likewise, avoid using sql_standard intervalstyle */
1307 374 : ExecuteSqlStatement(AH, "SET INTERVALSTYLE = POSTGRES");
1308 :
1309 : /*
1310 : * Use an explicitly specified extra_float_digits if it has been provided.
1311 : * Otherwise, set extra_float_digits so that we can dump float data
1312 : * exactly (given correctly implemented float I/O code, anyway).
1313 : */
1314 374 : if (have_extra_float_digits)
1315 : {
1316 0 : PQExpBuffer q = createPQExpBuffer();
1317 :
1318 0 : appendPQExpBuffer(q, "SET extra_float_digits TO %d",
1319 : extra_float_digits);
1320 0 : ExecuteSqlStatement(AH, q->data);
1321 0 : destroyPQExpBuffer(q);
1322 : }
1323 : else
1324 374 : ExecuteSqlStatement(AH, "SET extra_float_digits TO 3");
1325 :
1326 : /*
1327 : * Disable synchronized scanning, to prevent unpredictable changes in row
1328 : * ordering across a dump and reload.
1329 : */
1330 374 : ExecuteSqlStatement(AH, "SET synchronize_seqscans TO off");
1331 :
1332 : /*
1333 : * Disable timeouts if supported.
1334 : */
1335 374 : ExecuteSqlStatement(AH, "SET statement_timeout = 0");
1336 374 : if (AH->remoteVersion >= 90300)
1337 374 : ExecuteSqlStatement(AH, "SET lock_timeout = 0");
1338 374 : if (AH->remoteVersion >= 90600)
1339 374 : ExecuteSqlStatement(AH, "SET idle_in_transaction_session_timeout = 0");
1340 374 : if (AH->remoteVersion >= 170000)
1341 374 : ExecuteSqlStatement(AH, "SET transaction_timeout = 0");
1342 :
1343 : /*
1344 : * Quote all identifiers, if requested.
1345 : */
1346 374 : if (quote_all_identifiers)
1347 24 : ExecuteSqlStatement(AH, "SET quote_all_identifiers = true");
1348 :
1349 : /*
1350 : * Adjust row-security mode, if supported.
1351 : */
1352 374 : if (AH->remoteVersion >= 90500)
1353 : {
1354 374 : if (dopt->enable_row_security)
1355 0 : ExecuteSqlStatement(AH, "SET row_security = on");
1356 : else
1357 374 : ExecuteSqlStatement(AH, "SET row_security = off");
1358 : }
1359 :
1360 : /*
1361 : * For security reasons, we restrict the expansion of non-system views and
1362 : * access to foreign tables during the pg_dump process. This restriction
1363 : * is adjusted when dumping foreign table data.
1364 : */
1365 374 : set_restrict_relation_kind(AH, "view, foreign-table");
1366 :
1367 : /*
1368 : * Initialize prepared-query state to "nothing prepared". We do this here
1369 : * so that a parallel dump worker will have its own state.
1370 : */
1371 374 : AH->is_prepared = (bool *) pg_malloc0(NUM_PREP_QUERIES * sizeof(bool));
1372 :
1373 : /*
1374 : * Start transaction-snapshot mode transaction to dump consistent data.
1375 : */
1376 374 : ExecuteSqlStatement(AH, "BEGIN");
1377 :
1378 : /*
1379 : * To support the combination of serializable_deferrable with the jobs
1380 : * option we use REPEATABLE READ for the worker connections that are
1381 : * passed a snapshot. As long as the snapshot is acquired in a
1382 : * SERIALIZABLE, READ ONLY, DEFERRABLE transaction, its use within a
1383 : * REPEATABLE READ transaction provides the appropriate integrity
1384 : * guarantees. This is a kluge, but safe for back-patching.
1385 : */
1386 374 : if (dopt->serializable_deferrable && AH->sync_snapshot_id == NULL)
1387 0 : ExecuteSqlStatement(AH,
1388 : "SET TRANSACTION ISOLATION LEVEL "
1389 : "SERIALIZABLE, READ ONLY, DEFERRABLE");
1390 : else
1391 374 : ExecuteSqlStatement(AH,
1392 : "SET TRANSACTION ISOLATION LEVEL "
1393 : "REPEATABLE READ, READ ONLY");
1394 :
1395 : /*
1396 : * If user specified a snapshot to use, select that. In a parallel dump
1397 : * worker, we'll be passed dumpsnapshot == NULL, but AH->sync_snapshot_id
1398 : * is already set (if the server can handle it) and we should use that.
1399 : */
1400 374 : if (dumpsnapshot)
1401 0 : AH->sync_snapshot_id = pg_strdup(dumpsnapshot);
1402 :
1403 374 : if (AH->sync_snapshot_id)
1404 : {
1405 32 : PQExpBuffer query = createPQExpBuffer();
1406 :
1407 32 : appendPQExpBufferStr(query, "SET TRANSACTION SNAPSHOT ");
1408 32 : appendStringLiteralConn(query, AH->sync_snapshot_id, conn);
1409 32 : ExecuteSqlStatement(AH, query->data);
1410 32 : destroyPQExpBuffer(query);
1411 : }
1412 342 : else if (AH->numWorkers > 1)
1413 : {
1414 16 : if (AH->isStandby && AH->remoteVersion < 100000)
1415 0 : pg_fatal("parallel dumps from standby servers are not supported by this server version");
1416 16 : AH->sync_snapshot_id = get_synchronized_snapshot(AH);
1417 : }
1418 374 : }
1419 :
1420 : /* Set up connection for a parallel worker process */
1421 : static void
1422 32 : setupDumpWorker(Archive *AH)
1423 : {
1424 : /*
1425 : * We want to re-select all the same values the leader connection is
1426 : * using. We'll have inherited directly-usable values in
1427 : * AH->sync_snapshot_id and AH->use_role, but we need to translate the
1428 : * inherited encoding value back to a string to pass to setup_connection.
1429 : */
1430 32 : setup_connection(AH,
1431 : pg_encoding_to_char(AH->encoding),
1432 : NULL,
1433 : NULL);
1434 32 : }
1435 :
1436 : static char *
1437 16 : get_synchronized_snapshot(Archive *fout)
1438 : {
1439 16 : char *query = "SELECT pg_catalog.pg_export_snapshot()";
1440 : char *result;
1441 : PGresult *res;
1442 :
1443 16 : res = ExecuteSqlQueryForSingleRow(fout, query);
1444 16 : result = pg_strdup(PQgetvalue(res, 0, 0));
1445 16 : PQclear(res);
1446 :
1447 16 : return result;
1448 : }
1449 :
1450 : static ArchiveFormat
1451 360 : parseArchiveFormat(const char *format, ArchiveMode *mode)
1452 : {
1453 : ArchiveFormat archiveFormat;
1454 :
1455 360 : *mode = archModeWrite;
1456 :
1457 360 : if (pg_strcasecmp(format, "a") == 0 || pg_strcasecmp(format, "append") == 0)
1458 : {
1459 : /* This is used by pg_dumpall, and is not documented */
1460 86 : archiveFormat = archNull;
1461 86 : *mode = archModeAppend;
1462 : }
1463 274 : else if (pg_strcasecmp(format, "c") == 0)
1464 8 : archiveFormat = archCustom;
1465 266 : else if (pg_strcasecmp(format, "custom") == 0)
1466 30 : archiveFormat = archCustom;
1467 236 : else if (pg_strcasecmp(format, "d") == 0)
1468 14 : archiveFormat = archDirectory;
1469 222 : else if (pg_strcasecmp(format, "directory") == 0)
1470 6 : archiveFormat = archDirectory;
1471 216 : else if (pg_strcasecmp(format, "p") == 0)
1472 202 : archiveFormat = archNull;
1473 14 : else if (pg_strcasecmp(format, "plain") == 0)
1474 6 : archiveFormat = archNull;
1475 8 : else if (pg_strcasecmp(format, "t") == 0)
1476 4 : archiveFormat = archTar;
1477 4 : else if (pg_strcasecmp(format, "tar") == 0)
1478 2 : archiveFormat = archTar;
1479 : else
1480 2 : pg_fatal("invalid output format \"%s\" specified", format);
1481 358 : return archiveFormat;
1482 : }
1483 :
1484 : /*
1485 : * Find the OIDs of all schemas matching the given list of patterns,
1486 : * and append them to the given OID list.
1487 : */
1488 : static void
1489 364 : expand_schema_name_patterns(Archive *fout,
1490 : SimpleStringList *patterns,
1491 : SimpleOidList *oids,
1492 : bool strict_names)
1493 : {
1494 : PQExpBuffer query;
1495 : PGresult *res;
1496 : SimpleStringListCell *cell;
1497 : int i;
1498 :
1499 364 : if (patterns->head == NULL)
1500 322 : return; /* nothing to do */
1501 :
1502 42 : query = createPQExpBuffer();
1503 :
1504 : /*
1505 : * The loop below runs multiple SELECTs might sometimes result in
1506 : * duplicate entries in the OID list, but we don't care.
1507 : */
1508 :
1509 72 : for (cell = patterns->head; cell; cell = cell->next)
1510 : {
1511 : PQExpBufferData dbbuf;
1512 : int dotcnt;
1513 :
1514 42 : appendPQExpBufferStr(query,
1515 : "SELECT oid FROM pg_catalog.pg_namespace n\n");
1516 42 : initPQExpBuffer(&dbbuf);
1517 42 : processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1518 : false, NULL, "n.nspname", NULL, NULL, &dbbuf,
1519 : &dotcnt);
1520 42 : if (dotcnt > 1)
1521 4 : pg_fatal("improper qualified name (too many dotted names): %s",
1522 : cell->val);
1523 38 : else if (dotcnt == 1)
1524 6 : prohibit_crossdb_refs(GetConnection(fout), dbbuf.data, cell->val);
1525 32 : termPQExpBuffer(&dbbuf);
1526 :
1527 32 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1528 32 : if (strict_names && PQntuples(res) == 0)
1529 2 : pg_fatal("no matching schemas were found for pattern \"%s\"", cell->val);
1530 :
1531 58 : for (i = 0; i < PQntuples(res); i++)
1532 : {
1533 28 : simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1534 : }
1535 :
1536 30 : PQclear(res);
1537 30 : resetPQExpBuffer(query);
1538 : }
1539 :
1540 30 : destroyPQExpBuffer(query);
1541 : }
1542 :
1543 : /*
1544 : * Find the OIDs of all extensions matching the given list of patterns,
1545 : * and append them to the given OID list.
1546 : */
1547 : static void
1548 320 : expand_extension_name_patterns(Archive *fout,
1549 : SimpleStringList *patterns,
1550 : SimpleOidList *oids,
1551 : bool strict_names)
1552 : {
1553 : PQExpBuffer query;
1554 : PGresult *res;
1555 : SimpleStringListCell *cell;
1556 : int i;
1557 :
1558 320 : if (patterns->head == NULL)
1559 306 : return; /* nothing to do */
1560 :
1561 14 : query = createPQExpBuffer();
1562 :
1563 : /*
1564 : * The loop below runs multiple SELECTs might sometimes result in
1565 : * duplicate entries in the OID list, but we don't care.
1566 : */
1567 28 : for (cell = patterns->head; cell; cell = cell->next)
1568 : {
1569 : int dotcnt;
1570 :
1571 14 : appendPQExpBufferStr(query,
1572 : "SELECT oid FROM pg_catalog.pg_extension e\n");
1573 14 : processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1574 : false, NULL, "e.extname", NULL, NULL, NULL,
1575 : &dotcnt);
1576 14 : if (dotcnt > 0)
1577 0 : pg_fatal("improper qualified name (too many dotted names): %s",
1578 : cell->val);
1579 :
1580 14 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1581 14 : if (strict_names && PQntuples(res) == 0)
1582 0 : pg_fatal("no matching extensions were found for pattern \"%s\"", cell->val);
1583 :
1584 26 : for (i = 0; i < PQntuples(res); i++)
1585 : {
1586 12 : simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1587 : }
1588 :
1589 14 : PQclear(res);
1590 14 : resetPQExpBuffer(query);
1591 : }
1592 :
1593 14 : destroyPQExpBuffer(query);
1594 : }
1595 :
1596 : /*
1597 : * Find the OIDs of all foreign servers matching the given list of patterns,
1598 : * and append them to the given OID list.
1599 : */
1600 : static void
1601 314 : expand_foreign_server_name_patterns(Archive *fout,
1602 : SimpleStringList *patterns,
1603 : SimpleOidList *oids)
1604 : {
1605 : PQExpBuffer query;
1606 : PGresult *res;
1607 : SimpleStringListCell *cell;
1608 : int i;
1609 :
1610 314 : if (patterns->head == NULL)
1611 308 : return; /* nothing to do */
1612 :
1613 6 : query = createPQExpBuffer();
1614 :
1615 : /*
1616 : * The loop below runs multiple SELECTs might sometimes result in
1617 : * duplicate entries in the OID list, but we don't care.
1618 : */
1619 :
1620 10 : for (cell = patterns->head; cell; cell = cell->next)
1621 : {
1622 : int dotcnt;
1623 :
1624 6 : appendPQExpBufferStr(query,
1625 : "SELECT oid FROM pg_catalog.pg_foreign_server s\n");
1626 6 : processSQLNamePattern(GetConnection(fout), query, cell->val, false,
1627 : false, NULL, "s.srvname", NULL, NULL, NULL,
1628 : &dotcnt);
1629 6 : if (dotcnt > 0)
1630 0 : pg_fatal("improper qualified name (too many dotted names): %s",
1631 : cell->val);
1632 :
1633 6 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1634 6 : if (PQntuples(res) == 0)
1635 2 : pg_fatal("no matching foreign servers were found for pattern \"%s\"", cell->val);
1636 :
1637 8 : for (i = 0; i < PQntuples(res); i++)
1638 4 : simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1639 :
1640 4 : PQclear(res);
1641 4 : resetPQExpBuffer(query);
1642 : }
1643 :
1644 4 : destroyPQExpBuffer(query);
1645 : }
1646 :
1647 : /*
1648 : * Find the OIDs of all tables matching the given list of patterns,
1649 : * and append them to the given OID list. See also expand_dbname_patterns()
1650 : * in pg_dumpall.c
1651 : */
1652 : static void
1653 1902 : expand_table_name_patterns(Archive *fout,
1654 : SimpleStringList *patterns, SimpleOidList *oids,
1655 : bool strict_names, bool with_child_tables)
1656 : {
1657 : PQExpBuffer query;
1658 : PGresult *res;
1659 : SimpleStringListCell *cell;
1660 : int i;
1661 :
1662 1902 : if (patterns->head == NULL)
1663 1844 : return; /* nothing to do */
1664 :
1665 58 : query = createPQExpBuffer();
1666 :
1667 : /*
1668 : * this might sometimes result in duplicate entries in the OID list, but
1669 : * we don't care.
1670 : */
1671 :
1672 118 : for (cell = patterns->head; cell; cell = cell->next)
1673 : {
1674 : PQExpBufferData dbbuf;
1675 : int dotcnt;
1676 :
1677 : /*
1678 : * Query must remain ABSOLUTELY devoid of unqualified names. This
1679 : * would be unnecessary given a pg_table_is_visible() variant taking a
1680 : * search_path argument.
1681 : *
1682 : * For with_child_tables, we start with the basic query's results and
1683 : * recursively search the inheritance tree to add child tables.
1684 : */
1685 70 : if (with_child_tables)
1686 : {
1687 12 : appendPQExpBuffer(query, "WITH RECURSIVE partition_tree (relid) AS (\n");
1688 : }
1689 :
1690 70 : appendPQExpBuffer(query,
1691 : "SELECT c.oid"
1692 : "\nFROM pg_catalog.pg_class c"
1693 : "\n LEFT JOIN pg_catalog.pg_namespace n"
1694 : "\n ON n.oid OPERATOR(pg_catalog.=) c.relnamespace"
1695 : "\nWHERE c.relkind OPERATOR(pg_catalog.=) ANY"
1696 : "\n (array['%c', '%c', '%c', '%c', '%c', '%c'])\n",
1697 : RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW,
1698 : RELKIND_MATVIEW, RELKIND_FOREIGN_TABLE,
1699 : RELKIND_PARTITIONED_TABLE);
1700 70 : initPQExpBuffer(&dbbuf);
1701 70 : processSQLNamePattern(GetConnection(fout), query, cell->val, true,
1702 : false, "n.nspname", "c.relname", NULL,
1703 : "pg_catalog.pg_table_is_visible(c.oid)", &dbbuf,
1704 : &dotcnt);
1705 70 : if (dotcnt > 2)
1706 2 : pg_fatal("improper relation name (too many dotted names): %s",
1707 : cell->val);
1708 68 : else if (dotcnt == 2)
1709 4 : prohibit_crossdb_refs(GetConnection(fout), dbbuf.data, cell->val);
1710 64 : termPQExpBuffer(&dbbuf);
1711 :
1712 64 : if (with_child_tables)
1713 : {
1714 12 : appendPQExpBuffer(query, "UNION"
1715 : "\nSELECT i.inhrelid"
1716 : "\nFROM partition_tree p"
1717 : "\n JOIN pg_catalog.pg_inherits i"
1718 : "\n ON p.relid OPERATOR(pg_catalog.=) i.inhparent"
1719 : "\n)"
1720 : "\nSELECT relid FROM partition_tree");
1721 : }
1722 :
1723 64 : ExecuteSqlStatement(fout, "RESET search_path");
1724 64 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
1725 64 : PQclear(ExecuteSqlQueryForSingleRow(fout,
1726 : ALWAYS_SECURE_SEARCH_PATH_SQL));
1727 64 : if (strict_names && PQntuples(res) == 0)
1728 4 : pg_fatal("no matching tables were found for pattern \"%s\"", cell->val);
1729 :
1730 148 : for (i = 0; i < PQntuples(res); i++)
1731 : {
1732 88 : simple_oid_list_append(oids, atooid(PQgetvalue(res, i, 0)));
1733 : }
1734 :
1735 60 : PQclear(res);
1736 60 : resetPQExpBuffer(query);
1737 : }
1738 :
1739 48 : destroyPQExpBuffer(query);
1740 : }
1741 :
1742 : /*
1743 : * Verifies that the connected database name matches the given database name,
1744 : * and if not, dies with an error about the given pattern.
1745 : *
1746 : * The 'dbname' argument should be a literal name parsed from 'pattern'.
1747 : */
1748 : static void
1749 10 : prohibit_crossdb_refs(PGconn *conn, const char *dbname, const char *pattern)
1750 : {
1751 : const char *db;
1752 :
1753 10 : db = PQdb(conn);
1754 10 : if (db == NULL)
1755 0 : pg_fatal("You are currently not connected to a database.");
1756 :
1757 10 : if (strcmp(db, dbname) != 0)
1758 10 : pg_fatal("cross-database references are not implemented: %s",
1759 : pattern);
1760 0 : }
1761 :
1762 : /*
1763 : * checkExtensionMembership
1764 : * Determine whether object is an extension member, and if so,
1765 : * record an appropriate dependency and set the object's dump flag.
1766 : *
1767 : * It's important to call this for each object that could be an extension
1768 : * member. Generally, we integrate this with determining the object's
1769 : * to-be-dumped-ness, since extension membership overrides other rules for that.
1770 : *
1771 : * Returns true if object is an extension member, else false.
1772 : */
1773 : static bool
1774 959582 : checkExtensionMembership(DumpableObject *dobj, Archive *fout)
1775 : {
1776 959582 : ExtensionInfo *ext = findOwningExtension(dobj->catId);
1777 :
1778 959582 : if (ext == NULL)
1779 958190 : return false;
1780 :
1781 1392 : dobj->ext_member = true;
1782 :
1783 : /* Record dependency so that getDependencies needn't deal with that */
1784 1392 : addObjectDependency(dobj, ext->dobj.dumpId);
1785 :
1786 : /*
1787 : * In 9.6 and above, mark the member object to have any non-initial ACLs
1788 : * dumped. (Any initial ACLs will be removed later, using data from
1789 : * pg_init_privs, so that we'll dump only the delta from the extension's
1790 : * initial setup.)
1791 : *
1792 : * Prior to 9.6, we do not include any extension member components.
1793 : *
1794 : * In binary upgrades, we still dump all components of the members
1795 : * individually, since the idea is to exactly reproduce the database
1796 : * contents rather than replace the extension contents with something
1797 : * different.
1798 : *
1799 : * Note: it might be interesting someday to implement storage and delta
1800 : * dumping of extension members' RLS policies and/or security labels.
1801 : * However there is a pitfall for RLS policies: trying to dump them
1802 : * requires getting a lock on their tables, and the calling user might not
1803 : * have privileges for that. We need no lock to examine a table's ACLs,
1804 : * so the current feature doesn't have a problem of that sort.
1805 : */
1806 1392 : if (fout->dopt->binary_upgrade)
1807 152 : dobj->dump = ext->dobj.dump;
1808 : else
1809 : {
1810 1240 : if (fout->remoteVersion < 90600)
1811 0 : dobj->dump = DUMP_COMPONENT_NONE;
1812 : else
1813 1240 : dobj->dump = ext->dobj.dump_contains & (DUMP_COMPONENT_ACL);
1814 : }
1815 :
1816 1392 : return true;
1817 : }
1818 :
1819 : /*
1820 : * selectDumpableNamespace: policy-setting subroutine
1821 : * Mark a namespace as to be dumped or not
1822 : */
1823 : static void
1824 2534 : selectDumpableNamespace(NamespaceInfo *nsinfo, Archive *fout)
1825 : {
1826 : /*
1827 : * DUMP_COMPONENT_DEFINITION typically implies a CREATE SCHEMA statement
1828 : * and (for --clean) a DROP SCHEMA statement. (In the absence of
1829 : * DUMP_COMPONENT_DEFINITION, this value is irrelevant.)
1830 : */
1831 2534 : nsinfo->create = true;
1832 :
1833 : /*
1834 : * If specific tables are being dumped, do not dump any complete
1835 : * namespaces. If specific namespaces are being dumped, dump just those
1836 : * namespaces. Otherwise, dump all non-system namespaces.
1837 : */
1838 2534 : if (table_include_oids.head != NULL)
1839 100 : nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1840 2434 : else if (schema_include_oids.head != NULL)
1841 354 : nsinfo->dobj.dump_contains = nsinfo->dobj.dump =
1842 354 : simple_oid_list_member(&schema_include_oids,
1843 : nsinfo->dobj.catId.oid) ?
1844 354 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1845 2080 : else if (fout->remoteVersion >= 90600 &&
1846 2080 : strcmp(nsinfo->dobj.name, "pg_catalog") == 0)
1847 : {
1848 : /*
1849 : * In 9.6 and above, we dump out any ACLs defined in pg_catalog, if
1850 : * they are interesting (and not the original ACLs which were set at
1851 : * initdb time, see pg_init_privs).
1852 : */
1853 266 : nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ACL;
1854 : }
1855 1814 : else if (strncmp(nsinfo->dobj.name, "pg_", 3) == 0 ||
1856 820 : strcmp(nsinfo->dobj.name, "information_schema") == 0)
1857 : {
1858 : /* Other system schemas don't get dumped */
1859 1260 : nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1860 : }
1861 554 : else if (strcmp(nsinfo->dobj.name, "public") == 0)
1862 : {
1863 : /*
1864 : * The public schema is a strange beast that sits in a sort of
1865 : * no-mans-land between being a system object and a user object.
1866 : * CREATE SCHEMA would fail, so its DUMP_COMPONENT_DEFINITION is just
1867 : * a comment and an indication of ownership. If the owner is the
1868 : * default, omit that superfluous DUMP_COMPONENT_DEFINITION. Before
1869 : * v15, the default owner was BOOTSTRAP_SUPERUSERID.
1870 : */
1871 258 : nsinfo->create = false;
1872 258 : nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1873 258 : if (nsinfo->nspowner == ROLE_PG_DATABASE_OWNER)
1874 178 : nsinfo->dobj.dump &= ~DUMP_COMPONENT_DEFINITION;
1875 258 : nsinfo->dobj.dump_contains = DUMP_COMPONENT_ALL;
1876 :
1877 : /*
1878 : * Also, make like it has a comment even if it doesn't; this is so
1879 : * that we'll emit a command to drop the comment, if appropriate.
1880 : * (Without this, we'd not call dumpCommentExtended for it.)
1881 : */
1882 258 : nsinfo->dobj.components |= DUMP_COMPONENT_COMMENT;
1883 : }
1884 : else
1885 296 : nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_ALL;
1886 :
1887 : /*
1888 : * In any case, a namespace can be excluded by an exclusion switch
1889 : */
1890 3376 : if (nsinfo->dobj.dump_contains &&
1891 842 : simple_oid_list_member(&schema_exclude_oids,
1892 : nsinfo->dobj.catId.oid))
1893 6 : nsinfo->dobj.dump_contains = nsinfo->dobj.dump = DUMP_COMPONENT_NONE;
1894 :
1895 : /*
1896 : * If the schema belongs to an extension, allow extension membership to
1897 : * override the dump decision for the schema itself. However, this does
1898 : * not change dump_contains, so this won't change what we do with objects
1899 : * within the schema. (If they belong to the extension, they'll get
1900 : * suppressed by it, otherwise not.)
1901 : */
1902 2534 : (void) checkExtensionMembership(&nsinfo->dobj, fout);
1903 2534 : }
1904 :
1905 : /*
1906 : * selectDumpableTable: policy-setting subroutine
1907 : * Mark a table as to be dumped or not
1908 : */
1909 : static void
1910 81064 : selectDumpableTable(TableInfo *tbinfo, Archive *fout)
1911 : {
1912 81064 : if (checkExtensionMembership(&tbinfo->dobj, fout))
1913 450 : return; /* extension membership overrides all else */
1914 :
1915 : /*
1916 : * If specific tables are being dumped, dump just those tables; else, dump
1917 : * according to the parent namespace's dump flag.
1918 : */
1919 80614 : if (table_include_oids.head != NULL)
1920 10104 : tbinfo->dobj.dump = simple_oid_list_member(&table_include_oids,
1921 : tbinfo->dobj.catId.oid) ?
1922 5052 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
1923 : else
1924 75562 : tbinfo->dobj.dump = tbinfo->dobj.namespace->dobj.dump_contains;
1925 :
1926 : /*
1927 : * In any case, a table can be excluded by an exclusion switch
1928 : */
1929 130642 : if (tbinfo->dobj.dump &&
1930 50028 : simple_oid_list_member(&table_exclude_oids,
1931 : tbinfo->dobj.catId.oid))
1932 24 : tbinfo->dobj.dump = DUMP_COMPONENT_NONE;
1933 : }
1934 :
1935 : /*
1936 : * selectDumpableType: policy-setting subroutine
1937 : * Mark a type as to be dumped or not
1938 : *
1939 : * If it's a table's rowtype or an autogenerated array type, we also apply a
1940 : * special type code to facilitate sorting into the desired order. (We don't
1941 : * want to consider those to be ordinary types because that would bring tables
1942 : * up into the datatype part of the dump order.) We still set the object's
1943 : * dump flag; that's not going to cause the dummy type to be dumped, but we
1944 : * need it so that casts involving such types will be dumped correctly -- see
1945 : * dumpCast. This means the flag should be set the same as for the underlying
1946 : * object (the table or base type).
1947 : */
1948 : static void
1949 221912 : selectDumpableType(TypeInfo *tyinfo, Archive *fout)
1950 : {
1951 : /* skip complex types, except for standalone composite types */
1952 221912 : if (OidIsValid(tyinfo->typrelid) &&
1953 79724 : tyinfo->typrelkind != RELKIND_COMPOSITE_TYPE)
1954 : {
1955 79364 : TableInfo *tytable = findTableByOid(tyinfo->typrelid);
1956 :
1957 79364 : tyinfo->dobj.objType = DO_DUMMY_TYPE;
1958 79364 : if (tytable != NULL)
1959 79364 : tyinfo->dobj.dump = tytable->dobj.dump;
1960 : else
1961 0 : tyinfo->dobj.dump = DUMP_COMPONENT_NONE;
1962 79364 : return;
1963 : }
1964 :
1965 : /* skip auto-generated array and multirange types */
1966 142548 : if (tyinfo->isArray || tyinfo->isMultirange)
1967 : {
1968 108516 : tyinfo->dobj.objType = DO_DUMMY_TYPE;
1969 :
1970 : /*
1971 : * Fall through to set the dump flag; we assume that the subsequent
1972 : * rules will do the same thing as they would for the array's base
1973 : * type or multirange's range type. (We cannot reliably look up the
1974 : * base type here, since getTypes may not have processed it yet.)
1975 : */
1976 : }
1977 :
1978 142548 : if (checkExtensionMembership(&tyinfo->dobj, fout))
1979 300 : return; /* extension membership overrides all else */
1980 :
1981 : /* Dump based on if the contents of the namespace are being dumped */
1982 142248 : tyinfo->dobj.dump = tyinfo->dobj.namespace->dobj.dump_contains;
1983 : }
1984 :
1985 : /*
1986 : * selectDumpableDefaultACL: policy-setting subroutine
1987 : * Mark a default ACL as to be dumped or not
1988 : *
1989 : * For per-schema default ACLs, dump if the schema is to be dumped.
1990 : * Otherwise dump if we are dumping "everything". Note that dataOnly
1991 : * and aclsSkip are checked separately.
1992 : */
1993 : static void
1994 344 : selectDumpableDefaultACL(DefaultACLInfo *dinfo, DumpOptions *dopt)
1995 : {
1996 : /* Default ACLs can't be extension members */
1997 :
1998 344 : if (dinfo->dobj.namespace)
1999 : /* default ACLs are considered part of the namespace */
2000 172 : dinfo->dobj.dump = dinfo->dobj.namespace->dobj.dump_contains;
2001 : else
2002 172 : dinfo->dobj.dump = dopt->include_everything ?
2003 172 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2004 344 : }
2005 :
2006 : /*
2007 : * selectDumpableCast: policy-setting subroutine
2008 : * Mark a cast as to be dumped or not
2009 : *
2010 : * Casts do not belong to any particular namespace (since they haven't got
2011 : * names), nor do they have identifiable owners. To distinguish user-defined
2012 : * casts from built-in ones, we must resort to checking whether the cast's
2013 : * OID is in the range reserved for initdb.
2014 : */
2015 : static void
2016 68854 : selectDumpableCast(CastInfo *cast, Archive *fout)
2017 : {
2018 68854 : if (checkExtensionMembership(&cast->dobj, fout))
2019 0 : return; /* extension membership overrides all else */
2020 :
2021 : /*
2022 : * This would be DUMP_COMPONENT_ACL for from-initdb casts, but they do not
2023 : * support ACLs currently.
2024 : */
2025 68854 : if (cast->dobj.catId.oid <= (Oid) g_last_builtin_oid)
2026 68684 : cast->dobj.dump = DUMP_COMPONENT_NONE;
2027 : else
2028 170 : cast->dobj.dump = fout->dopt->include_everything ?
2029 170 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2030 : }
2031 :
2032 : /*
2033 : * selectDumpableProcLang: policy-setting subroutine
2034 : * Mark a procedural language as to be dumped or not
2035 : *
2036 : * Procedural languages do not belong to any particular namespace. To
2037 : * identify built-in languages, we must resort to checking whether the
2038 : * language's OID is in the range reserved for initdb.
2039 : */
2040 : static void
2041 394 : selectDumpableProcLang(ProcLangInfo *plang, Archive *fout)
2042 : {
2043 394 : if (checkExtensionMembership(&plang->dobj, fout))
2044 308 : return; /* extension membership overrides all else */
2045 :
2046 : /*
2047 : * Only include procedural languages when we are dumping everything.
2048 : *
2049 : * For from-initdb procedural languages, only include ACLs, as we do for
2050 : * the pg_catalog namespace. We need this because procedural languages do
2051 : * not live in any namespace.
2052 : */
2053 86 : if (!fout->dopt->include_everything)
2054 16 : plang->dobj.dump = DUMP_COMPONENT_NONE;
2055 : else
2056 : {
2057 70 : if (plang->dobj.catId.oid <= (Oid) g_last_builtin_oid)
2058 0 : plang->dobj.dump = fout->remoteVersion < 90600 ?
2059 0 : DUMP_COMPONENT_NONE : DUMP_COMPONENT_ACL;
2060 : else
2061 70 : plang->dobj.dump = DUMP_COMPONENT_ALL;
2062 : }
2063 : }
2064 :
2065 : /*
2066 : * selectDumpableAccessMethod: policy-setting subroutine
2067 : * Mark an access method as to be dumped or not
2068 : *
2069 : * Access methods do not belong to any particular namespace. To identify
2070 : * built-in access methods, we must resort to checking whether the
2071 : * method's OID is in the range reserved for initdb.
2072 : */
2073 : static void
2074 2392 : selectDumpableAccessMethod(AccessMethodInfo *method, Archive *fout)
2075 : {
2076 2392 : if (checkExtensionMembership(&method->dobj, fout))
2077 50 : return; /* extension membership overrides all else */
2078 :
2079 : /*
2080 : * This would be DUMP_COMPONENT_ACL for from-initdb access methods, but
2081 : * they do not support ACLs currently.
2082 : */
2083 2342 : if (method->dobj.catId.oid <= (Oid) g_last_builtin_oid)
2084 2156 : method->dobj.dump = DUMP_COMPONENT_NONE;
2085 : else
2086 186 : method->dobj.dump = fout->dopt->include_everything ?
2087 186 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2088 : }
2089 :
2090 : /*
2091 : * selectDumpableExtension: policy-setting subroutine
2092 : * Mark an extension as to be dumped or not
2093 : *
2094 : * Built-in extensions should be skipped except for checking ACLs, since we
2095 : * assume those will already be installed in the target database. We identify
2096 : * such extensions by their having OIDs in the range reserved for initdb.
2097 : * We dump all user-added extensions by default. No extensions are dumped
2098 : * if include_everything is false (i.e., a --schema or --table switch was
2099 : * given), except if --extension specifies a list of extensions to dump.
2100 : */
2101 : static void
2102 360 : selectDumpableExtension(ExtensionInfo *extinfo, DumpOptions *dopt)
2103 : {
2104 : /*
2105 : * Use DUMP_COMPONENT_ACL for built-in extensions, to allow users to
2106 : * change permissions on their member objects, if they wish to, and have
2107 : * those changes preserved.
2108 : */
2109 360 : if (extinfo->dobj.catId.oid <= (Oid) g_last_builtin_oid)
2110 310 : extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_ACL;
2111 : else
2112 : {
2113 : /* check if there is a list of extensions to dump */
2114 50 : if (extension_include_oids.head != NULL)
2115 8 : extinfo->dobj.dump = extinfo->dobj.dump_contains =
2116 8 : simple_oid_list_member(&extension_include_oids,
2117 : extinfo->dobj.catId.oid) ?
2118 8 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2119 : else
2120 42 : extinfo->dobj.dump = extinfo->dobj.dump_contains =
2121 42 : dopt->include_everything ?
2122 42 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2123 :
2124 : /* check that the extension is not explicitly excluded */
2125 92 : if (extinfo->dobj.dump &&
2126 42 : simple_oid_list_member(&extension_exclude_oids,
2127 : extinfo->dobj.catId.oid))
2128 4 : extinfo->dobj.dump = extinfo->dobj.dump_contains = DUMP_COMPONENT_NONE;
2129 : }
2130 360 : }
2131 :
2132 : /*
2133 : * selectDumpablePublicationObject: policy-setting subroutine
2134 : * Mark a publication object as to be dumped or not
2135 : *
2136 : * A publication can have schemas and tables which have schemas, but those are
2137 : * ignored in decision making, because publications are only dumped when we are
2138 : * dumping everything.
2139 : */
2140 : static void
2141 652 : selectDumpablePublicationObject(DumpableObject *dobj, Archive *fout)
2142 : {
2143 652 : if (checkExtensionMembership(dobj, fout))
2144 0 : return; /* extension membership overrides all else */
2145 :
2146 652 : dobj->dump = fout->dopt->include_everything ?
2147 652 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2148 : }
2149 :
2150 : /*
2151 : * selectDumpableStatisticsObject: policy-setting subroutine
2152 : * Mark an extended statistics object as to be dumped or not
2153 : *
2154 : * We dump an extended statistics object if the schema it's in and the table
2155 : * it's for are being dumped. (This'll need more thought if statistics
2156 : * objects ever support cross-table stats.)
2157 : */
2158 : static void
2159 314 : selectDumpableStatisticsObject(StatsExtInfo *sobj, Archive *fout)
2160 : {
2161 314 : if (checkExtensionMembership(&sobj->dobj, fout))
2162 0 : return; /* extension membership overrides all else */
2163 :
2164 314 : sobj->dobj.dump = sobj->dobj.namespace->dobj.dump_contains;
2165 314 : if (sobj->stattable == NULL ||
2166 314 : !(sobj->stattable->dobj.dump & DUMP_COMPONENT_DEFINITION))
2167 56 : sobj->dobj.dump = DUMP_COMPONENT_NONE;
2168 : }
2169 :
2170 : /*
2171 : * selectDumpableObject: policy-setting subroutine
2172 : * Mark a generic dumpable object as to be dumped or not
2173 : *
2174 : * Use this only for object types without a special-case routine above.
2175 : */
2176 : static void
2177 660830 : selectDumpableObject(DumpableObject *dobj, Archive *fout)
2178 : {
2179 660830 : if (checkExtensionMembership(dobj, fout))
2180 234 : return; /* extension membership overrides all else */
2181 :
2182 : /*
2183 : * Default policy is to dump if parent namespace is dumpable, or for
2184 : * non-namespace-associated items, dump if we're dumping "everything".
2185 : */
2186 660596 : if (dobj->namespace)
2187 659426 : dobj->dump = dobj->namespace->dobj.dump_contains;
2188 : else
2189 1170 : dobj->dump = fout->dopt->include_everything ?
2190 1170 : DUMP_COMPONENT_ALL : DUMP_COMPONENT_NONE;
2191 : }
2192 :
2193 : /*
2194 : * Dump a table's contents for loading using the COPY command
2195 : * - this routine is called by the Archiver when it wants the table
2196 : * to be dumped.
2197 : */
2198 : static int
2199 7018 : dumpTableData_copy(Archive *fout, const void *dcontext)
2200 : {
2201 7018 : TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
2202 7018 : TableInfo *tbinfo = tdinfo->tdtable;
2203 7018 : const char *classname = tbinfo->dobj.name;
2204 7018 : PQExpBuffer q = createPQExpBuffer();
2205 :
2206 : /*
2207 : * Note: can't use getThreadLocalPQExpBuffer() here, we're calling fmtId
2208 : * which uses it already.
2209 : */
2210 7018 : PQExpBuffer clistBuf = createPQExpBuffer();
2211 7018 : PGconn *conn = GetConnection(fout);
2212 : PGresult *res;
2213 : int ret;
2214 : char *copybuf;
2215 : const char *column_list;
2216 :
2217 7018 : pg_log_info("dumping contents of table \"%s.%s\"",
2218 : tbinfo->dobj.namespace->dobj.name, classname);
2219 :
2220 : /*
2221 : * Specify the column list explicitly so that we have no possibility of
2222 : * retrieving data in the wrong column order. (The default column
2223 : * ordering of COPY will not be what we want in certain corner cases
2224 : * involving ADD COLUMN and inheritance.)
2225 : */
2226 7018 : column_list = fmtCopyColumnList(tbinfo, clistBuf);
2227 :
2228 : /*
2229 : * Use COPY (SELECT ...) TO when dumping a foreign table's data, and when
2230 : * a filter condition was specified. For other cases a simple COPY
2231 : * suffices.
2232 : */
2233 7018 : if (tdinfo->filtercond || tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2234 : {
2235 : /* Temporary allows to access to foreign tables to dump data */
2236 2 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2237 2 : set_restrict_relation_kind(fout, "view");
2238 :
2239 2 : appendPQExpBufferStr(q, "COPY (SELECT ");
2240 : /* klugery to get rid of parens in column list */
2241 2 : if (strlen(column_list) > 2)
2242 : {
2243 2 : appendPQExpBufferStr(q, column_list + 1);
2244 2 : q->data[q->len - 1] = ' ';
2245 : }
2246 : else
2247 0 : appendPQExpBufferStr(q, "* ");
2248 :
2249 4 : appendPQExpBuffer(q, "FROM %s %s) TO stdout;",
2250 2 : fmtQualifiedDumpable(tbinfo),
2251 2 : tdinfo->filtercond ? tdinfo->filtercond : "");
2252 : }
2253 : else
2254 : {
2255 7016 : appendPQExpBuffer(q, "COPY %s %s TO stdout;",
2256 7016 : fmtQualifiedDumpable(tbinfo),
2257 : column_list);
2258 : }
2259 7018 : res = ExecuteSqlQuery(fout, q->data, PGRES_COPY_OUT);
2260 7016 : PQclear(res);
2261 7016 : destroyPQExpBuffer(clistBuf);
2262 :
2263 : for (;;)
2264 : {
2265 3601690 : ret = PQgetCopyData(conn, ©buf, 0);
2266 :
2267 3601690 : if (ret < 0)
2268 7016 : break; /* done or error */
2269 :
2270 3594674 : if (copybuf)
2271 : {
2272 3594674 : WriteData(fout, copybuf, ret);
2273 3594674 : PQfreemem(copybuf);
2274 : }
2275 :
2276 : /* ----------
2277 : * THROTTLE:
2278 : *
2279 : * There was considerable discussion in late July, 2000 regarding
2280 : * slowing down pg_dump when backing up large tables. Users with both
2281 : * slow & fast (multi-processor) machines experienced performance
2282 : * degradation when doing a backup.
2283 : *
2284 : * Initial attempts based on sleeping for a number of ms for each ms
2285 : * of work were deemed too complex, then a simple 'sleep in each loop'
2286 : * implementation was suggested. The latter failed because the loop
2287 : * was too tight. Finally, the following was implemented:
2288 : *
2289 : * If throttle is non-zero, then
2290 : * See how long since the last sleep.
2291 : * Work out how long to sleep (based on ratio).
2292 : * If sleep is more than 100ms, then
2293 : * sleep
2294 : * reset timer
2295 : * EndIf
2296 : * EndIf
2297 : *
2298 : * where the throttle value was the number of ms to sleep per ms of
2299 : * work. The calculation was done in each loop.
2300 : *
2301 : * Most of the hard work is done in the backend, and this solution
2302 : * still did not work particularly well: on slow machines, the ratio
2303 : * was 50:1, and on medium paced machines, 1:1, and on fast
2304 : * multi-processor machines, it had little or no effect, for reasons
2305 : * that were unclear.
2306 : *
2307 : * Further discussion ensued, and the proposal was dropped.
2308 : *
2309 : * For those people who want this feature, it can be implemented using
2310 : * gettimeofday in each loop, calculating the time since last sleep,
2311 : * multiplying that by the sleep ratio, then if the result is more
2312 : * than a preset 'minimum sleep time' (say 100ms), call the 'select'
2313 : * function to sleep for a subsecond period ie.
2314 : *
2315 : * select(0, NULL, NULL, NULL, &tvi);
2316 : *
2317 : * This will return after the interval specified in the structure tvi.
2318 : * Finally, call gettimeofday again to save the 'last sleep time'.
2319 : * ----------
2320 : */
2321 : }
2322 7016 : archprintf(fout, "\\.\n\n\n");
2323 :
2324 7016 : if (ret == -2)
2325 : {
2326 : /* copy data transfer failed */
2327 0 : pg_log_error("Dumping the contents of table \"%s\" failed: PQgetCopyData() failed.", classname);
2328 0 : pg_log_error_detail("Error message from server: %s", PQerrorMessage(conn));
2329 0 : pg_log_error_detail("Command was: %s", q->data);
2330 0 : exit_nicely(1);
2331 : }
2332 :
2333 : /* Check command status and return to normal libpq state */
2334 7016 : res = PQgetResult(conn);
2335 7016 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
2336 : {
2337 0 : pg_log_error("Dumping the contents of table \"%s\" failed: PQgetResult() failed.", classname);
2338 0 : pg_log_error_detail("Error message from server: %s", PQerrorMessage(conn));
2339 0 : pg_log_error_detail("Command was: %s", q->data);
2340 0 : exit_nicely(1);
2341 : }
2342 7016 : PQclear(res);
2343 :
2344 : /* Do this to ensure we've pumped libpq back to idle state */
2345 7016 : if (PQgetResult(conn) != NULL)
2346 0 : pg_log_warning("unexpected extra results during COPY of table \"%s\"",
2347 : classname);
2348 :
2349 7016 : destroyPQExpBuffer(q);
2350 :
2351 : /* Revert back the setting */
2352 7016 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2353 0 : set_restrict_relation_kind(fout, "view, foreign-table");
2354 :
2355 7016 : return 1;
2356 : }
2357 :
2358 : /*
2359 : * Dump table data using INSERT commands.
2360 : *
2361 : * Caution: when we restore from an archive file direct to database, the
2362 : * INSERT commands emitted by this function have to be parsed by
2363 : * pg_backup_db.c's ExecuteSimpleCommands(), which will not handle comments,
2364 : * E'' strings, or dollar-quoted strings. So don't emit anything like that.
2365 : */
2366 : static int
2367 138 : dumpTableData_insert(Archive *fout, const void *dcontext)
2368 : {
2369 138 : TableDataInfo *tdinfo = (TableDataInfo *) dcontext;
2370 138 : TableInfo *tbinfo = tdinfo->tdtable;
2371 138 : DumpOptions *dopt = fout->dopt;
2372 138 : PQExpBuffer q = createPQExpBuffer();
2373 138 : PQExpBuffer insertStmt = NULL;
2374 : char *attgenerated;
2375 : PGresult *res;
2376 : int nfields,
2377 : i;
2378 138 : int rows_per_statement = dopt->dump_inserts;
2379 138 : int rows_this_statement = 0;
2380 :
2381 : /* Temporary allows to access to foreign tables to dump data */
2382 138 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2383 0 : set_restrict_relation_kind(fout, "view");
2384 :
2385 : /*
2386 : * If we're going to emit INSERTs with column names, the most efficient
2387 : * way to deal with generated columns is to exclude them entirely. For
2388 : * INSERTs without column names, we have to emit DEFAULT rather than the
2389 : * actual column value --- but we can save a few cycles by fetching nulls
2390 : * rather than the uninteresting-to-us value.
2391 : */
2392 138 : attgenerated = (char *) pg_malloc(tbinfo->numatts * sizeof(char));
2393 138 : appendPQExpBufferStr(q, "DECLARE _pg_dump_cursor CURSOR FOR SELECT ");
2394 138 : nfields = 0;
2395 442 : for (i = 0; i < tbinfo->numatts; i++)
2396 : {
2397 304 : if (tbinfo->attisdropped[i])
2398 4 : continue;
2399 300 : if (tbinfo->attgenerated[i] && dopt->column_inserts)
2400 10 : continue;
2401 290 : if (nfields > 0)
2402 166 : appendPQExpBufferStr(q, ", ");
2403 290 : if (tbinfo->attgenerated[i])
2404 10 : appendPQExpBufferStr(q, "NULL");
2405 : else
2406 280 : appendPQExpBufferStr(q, fmtId(tbinfo->attnames[i]));
2407 290 : attgenerated[nfields] = tbinfo->attgenerated[i];
2408 290 : nfields++;
2409 : }
2410 : /* Servers before 9.4 will complain about zero-column SELECT */
2411 138 : if (nfields == 0)
2412 14 : appendPQExpBufferStr(q, "NULL");
2413 138 : appendPQExpBuffer(q, " FROM ONLY %s",
2414 138 : fmtQualifiedDumpable(tbinfo));
2415 138 : if (tdinfo->filtercond)
2416 0 : appendPQExpBuffer(q, " %s", tdinfo->filtercond);
2417 :
2418 138 : ExecuteSqlStatement(fout, q->data);
2419 :
2420 : while (1)
2421 : {
2422 238 : res = ExecuteSqlQuery(fout, "FETCH 100 FROM _pg_dump_cursor",
2423 : PGRES_TUPLES_OK);
2424 :
2425 : /* cross-check field count, allowing for dummy NULL if any */
2426 238 : if (nfields != PQnfields(res) &&
2427 20 : !(nfields == 0 && PQnfields(res) == 1))
2428 0 : pg_fatal("wrong number of fields retrieved from table \"%s\"",
2429 : tbinfo->dobj.name);
2430 :
2431 : /*
2432 : * First time through, we build as much of the INSERT statement as
2433 : * possible in "insertStmt", which we can then just print for each
2434 : * statement. If the table happens to have zero dumpable columns then
2435 : * this will be a complete statement, otherwise it will end in
2436 : * "VALUES" and be ready to have the row's column values printed.
2437 : */
2438 238 : if (insertStmt == NULL)
2439 : {
2440 : TableInfo *targettab;
2441 :
2442 138 : insertStmt = createPQExpBuffer();
2443 :
2444 : /*
2445 : * When load-via-partition-root is set or forced, get the root
2446 : * table name for the partition table, so that we can reload data
2447 : * through the root table.
2448 : */
2449 138 : if (tbinfo->ispartition &&
2450 80 : (dopt->load_via_partition_root ||
2451 40 : forcePartitionRootLoad(tbinfo)))
2452 6 : targettab = getRootTableInfo(tbinfo);
2453 : else
2454 132 : targettab = tbinfo;
2455 :
2456 138 : appendPQExpBuffer(insertStmt, "INSERT INTO %s ",
2457 138 : fmtQualifiedDumpable(targettab));
2458 :
2459 : /* corner case for zero-column table */
2460 138 : if (nfields == 0)
2461 : {
2462 14 : appendPQExpBufferStr(insertStmt, "DEFAULT VALUES;\n");
2463 : }
2464 : else
2465 : {
2466 : /* append the list of column names if required */
2467 124 : if (dopt->column_inserts)
2468 : {
2469 54 : appendPQExpBufferChar(insertStmt, '(');
2470 176 : for (int field = 0; field < nfields; field++)
2471 : {
2472 122 : if (field > 0)
2473 68 : appendPQExpBufferStr(insertStmt, ", ");
2474 122 : appendPQExpBufferStr(insertStmt,
2475 122 : fmtId(PQfname(res, field)));
2476 : }
2477 54 : appendPQExpBufferStr(insertStmt, ") ");
2478 : }
2479 :
2480 124 : if (tbinfo->needs_override)
2481 4 : appendPQExpBufferStr(insertStmt, "OVERRIDING SYSTEM VALUE ");
2482 :
2483 124 : appendPQExpBufferStr(insertStmt, "VALUES");
2484 : }
2485 : }
2486 :
2487 6380 : for (int tuple = 0; tuple < PQntuples(res); tuple++)
2488 : {
2489 : /* Write the INSERT if not in the middle of a multi-row INSERT. */
2490 6142 : if (rows_this_statement == 0)
2491 6130 : archputs(insertStmt->data, fout);
2492 :
2493 : /*
2494 : * If it is zero-column table then we've already written the
2495 : * complete statement, which will mean we've disobeyed
2496 : * --rows-per-insert when it's set greater than 1. We do support
2497 : * a way to make this multi-row with: SELECT UNION ALL SELECT
2498 : * UNION ALL ... but that's non-standard so we should avoid it
2499 : * given that using INSERTs is mostly only ever needed for
2500 : * cross-database exports.
2501 : */
2502 6142 : if (nfields == 0)
2503 12 : continue;
2504 :
2505 : /* Emit a row heading */
2506 6130 : if (rows_per_statement == 1)
2507 6112 : archputs(" (", fout);
2508 18 : else if (rows_this_statement > 0)
2509 12 : archputs(",\n\t(", fout);
2510 : else
2511 6 : archputs("\n\t(", fout);
2512 :
2513 18498 : for (int field = 0; field < nfields; field++)
2514 : {
2515 12368 : if (field > 0)
2516 6238 : archputs(", ", fout);
2517 12368 : if (attgenerated[field])
2518 : {
2519 4 : archputs("DEFAULT", fout);
2520 4 : continue;
2521 : }
2522 12364 : if (PQgetisnull(res, tuple, field))
2523 : {
2524 166 : archputs("NULL", fout);
2525 166 : continue;
2526 : }
2527 :
2528 : /* XXX This code is partially duplicated in ruleutils.c */
2529 12198 : switch (PQftype(res, field))
2530 : {
2531 8138 : case INT2OID:
2532 : case INT4OID:
2533 : case INT8OID:
2534 : case OIDOID:
2535 : case FLOAT4OID:
2536 : case FLOAT8OID:
2537 : case NUMERICOID:
2538 : {
2539 : /*
2540 : * These types are printed without quotes unless
2541 : * they contain values that aren't accepted by the
2542 : * scanner unquoted (e.g., 'NaN'). Note that
2543 : * strtod() and friends might accept NaN, so we
2544 : * can't use that to test.
2545 : *
2546 : * In reality we only need to defend against
2547 : * infinity and NaN, so we need not get too crazy
2548 : * about pattern matching here.
2549 : */
2550 8138 : const char *s = PQgetvalue(res, tuple, field);
2551 :
2552 8138 : if (strspn(s, "0123456789 +-eE.") == strlen(s))
2553 8134 : archputs(s, fout);
2554 : else
2555 4 : archprintf(fout, "'%s'", s);
2556 : }
2557 8138 : break;
2558 :
2559 4 : case BITOID:
2560 : case VARBITOID:
2561 4 : archprintf(fout, "B'%s'",
2562 : PQgetvalue(res, tuple, field));
2563 4 : break;
2564 :
2565 8 : case BOOLOID:
2566 8 : if (strcmp(PQgetvalue(res, tuple, field), "t") == 0)
2567 4 : archputs("true", fout);
2568 : else
2569 4 : archputs("false", fout);
2570 8 : break;
2571 :
2572 4048 : default:
2573 : /* All other types are printed as string literals. */
2574 4048 : resetPQExpBuffer(q);
2575 4048 : appendStringLiteralAH(q,
2576 : PQgetvalue(res, tuple, field),
2577 : fout);
2578 4048 : archputs(q->data, fout);
2579 4048 : break;
2580 : }
2581 : }
2582 :
2583 : /* Terminate the row ... */
2584 6130 : archputs(")", fout);
2585 :
2586 : /* ... and the statement, if the target no. of rows is reached */
2587 6130 : if (++rows_this_statement >= rows_per_statement)
2588 : {
2589 6116 : if (dopt->do_nothing)
2590 0 : archputs(" ON CONFLICT DO NOTHING;\n", fout);
2591 : else
2592 6116 : archputs(";\n", fout);
2593 : /* Reset the row counter */
2594 6116 : rows_this_statement = 0;
2595 : }
2596 : }
2597 :
2598 238 : if (PQntuples(res) <= 0)
2599 : {
2600 138 : PQclear(res);
2601 138 : break;
2602 : }
2603 100 : PQclear(res);
2604 : }
2605 :
2606 : /* Terminate any statements that didn't make the row count. */
2607 138 : if (rows_this_statement > 0)
2608 : {
2609 2 : if (dopt->do_nothing)
2610 0 : archputs(" ON CONFLICT DO NOTHING;\n", fout);
2611 : else
2612 2 : archputs(";\n", fout);
2613 : }
2614 :
2615 138 : archputs("\n\n", fout);
2616 :
2617 138 : ExecuteSqlStatement(fout, "CLOSE _pg_dump_cursor");
2618 :
2619 138 : destroyPQExpBuffer(q);
2620 138 : if (insertStmt != NULL)
2621 138 : destroyPQExpBuffer(insertStmt);
2622 138 : free(attgenerated);
2623 :
2624 : /* Revert back the setting */
2625 138 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
2626 0 : set_restrict_relation_kind(fout, "view, foreign-table");
2627 :
2628 138 : return 1;
2629 : }
2630 :
2631 : /*
2632 : * getRootTableInfo:
2633 : * get the root TableInfo for the given partition table.
2634 : */
2635 : static TableInfo *
2636 18 : getRootTableInfo(const TableInfo *tbinfo)
2637 : {
2638 : TableInfo *parentTbinfo;
2639 :
2640 : Assert(tbinfo->ispartition);
2641 : Assert(tbinfo->numParents == 1);
2642 :
2643 18 : parentTbinfo = tbinfo->parents[0];
2644 18 : while (parentTbinfo->ispartition)
2645 : {
2646 : Assert(parentTbinfo->numParents == 1);
2647 0 : parentTbinfo = parentTbinfo->parents[0];
2648 : }
2649 :
2650 18 : return parentTbinfo;
2651 : }
2652 :
2653 : /*
2654 : * forcePartitionRootLoad
2655 : * Check if we must force load_via_partition_root for this partition.
2656 : *
2657 : * This is required if any level of ancestral partitioned table has an
2658 : * unsafe partitioning scheme.
2659 : */
2660 : static bool
2661 1884 : forcePartitionRootLoad(const TableInfo *tbinfo)
2662 : {
2663 : TableInfo *parentTbinfo;
2664 :
2665 : Assert(tbinfo->ispartition);
2666 : Assert(tbinfo->numParents == 1);
2667 :
2668 1884 : parentTbinfo = tbinfo->parents[0];
2669 1884 : if (parentTbinfo->unsafe_partitions)
2670 18 : return true;
2671 2298 : while (parentTbinfo->ispartition)
2672 : {
2673 : Assert(parentTbinfo->numParents == 1);
2674 432 : parentTbinfo = parentTbinfo->parents[0];
2675 432 : if (parentTbinfo->unsafe_partitions)
2676 0 : return true;
2677 : }
2678 :
2679 1866 : return false;
2680 : }
2681 :
2682 : /*
2683 : * dumpTableData -
2684 : * dump the contents of a single table
2685 : *
2686 : * Actually, this just makes an ArchiveEntry for the table contents.
2687 : */
2688 : static void
2689 7292 : dumpTableData(Archive *fout, const TableDataInfo *tdinfo)
2690 : {
2691 7292 : DumpOptions *dopt = fout->dopt;
2692 7292 : TableInfo *tbinfo = tdinfo->tdtable;
2693 7292 : PQExpBuffer copyBuf = createPQExpBuffer();
2694 7292 : PQExpBuffer clistBuf = createPQExpBuffer();
2695 : DataDumperPtr dumpFn;
2696 7292 : char *tdDefn = NULL;
2697 : char *copyStmt;
2698 : const char *copyFrom;
2699 :
2700 : /* We had better have loaded per-column details about this table */
2701 : Assert(tbinfo->interesting);
2702 :
2703 : /*
2704 : * When load-via-partition-root is set or forced, get the root table name
2705 : * for the partition table, so that we can reload data through the root
2706 : * table. Then construct a comment to be inserted into the TOC entry's
2707 : * defn field, so that such cases can be identified reliably.
2708 : */
2709 7292 : if (tbinfo->ispartition &&
2710 3688 : (dopt->load_via_partition_root ||
2711 1844 : forcePartitionRootLoad(tbinfo)))
2712 12 : {
2713 : TableInfo *parentTbinfo;
2714 :
2715 12 : parentTbinfo = getRootTableInfo(tbinfo);
2716 12 : copyFrom = fmtQualifiedDumpable(parentTbinfo);
2717 12 : printfPQExpBuffer(copyBuf, "-- load via partition root %s",
2718 : copyFrom);
2719 12 : tdDefn = pg_strdup(copyBuf->data);
2720 : }
2721 : else
2722 7280 : copyFrom = fmtQualifiedDumpable(tbinfo);
2723 :
2724 7292 : if (dopt->dump_inserts == 0)
2725 : {
2726 : /* Dump/restore using COPY */
2727 7154 : dumpFn = dumpTableData_copy;
2728 : /* must use 2 steps here 'cause fmtId is nonreentrant */
2729 7154 : printfPQExpBuffer(copyBuf, "COPY %s ",
2730 : copyFrom);
2731 7154 : appendPQExpBuffer(copyBuf, "%s FROM stdin;\n",
2732 : fmtCopyColumnList(tbinfo, clistBuf));
2733 7154 : copyStmt = copyBuf->data;
2734 : }
2735 : else
2736 : {
2737 : /* Restore using INSERT */
2738 138 : dumpFn = dumpTableData_insert;
2739 138 : copyStmt = NULL;
2740 : }
2741 :
2742 : /*
2743 : * Note: although the TableDataInfo is a full DumpableObject, we treat its
2744 : * dependency on its table as "special" and pass it to ArchiveEntry now.
2745 : * See comments for BuildArchiveDependencies.
2746 : */
2747 7292 : if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2748 : {
2749 : TocEntry *te;
2750 :
2751 7292 : te = ArchiveEntry(fout, tdinfo->dobj.catId, tdinfo->dobj.dumpId,
2752 7292 : ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2753 : .namespace = tbinfo->dobj.namespace->dobj.name,
2754 : .owner = tbinfo->rolname,
2755 : .description = "TABLE DATA",
2756 : .section = SECTION_DATA,
2757 : .createStmt = tdDefn,
2758 : .copyStmt = copyStmt,
2759 : .deps = &(tbinfo->dobj.dumpId),
2760 : .nDeps = 1,
2761 : .dumpFn = dumpFn,
2762 : .dumpArg = tdinfo));
2763 :
2764 : /*
2765 : * Set the TocEntry's dataLength in case we are doing a parallel dump
2766 : * and want to order dump jobs by table size. We choose to measure
2767 : * dataLength in table pages (including TOAST pages) during dump, so
2768 : * no scaling is needed.
2769 : *
2770 : * However, relpages is declared as "integer" in pg_class, and hence
2771 : * also in TableInfo, but it's really BlockNumber a/k/a unsigned int.
2772 : * Cast so that we get the right interpretation of table sizes
2773 : * exceeding INT_MAX pages.
2774 : */
2775 7292 : te->dataLength = (BlockNumber) tbinfo->relpages;
2776 7292 : te->dataLength += (BlockNumber) tbinfo->toastpages;
2777 :
2778 : /*
2779 : * If pgoff_t is only 32 bits wide, the above refinement is useless,
2780 : * and instead we'd better worry about integer overflow. Clamp to
2781 : * INT_MAX if the correct result exceeds that.
2782 : */
2783 : if (sizeof(te->dataLength) == 4 &&
2784 : (tbinfo->relpages < 0 || tbinfo->toastpages < 0 ||
2785 : te->dataLength < 0))
2786 : te->dataLength = INT_MAX;
2787 : }
2788 :
2789 7292 : destroyPQExpBuffer(copyBuf);
2790 7292 : destroyPQExpBuffer(clistBuf);
2791 7292 : }
2792 :
2793 : /*
2794 : * refreshMatViewData -
2795 : * load or refresh the contents of a single materialized view
2796 : *
2797 : * Actually, this just makes an ArchiveEntry for the REFRESH MATERIALIZED VIEW
2798 : * statement.
2799 : */
2800 : static void
2801 676 : refreshMatViewData(Archive *fout, const TableDataInfo *tdinfo)
2802 : {
2803 676 : TableInfo *tbinfo = tdinfo->tdtable;
2804 : PQExpBuffer q;
2805 :
2806 : /* If the materialized view is not flagged as populated, skip this. */
2807 676 : if (!tbinfo->relispopulated)
2808 136 : return;
2809 :
2810 540 : q = createPQExpBuffer();
2811 :
2812 540 : appendPQExpBuffer(q, "REFRESH MATERIALIZED VIEW %s;\n",
2813 540 : fmtQualifiedDumpable(tbinfo));
2814 :
2815 540 : if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
2816 540 : ArchiveEntry(fout,
2817 : tdinfo->dobj.catId, /* catalog ID */
2818 : tdinfo->dobj.dumpId, /* dump ID */
2819 540 : ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
2820 : .namespace = tbinfo->dobj.namespace->dobj.name,
2821 : .owner = tbinfo->rolname,
2822 : .description = "MATERIALIZED VIEW DATA",
2823 : .section = SECTION_POST_DATA,
2824 : .createStmt = q->data,
2825 : .deps = tdinfo->dobj.dependencies,
2826 : .nDeps = tdinfo->dobj.nDeps));
2827 :
2828 540 : destroyPQExpBuffer(q);
2829 : }
2830 :
2831 : /*
2832 : * getTableData -
2833 : * set up dumpable objects representing the contents of tables
2834 : */
2835 : static void
2836 304 : getTableData(DumpOptions *dopt, TableInfo *tblinfo, int numTables, char relkind)
2837 : {
2838 : int i;
2839 :
2840 80248 : for (i = 0; i < numTables; i++)
2841 : {
2842 79944 : if (tblinfo[i].dobj.dump & DUMP_COMPONENT_DATA &&
2843 1634 : (!relkind || tblinfo[i].relkind == relkind))
2844 10542 : makeTableDataInfo(dopt, &(tblinfo[i]));
2845 : }
2846 304 : }
2847 :
2848 : /*
2849 : * Make a dumpable object for the data of this specific table
2850 : *
2851 : * Note: we make a TableDataInfo if and only if we are going to dump the
2852 : * table data; the "dump" field in such objects isn't very interesting.
2853 : */
2854 : static void
2855 10620 : makeTableDataInfo(DumpOptions *dopt, TableInfo *tbinfo)
2856 : {
2857 : TableDataInfo *tdinfo;
2858 :
2859 : /*
2860 : * Nothing to do if we already decided to dump the table. This will
2861 : * happen for "config" tables.
2862 : */
2863 10620 : if (tbinfo->dataObj != NULL)
2864 2 : return;
2865 :
2866 : /* Skip VIEWs (no data to dump) */
2867 10618 : if (tbinfo->relkind == RELKIND_VIEW)
2868 920 : return;
2869 : /* Skip FOREIGN TABLEs (no data to dump) unless requested explicitly */
2870 9698 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
2871 76 : (foreign_servers_include_oids.head == NULL ||
2872 8 : !simple_oid_list_member(&foreign_servers_include_oids,
2873 : tbinfo->foreign_server)))
2874 74 : return;
2875 : /* Skip partitioned tables (data in partitions) */
2876 9624 : if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
2877 876 : return;
2878 :
2879 : /* Don't dump data in unlogged tables, if so requested */
2880 8748 : if (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
2881 82 : dopt->no_unlogged_table_data)
2882 36 : return;
2883 :
2884 : /* Check that the data is not explicitly excluded */
2885 8712 : if (simple_oid_list_member(&tabledata_exclude_oids,
2886 : tbinfo->dobj.catId.oid))
2887 16 : return;
2888 :
2889 : /* OK, let's dump it */
2890 8696 : tdinfo = (TableDataInfo *) pg_malloc(sizeof(TableDataInfo));
2891 :
2892 8696 : if (tbinfo->relkind == RELKIND_MATVIEW)
2893 676 : tdinfo->dobj.objType = DO_REFRESH_MATVIEW;
2894 8020 : else if (tbinfo->relkind == RELKIND_SEQUENCE)
2895 728 : tdinfo->dobj.objType = DO_SEQUENCE_SET;
2896 : else
2897 7292 : tdinfo->dobj.objType = DO_TABLE_DATA;
2898 :
2899 : /*
2900 : * Note: use tableoid 0 so that this object won't be mistaken for
2901 : * something that pg_depend entries apply to.
2902 : */
2903 8696 : tdinfo->dobj.catId.tableoid = 0;
2904 8696 : tdinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
2905 8696 : AssignDumpId(&tdinfo->dobj);
2906 8696 : tdinfo->dobj.name = tbinfo->dobj.name;
2907 8696 : tdinfo->dobj.namespace = tbinfo->dobj.namespace;
2908 8696 : tdinfo->tdtable = tbinfo;
2909 8696 : tdinfo->filtercond = NULL; /* might get set later */
2910 8696 : addObjectDependency(&tdinfo->dobj, tbinfo->dobj.dumpId);
2911 :
2912 : /* A TableDataInfo contains data, of course */
2913 8696 : tdinfo->dobj.components |= DUMP_COMPONENT_DATA;
2914 :
2915 8696 : tbinfo->dataObj = tdinfo;
2916 :
2917 : /* Make sure that we'll collect per-column info for this table. */
2918 8696 : tbinfo->interesting = true;
2919 : }
2920 :
2921 : /*
2922 : * The refresh for a materialized view must be dependent on the refresh for
2923 : * any materialized view that this one is dependent on.
2924 : *
2925 : * This must be called after all the objects are created, but before they are
2926 : * sorted.
2927 : */
2928 : static void
2929 276 : buildMatViewRefreshDependencies(Archive *fout)
2930 : {
2931 : PQExpBuffer query;
2932 : PGresult *res;
2933 : int ntups,
2934 : i;
2935 : int i_classid,
2936 : i_objid,
2937 : i_refobjid;
2938 :
2939 : /* No Mat Views before 9.3. */
2940 276 : if (fout->remoteVersion < 90300)
2941 0 : return;
2942 :
2943 276 : query = createPQExpBuffer();
2944 :
2945 276 : appendPQExpBufferStr(query, "WITH RECURSIVE w AS "
2946 : "( "
2947 : "SELECT d1.objid, d2.refobjid, c2.relkind AS refrelkind "
2948 : "FROM pg_depend d1 "
2949 : "JOIN pg_class c1 ON c1.oid = d1.objid "
2950 : "AND c1.relkind = " CppAsString2(RELKIND_MATVIEW)
2951 : " JOIN pg_rewrite r1 ON r1.ev_class = d1.objid "
2952 : "JOIN pg_depend d2 ON d2.classid = 'pg_rewrite'::regclass "
2953 : "AND d2.objid = r1.oid "
2954 : "AND d2.refobjid <> d1.objid "
2955 : "JOIN pg_class c2 ON c2.oid = d2.refobjid "
2956 : "AND c2.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2957 : CppAsString2(RELKIND_VIEW) ") "
2958 : "WHERE d1.classid = 'pg_class'::regclass "
2959 : "UNION "
2960 : "SELECT w.objid, d3.refobjid, c3.relkind "
2961 : "FROM w "
2962 : "JOIN pg_rewrite r3 ON r3.ev_class = w.refobjid "
2963 : "JOIN pg_depend d3 ON d3.classid = 'pg_rewrite'::regclass "
2964 : "AND d3.objid = r3.oid "
2965 : "AND d3.refobjid <> w.refobjid "
2966 : "JOIN pg_class c3 ON c3.oid = d3.refobjid "
2967 : "AND c3.relkind IN (" CppAsString2(RELKIND_MATVIEW) ","
2968 : CppAsString2(RELKIND_VIEW) ") "
2969 : ") "
2970 : "SELECT 'pg_class'::regclass::oid AS classid, objid, refobjid "
2971 : "FROM w "
2972 : "WHERE refrelkind = " CppAsString2(RELKIND_MATVIEW));
2973 :
2974 276 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
2975 :
2976 276 : ntups = PQntuples(res);
2977 :
2978 276 : i_classid = PQfnumber(res, "classid");
2979 276 : i_objid = PQfnumber(res, "objid");
2980 276 : i_refobjid = PQfnumber(res, "refobjid");
2981 :
2982 804 : for (i = 0; i < ntups; i++)
2983 : {
2984 : CatalogId objId;
2985 : CatalogId refobjId;
2986 : DumpableObject *dobj;
2987 : DumpableObject *refdobj;
2988 : TableInfo *tbinfo;
2989 : TableInfo *reftbinfo;
2990 :
2991 528 : objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
2992 528 : objId.oid = atooid(PQgetvalue(res, i, i_objid));
2993 528 : refobjId.tableoid = objId.tableoid;
2994 528 : refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
2995 :
2996 528 : dobj = findObjectByCatalogId(objId);
2997 528 : if (dobj == NULL)
2998 96 : continue;
2999 :
3000 : Assert(dobj->objType == DO_TABLE);
3001 528 : tbinfo = (TableInfo *) dobj;
3002 : Assert(tbinfo->relkind == RELKIND_MATVIEW);
3003 528 : dobj = (DumpableObject *) tbinfo->dataObj;
3004 528 : if (dobj == NULL)
3005 96 : continue;
3006 : Assert(dobj->objType == DO_REFRESH_MATVIEW);
3007 :
3008 432 : refdobj = findObjectByCatalogId(refobjId);
3009 432 : if (refdobj == NULL)
3010 0 : continue;
3011 :
3012 : Assert(refdobj->objType == DO_TABLE);
3013 432 : reftbinfo = (TableInfo *) refdobj;
3014 : Assert(reftbinfo->relkind == RELKIND_MATVIEW);
3015 432 : refdobj = (DumpableObject *) reftbinfo->dataObj;
3016 432 : if (refdobj == NULL)
3017 0 : continue;
3018 : Assert(refdobj->objType == DO_REFRESH_MATVIEW);
3019 :
3020 432 : addObjectDependency(dobj, refdobj->dumpId);
3021 :
3022 432 : if (!reftbinfo->relispopulated)
3023 68 : tbinfo->relispopulated = false;
3024 : }
3025 :
3026 276 : PQclear(res);
3027 :
3028 276 : destroyPQExpBuffer(query);
3029 : }
3030 :
3031 : /*
3032 : * getTableDataFKConstraints -
3033 : * add dump-order dependencies reflecting foreign key constraints
3034 : *
3035 : * This code is executed only in a data-only dump --- in schema+data dumps
3036 : * we handle foreign key issues by not creating the FK constraints until
3037 : * after the data is loaded. In a data-only dump, however, we want to
3038 : * order the table data objects in such a way that a table's referenced
3039 : * tables are restored first. (In the presence of circular references or
3040 : * self-references this may be impossible; we'll detect and complain about
3041 : * that during the dependency sorting step.)
3042 : */
3043 : static void
3044 12 : getTableDataFKConstraints(void)
3045 : {
3046 : DumpableObject **dobjs;
3047 : int numObjs;
3048 : int i;
3049 :
3050 : /* Search through all the dumpable objects for FK constraints */
3051 12 : getDumpableObjects(&dobjs, &numObjs);
3052 42778 : for (i = 0; i < numObjs; i++)
3053 : {
3054 42766 : if (dobjs[i]->objType == DO_FK_CONSTRAINT)
3055 : {
3056 12 : ConstraintInfo *cinfo = (ConstraintInfo *) dobjs[i];
3057 : TableInfo *ftable;
3058 :
3059 : /* Not interesting unless both tables are to be dumped */
3060 12 : if (cinfo->contable == NULL ||
3061 12 : cinfo->contable->dataObj == NULL)
3062 6 : continue;
3063 6 : ftable = findTableByOid(cinfo->confrelid);
3064 6 : if (ftable == NULL ||
3065 6 : ftable->dataObj == NULL)
3066 0 : continue;
3067 :
3068 : /*
3069 : * Okay, make referencing table's TABLE_DATA object depend on the
3070 : * referenced table's TABLE_DATA object.
3071 : */
3072 6 : addObjectDependency(&cinfo->contable->dataObj->dobj,
3073 6 : ftable->dataObj->dobj.dumpId);
3074 : }
3075 : }
3076 12 : free(dobjs);
3077 12 : }
3078 :
3079 :
3080 : /*
3081 : * dumpDatabase:
3082 : * dump the database definition
3083 : */
3084 : static void
3085 120 : dumpDatabase(Archive *fout)
3086 : {
3087 120 : DumpOptions *dopt = fout->dopt;
3088 120 : PQExpBuffer dbQry = createPQExpBuffer();
3089 120 : PQExpBuffer delQry = createPQExpBuffer();
3090 120 : PQExpBuffer creaQry = createPQExpBuffer();
3091 120 : PQExpBuffer labelq = createPQExpBuffer();
3092 120 : PGconn *conn = GetConnection(fout);
3093 : PGresult *res;
3094 : int i_tableoid,
3095 : i_oid,
3096 : i_datname,
3097 : i_datdba,
3098 : i_encoding,
3099 : i_datlocprovider,
3100 : i_collate,
3101 : i_ctype,
3102 : i_datlocale,
3103 : i_daticurules,
3104 : i_frozenxid,
3105 : i_minmxid,
3106 : i_datacl,
3107 : i_acldefault,
3108 : i_datistemplate,
3109 : i_datconnlimit,
3110 : i_datcollversion,
3111 : i_tablespace;
3112 : CatalogId dbCatId;
3113 : DumpId dbDumpId;
3114 : DumpableAcl dbdacl;
3115 : const char *datname,
3116 : *dba,
3117 : *encoding,
3118 : *datlocprovider,
3119 : *collate,
3120 : *ctype,
3121 : *locale,
3122 : *icurules,
3123 : *datistemplate,
3124 : *datconnlimit,
3125 : *tablespace;
3126 : uint32 frozenxid,
3127 : minmxid;
3128 : char *qdatname;
3129 :
3130 120 : pg_log_info("saving database definition");
3131 :
3132 : /*
3133 : * Fetch the database-level properties for this database.
3134 : */
3135 120 : appendPQExpBufferStr(dbQry, "SELECT tableoid, oid, datname, "
3136 : "datdba, "
3137 : "pg_encoding_to_char(encoding) AS encoding, "
3138 : "datcollate, datctype, datfrozenxid, "
3139 : "datacl, acldefault('d', datdba) AS acldefault, "
3140 : "datistemplate, datconnlimit, ");
3141 120 : if (fout->remoteVersion >= 90300)
3142 120 : appendPQExpBufferStr(dbQry, "datminmxid, ");
3143 : else
3144 0 : appendPQExpBufferStr(dbQry, "0 AS datminmxid, ");
3145 120 : if (fout->remoteVersion >= 170000)
3146 120 : appendPQExpBufferStr(dbQry, "datlocprovider, datlocale, datcollversion, ");
3147 0 : else if (fout->remoteVersion >= 150000)
3148 0 : appendPQExpBufferStr(dbQry, "datlocprovider, daticulocale AS datlocale, datcollversion, ");
3149 : else
3150 0 : appendPQExpBufferStr(dbQry, "'c' AS datlocprovider, NULL AS datlocale, NULL AS datcollversion, ");
3151 120 : if (fout->remoteVersion >= 160000)
3152 120 : appendPQExpBufferStr(dbQry, "daticurules, ");
3153 : else
3154 0 : appendPQExpBufferStr(dbQry, "NULL AS daticurules, ");
3155 120 : appendPQExpBufferStr(dbQry,
3156 : "(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, "
3157 : "shobj_description(oid, 'pg_database') AS description "
3158 : "FROM pg_database "
3159 : "WHERE datname = current_database()");
3160 :
3161 120 : res = ExecuteSqlQueryForSingleRow(fout, dbQry->data);
3162 :
3163 120 : i_tableoid = PQfnumber(res, "tableoid");
3164 120 : i_oid = PQfnumber(res, "oid");
3165 120 : i_datname = PQfnumber(res, "datname");
3166 120 : i_datdba = PQfnumber(res, "datdba");
3167 120 : i_encoding = PQfnumber(res, "encoding");
3168 120 : i_datlocprovider = PQfnumber(res, "datlocprovider");
3169 120 : i_collate = PQfnumber(res, "datcollate");
3170 120 : i_ctype = PQfnumber(res, "datctype");
3171 120 : i_datlocale = PQfnumber(res, "datlocale");
3172 120 : i_daticurules = PQfnumber(res, "daticurules");
3173 120 : i_frozenxid = PQfnumber(res, "datfrozenxid");
3174 120 : i_minmxid = PQfnumber(res, "datminmxid");
3175 120 : i_datacl = PQfnumber(res, "datacl");
3176 120 : i_acldefault = PQfnumber(res, "acldefault");
3177 120 : i_datistemplate = PQfnumber(res, "datistemplate");
3178 120 : i_datconnlimit = PQfnumber(res, "datconnlimit");
3179 120 : i_datcollversion = PQfnumber(res, "datcollversion");
3180 120 : i_tablespace = PQfnumber(res, "tablespace");
3181 :
3182 120 : dbCatId.tableoid = atooid(PQgetvalue(res, 0, i_tableoid));
3183 120 : dbCatId.oid = atooid(PQgetvalue(res, 0, i_oid));
3184 120 : datname = PQgetvalue(res, 0, i_datname);
3185 120 : dba = getRoleName(PQgetvalue(res, 0, i_datdba));
3186 120 : encoding = PQgetvalue(res, 0, i_encoding);
3187 120 : datlocprovider = PQgetvalue(res, 0, i_datlocprovider);
3188 120 : collate = PQgetvalue(res, 0, i_collate);
3189 120 : ctype = PQgetvalue(res, 0, i_ctype);
3190 120 : if (!PQgetisnull(res, 0, i_datlocale))
3191 28 : locale = PQgetvalue(res, 0, i_datlocale);
3192 : else
3193 92 : locale = NULL;
3194 120 : if (!PQgetisnull(res, 0, i_daticurules))
3195 0 : icurules = PQgetvalue(res, 0, i_daticurules);
3196 : else
3197 120 : icurules = NULL;
3198 120 : frozenxid = atooid(PQgetvalue(res, 0, i_frozenxid));
3199 120 : minmxid = atooid(PQgetvalue(res, 0, i_minmxid));
3200 120 : dbdacl.acl = PQgetvalue(res, 0, i_datacl);
3201 120 : dbdacl.acldefault = PQgetvalue(res, 0, i_acldefault);
3202 120 : datistemplate = PQgetvalue(res, 0, i_datistemplate);
3203 120 : datconnlimit = PQgetvalue(res, 0, i_datconnlimit);
3204 120 : tablespace = PQgetvalue(res, 0, i_tablespace);
3205 :
3206 120 : qdatname = pg_strdup(fmtId(datname));
3207 :
3208 : /*
3209 : * Prepare the CREATE DATABASE command. We must specify OID (if we want
3210 : * to preserve that), as well as the encoding, locale, and tablespace
3211 : * since those can't be altered later. Other DB properties are left to
3212 : * the DATABASE PROPERTIES entry, so that they can be applied after
3213 : * reconnecting to the target DB.
3214 : *
3215 : * For binary upgrade, we use the FILE_COPY strategy because testing has
3216 : * shown it to be faster. When the server is in binary upgrade mode, it
3217 : * will also skip the checkpoints this strategy ordinarily performs.
3218 : */
3219 120 : if (dopt->binary_upgrade)
3220 : {
3221 26 : appendPQExpBuffer(creaQry,
3222 : "CREATE DATABASE %s WITH TEMPLATE = template0 "
3223 : "OID = %u STRATEGY = FILE_COPY",
3224 : qdatname, dbCatId.oid);
3225 : }
3226 : else
3227 : {
3228 94 : appendPQExpBuffer(creaQry, "CREATE DATABASE %s WITH TEMPLATE = template0",
3229 : qdatname);
3230 : }
3231 120 : if (strlen(encoding) > 0)
3232 : {
3233 120 : appendPQExpBufferStr(creaQry, " ENCODING = ");
3234 120 : appendStringLiteralAH(creaQry, encoding, fout);
3235 : }
3236 :
3237 120 : appendPQExpBufferStr(creaQry, " LOCALE_PROVIDER = ");
3238 120 : if (datlocprovider[0] == 'b')
3239 28 : appendPQExpBufferStr(creaQry, "builtin");
3240 92 : else if (datlocprovider[0] == 'c')
3241 92 : appendPQExpBufferStr(creaQry, "libc");
3242 0 : else if (datlocprovider[0] == 'i')
3243 0 : appendPQExpBufferStr(creaQry, "icu");
3244 : else
3245 0 : pg_fatal("unrecognized locale provider: %s",
3246 : datlocprovider);
3247 :
3248 120 : if (strlen(collate) > 0 && strcmp(collate, ctype) == 0)
3249 : {
3250 120 : appendPQExpBufferStr(creaQry, " LOCALE = ");
3251 120 : appendStringLiteralAH(creaQry, collate, fout);
3252 : }
3253 : else
3254 : {
3255 0 : if (strlen(collate) > 0)
3256 : {
3257 0 : appendPQExpBufferStr(creaQry, " LC_COLLATE = ");
3258 0 : appendStringLiteralAH(creaQry, collate, fout);
3259 : }
3260 0 : if (strlen(ctype) > 0)
3261 : {
3262 0 : appendPQExpBufferStr(creaQry, " LC_CTYPE = ");
3263 0 : appendStringLiteralAH(creaQry, ctype, fout);
3264 : }
3265 : }
3266 120 : if (locale)
3267 : {
3268 28 : if (datlocprovider[0] == 'b')
3269 28 : appendPQExpBufferStr(creaQry, " BUILTIN_LOCALE = ");
3270 : else
3271 0 : appendPQExpBufferStr(creaQry, " ICU_LOCALE = ");
3272 :
3273 28 : appendStringLiteralAH(creaQry, locale, fout);
3274 : }
3275 :
3276 120 : if (icurules)
3277 : {
3278 0 : appendPQExpBufferStr(creaQry, " ICU_RULES = ");
3279 0 : appendStringLiteralAH(creaQry, icurules, fout);
3280 : }
3281 :
3282 : /*
3283 : * For binary upgrade, carry over the collation version. For normal
3284 : * dump/restore, omit the version, so that it is computed upon restore.
3285 : */
3286 120 : if (dopt->binary_upgrade)
3287 : {
3288 26 : if (!PQgetisnull(res, 0, i_datcollversion))
3289 : {
3290 26 : appendPQExpBufferStr(creaQry, " COLLATION_VERSION = ");
3291 26 : appendStringLiteralAH(creaQry,
3292 : PQgetvalue(res, 0, i_datcollversion),
3293 : fout);
3294 : }
3295 : }
3296 :
3297 : /*
3298 : * Note: looking at dopt->outputNoTablespaces here is completely the wrong
3299 : * thing; the decision whether to specify a tablespace should be left till
3300 : * pg_restore, so that pg_restore --no-tablespaces applies. Ideally we'd
3301 : * label the DATABASE entry with the tablespace and let the normal
3302 : * tablespace selection logic work ... but CREATE DATABASE doesn't pay
3303 : * attention to default_tablespace, so that won't work.
3304 : */
3305 120 : if (strlen(tablespace) > 0 && strcmp(tablespace, "pg_default") != 0 &&
3306 0 : !dopt->outputNoTablespaces)
3307 0 : appendPQExpBuffer(creaQry, " TABLESPACE = %s",
3308 : fmtId(tablespace));
3309 120 : appendPQExpBufferStr(creaQry, ";\n");
3310 :
3311 120 : appendPQExpBuffer(delQry, "DROP DATABASE %s;\n",
3312 : qdatname);
3313 :
3314 120 : dbDumpId = createDumpId();
3315 :
3316 120 : ArchiveEntry(fout,
3317 : dbCatId, /* catalog ID */
3318 : dbDumpId, /* dump ID */
3319 120 : ARCHIVE_OPTS(.tag = datname,
3320 : .owner = dba,
3321 : .description = "DATABASE",
3322 : .section = SECTION_PRE_DATA,
3323 : .createStmt = creaQry->data,
3324 : .dropStmt = delQry->data));
3325 :
3326 : /* Compute correct tag for archive entry */
3327 120 : appendPQExpBuffer(labelq, "DATABASE %s", qdatname);
3328 :
3329 : /* Dump DB comment if any */
3330 : {
3331 : /*
3332 : * 8.2 and up keep comments on shared objects in a shared table, so we
3333 : * cannot use the dumpComment() code used for other database objects.
3334 : * Be careful that the ArchiveEntry parameters match that function.
3335 : */
3336 120 : char *comment = PQgetvalue(res, 0, PQfnumber(res, "description"));
3337 :
3338 120 : if (comment && *comment && !dopt->no_comments)
3339 : {
3340 50 : resetPQExpBuffer(dbQry);
3341 :
3342 : /*
3343 : * Generates warning when loaded into a differently-named
3344 : * database.
3345 : */
3346 50 : appendPQExpBuffer(dbQry, "COMMENT ON DATABASE %s IS ", qdatname);
3347 50 : appendStringLiteralAH(dbQry, comment, fout);
3348 50 : appendPQExpBufferStr(dbQry, ";\n");
3349 :
3350 50 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
3351 50 : ARCHIVE_OPTS(.tag = labelq->data,
3352 : .owner = dba,
3353 : .description = "COMMENT",
3354 : .section = SECTION_NONE,
3355 : .createStmt = dbQry->data,
3356 : .deps = &dbDumpId,
3357 : .nDeps = 1));
3358 : }
3359 : }
3360 :
3361 : /* Dump DB security label, if enabled */
3362 120 : if (!dopt->no_security_labels)
3363 : {
3364 : PGresult *shres;
3365 : PQExpBuffer seclabelQry;
3366 :
3367 120 : seclabelQry = createPQExpBuffer();
3368 :
3369 120 : buildShSecLabelQuery("pg_database", dbCatId.oid, seclabelQry);
3370 120 : shres = ExecuteSqlQuery(fout, seclabelQry->data, PGRES_TUPLES_OK);
3371 120 : resetPQExpBuffer(seclabelQry);
3372 120 : emitShSecLabels(conn, shres, seclabelQry, "DATABASE", datname);
3373 120 : if (seclabelQry->len > 0)
3374 0 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
3375 0 : ARCHIVE_OPTS(.tag = labelq->data,
3376 : .owner = dba,
3377 : .description = "SECURITY LABEL",
3378 : .section = SECTION_NONE,
3379 : .createStmt = seclabelQry->data,
3380 : .deps = &dbDumpId,
3381 : .nDeps = 1));
3382 120 : destroyPQExpBuffer(seclabelQry);
3383 120 : PQclear(shres);
3384 : }
3385 :
3386 : /*
3387 : * Dump ACL if any. Note that we do not support initial privileges
3388 : * (pg_init_privs) on databases.
3389 : */
3390 120 : dbdacl.privtype = 0;
3391 120 : dbdacl.initprivs = NULL;
3392 :
3393 120 : dumpACL(fout, dbDumpId, InvalidDumpId, "DATABASE",
3394 : qdatname, NULL, NULL,
3395 : NULL, dba, &dbdacl);
3396 :
3397 : /*
3398 : * Now construct a DATABASE PROPERTIES archive entry to restore any
3399 : * non-default database-level properties. (The reason this must be
3400 : * separate is that we cannot put any additional commands into the TOC
3401 : * entry that has CREATE DATABASE. pg_restore would execute such a group
3402 : * in an implicit transaction block, and the backend won't allow CREATE
3403 : * DATABASE in that context.)
3404 : */
3405 120 : resetPQExpBuffer(creaQry);
3406 120 : resetPQExpBuffer(delQry);
3407 :
3408 120 : if (strlen(datconnlimit) > 0 && strcmp(datconnlimit, "-1") != 0)
3409 0 : appendPQExpBuffer(creaQry, "ALTER DATABASE %s CONNECTION LIMIT = %s;\n",
3410 : qdatname, datconnlimit);
3411 :
3412 120 : if (strcmp(datistemplate, "t") == 0)
3413 : {
3414 8 : appendPQExpBuffer(creaQry, "ALTER DATABASE %s IS_TEMPLATE = true;\n",
3415 : qdatname);
3416 :
3417 : /*
3418 : * The backend won't accept DROP DATABASE on a template database. We
3419 : * can deal with that by removing the template marking before the DROP
3420 : * gets issued. We'd prefer to use ALTER DATABASE IF EXISTS here, but
3421 : * since no such command is currently supported, fake it with a direct
3422 : * UPDATE on pg_database.
3423 : */
3424 8 : appendPQExpBufferStr(delQry, "UPDATE pg_catalog.pg_database "
3425 : "SET datistemplate = false WHERE datname = ");
3426 8 : appendStringLiteralAH(delQry, datname, fout);
3427 8 : appendPQExpBufferStr(delQry, ";\n");
3428 : }
3429 :
3430 : /*
3431 : * We do not restore pg_database.dathasloginevt because it is set
3432 : * automatically on login event trigger creation.
3433 : */
3434 :
3435 : /* Add database-specific SET options */
3436 120 : dumpDatabaseConfig(fout, creaQry, datname, dbCatId.oid);
3437 :
3438 : /*
3439 : * We stick this binary-upgrade query into the DATABASE PROPERTIES archive
3440 : * entry, too, for lack of a better place.
3441 : */
3442 120 : if (dopt->binary_upgrade)
3443 : {
3444 26 : appendPQExpBufferStr(creaQry, "\n-- For binary upgrade, set datfrozenxid and datminmxid.\n");
3445 26 : appendPQExpBuffer(creaQry, "UPDATE pg_catalog.pg_database\n"
3446 : "SET datfrozenxid = '%u', datminmxid = '%u'\n"
3447 : "WHERE datname = ",
3448 : frozenxid, minmxid);
3449 26 : appendStringLiteralAH(creaQry, datname, fout);
3450 26 : appendPQExpBufferStr(creaQry, ";\n");
3451 : }
3452 :
3453 120 : if (creaQry->len > 0)
3454 34 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
3455 34 : ARCHIVE_OPTS(.tag = datname,
3456 : .owner = dba,
3457 : .description = "DATABASE PROPERTIES",
3458 : .section = SECTION_PRE_DATA,
3459 : .createStmt = creaQry->data,
3460 : .dropStmt = delQry->data,
3461 : .deps = &dbDumpId));
3462 :
3463 : /*
3464 : * pg_largeobject comes from the old system intact, so set its
3465 : * relfrozenxids, relminmxids and relfilenode.
3466 : */
3467 120 : if (dopt->binary_upgrade)
3468 : {
3469 : PGresult *lo_res;
3470 26 : PQExpBuffer loFrozenQry = createPQExpBuffer();
3471 26 : PQExpBuffer loOutQry = createPQExpBuffer();
3472 26 : PQExpBuffer loHorizonQry = createPQExpBuffer();
3473 : int ii_relfrozenxid,
3474 : ii_relfilenode,
3475 : ii_oid,
3476 : ii_relminmxid;
3477 :
3478 : /*
3479 : * pg_largeobject
3480 : */
3481 26 : if (fout->remoteVersion >= 90300)
3482 26 : appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, relminmxid, relfilenode, oid\n"
3483 : "FROM pg_catalog.pg_class\n"
3484 : "WHERE oid IN (%u, %u);\n",
3485 : LargeObjectRelationId, LargeObjectLOidPNIndexId);
3486 : else
3487 0 : appendPQExpBuffer(loFrozenQry, "SELECT relfrozenxid, 0 AS relminmxid, relfilenode, oid\n"
3488 : "FROM pg_catalog.pg_class\n"
3489 : "WHERE oid IN (%u, %u);\n",
3490 : LargeObjectRelationId, LargeObjectLOidPNIndexId);
3491 :
3492 26 : lo_res = ExecuteSqlQuery(fout, loFrozenQry->data, PGRES_TUPLES_OK);
3493 :
3494 26 : ii_relfrozenxid = PQfnumber(lo_res, "relfrozenxid");
3495 26 : ii_relminmxid = PQfnumber(lo_res, "relminmxid");
3496 26 : ii_relfilenode = PQfnumber(lo_res, "relfilenode");
3497 26 : ii_oid = PQfnumber(lo_res, "oid");
3498 :
3499 26 : appendPQExpBufferStr(loHorizonQry, "\n-- For binary upgrade, set pg_largeobject relfrozenxid and relminmxid\n");
3500 26 : appendPQExpBufferStr(loOutQry, "\n-- For binary upgrade, preserve pg_largeobject and index relfilenodes\n");
3501 78 : for (int i = 0; i < PQntuples(lo_res); ++i)
3502 : {
3503 : Oid oid;
3504 : RelFileNumber relfilenumber;
3505 :
3506 52 : appendPQExpBuffer(loHorizonQry, "UPDATE pg_catalog.pg_class\n"
3507 : "SET relfrozenxid = '%u', relminmxid = '%u'\n"
3508 : "WHERE oid = %u;\n",
3509 52 : atooid(PQgetvalue(lo_res, i, ii_relfrozenxid)),
3510 52 : atooid(PQgetvalue(lo_res, i, ii_relminmxid)),
3511 52 : atooid(PQgetvalue(lo_res, i, ii_oid)));
3512 :
3513 52 : oid = atooid(PQgetvalue(lo_res, i, ii_oid));
3514 52 : relfilenumber = atooid(PQgetvalue(lo_res, i, ii_relfilenode));
3515 :
3516 52 : if (oid == LargeObjectRelationId)
3517 26 : appendPQExpBuffer(loOutQry,
3518 : "SELECT pg_catalog.binary_upgrade_set_next_heap_relfilenode('%u'::pg_catalog.oid);\n",
3519 : relfilenumber);
3520 26 : else if (oid == LargeObjectLOidPNIndexId)
3521 26 : appendPQExpBuffer(loOutQry,
3522 : "SELECT pg_catalog.binary_upgrade_set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
3523 : relfilenumber);
3524 : }
3525 :
3526 26 : appendPQExpBufferStr(loOutQry,
3527 : "TRUNCATE pg_catalog.pg_largeobject;\n");
3528 26 : appendPQExpBufferStr(loOutQry, loHorizonQry->data);
3529 :
3530 26 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
3531 26 : ARCHIVE_OPTS(.tag = "pg_largeobject",
3532 : .description = "pg_largeobject",
3533 : .section = SECTION_PRE_DATA,
3534 : .createStmt = loOutQry->data));
3535 :
3536 26 : PQclear(lo_res);
3537 :
3538 26 : destroyPQExpBuffer(loFrozenQry);
3539 26 : destroyPQExpBuffer(loHorizonQry);
3540 26 : destroyPQExpBuffer(loOutQry);
3541 : }
3542 :
3543 120 : PQclear(res);
3544 :
3545 120 : free(qdatname);
3546 120 : destroyPQExpBuffer(dbQry);
3547 120 : destroyPQExpBuffer(delQry);
3548 120 : destroyPQExpBuffer(creaQry);
3549 120 : destroyPQExpBuffer(labelq);
3550 120 : }
3551 :
3552 : /*
3553 : * Collect any database-specific or role-and-database-specific SET options
3554 : * for this database, and append them to outbuf.
3555 : */
3556 : static void
3557 120 : dumpDatabaseConfig(Archive *AH, PQExpBuffer outbuf,
3558 : const char *dbname, Oid dboid)
3559 : {
3560 120 : PGconn *conn = GetConnection(AH);
3561 120 : PQExpBuffer buf = createPQExpBuffer();
3562 : PGresult *res;
3563 :
3564 : /* First collect database-specific options */
3565 120 : printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
3566 : "WHERE setrole = 0 AND setdatabase = '%u'::oid",
3567 : dboid);
3568 :
3569 120 : res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3570 :
3571 180 : for (int i = 0; i < PQntuples(res); i++)
3572 60 : makeAlterConfigCommand(conn, PQgetvalue(res, i, 0),
3573 : "DATABASE", dbname, NULL, NULL,
3574 : outbuf);
3575 :
3576 120 : PQclear(res);
3577 :
3578 : /* Now look for role-and-database-specific options */
3579 120 : printfPQExpBuffer(buf, "SELECT rolname, unnest(setconfig) "
3580 : "FROM pg_db_role_setting s, pg_roles r "
3581 : "WHERE setrole = r.oid AND setdatabase = '%u'::oid",
3582 : dboid);
3583 :
3584 120 : res = ExecuteSqlQuery(AH, buf->data, PGRES_TUPLES_OK);
3585 :
3586 120 : for (int i = 0; i < PQntuples(res); i++)
3587 0 : makeAlterConfigCommand(conn, PQgetvalue(res, i, 1),
3588 0 : "ROLE", PQgetvalue(res, i, 0),
3589 : "DATABASE", dbname,
3590 : outbuf);
3591 :
3592 120 : PQclear(res);
3593 :
3594 120 : destroyPQExpBuffer(buf);
3595 120 : }
3596 :
3597 : /*
3598 : * dumpEncoding: put the correct encoding into the archive
3599 : */
3600 : static void
3601 308 : dumpEncoding(Archive *AH)
3602 : {
3603 308 : const char *encname = pg_encoding_to_char(AH->encoding);
3604 308 : PQExpBuffer qry = createPQExpBuffer();
3605 :
3606 308 : pg_log_info("saving encoding = %s", encname);
3607 :
3608 308 : appendPQExpBufferStr(qry, "SET client_encoding = ");
3609 308 : appendStringLiteralAH(qry, encname, AH);
3610 308 : appendPQExpBufferStr(qry, ";\n");
3611 :
3612 308 : ArchiveEntry(AH, nilCatalogId, createDumpId(),
3613 308 : ARCHIVE_OPTS(.tag = "ENCODING",
3614 : .description = "ENCODING",
3615 : .section = SECTION_PRE_DATA,
3616 : .createStmt = qry->data));
3617 :
3618 308 : destroyPQExpBuffer(qry);
3619 308 : }
3620 :
3621 :
3622 : /*
3623 : * dumpStdStrings: put the correct escape string behavior into the archive
3624 : */
3625 : static void
3626 308 : dumpStdStrings(Archive *AH)
3627 : {
3628 308 : const char *stdstrings = AH->std_strings ? "on" : "off";
3629 308 : PQExpBuffer qry = createPQExpBuffer();
3630 :
3631 308 : pg_log_info("saving \"standard_conforming_strings = %s\"",
3632 : stdstrings);
3633 :
3634 308 : appendPQExpBuffer(qry, "SET standard_conforming_strings = '%s';\n",
3635 : stdstrings);
3636 :
3637 308 : ArchiveEntry(AH, nilCatalogId, createDumpId(),
3638 308 : ARCHIVE_OPTS(.tag = "STDSTRINGS",
3639 : .description = "STDSTRINGS",
3640 : .section = SECTION_PRE_DATA,
3641 : .createStmt = qry->data));
3642 :
3643 308 : destroyPQExpBuffer(qry);
3644 308 : }
3645 :
3646 : /*
3647 : * dumpSearchPath: record the active search_path in the archive
3648 : */
3649 : static void
3650 308 : dumpSearchPath(Archive *AH)
3651 : {
3652 308 : PQExpBuffer qry = createPQExpBuffer();
3653 308 : PQExpBuffer path = createPQExpBuffer();
3654 : PGresult *res;
3655 308 : char **schemanames = NULL;
3656 308 : int nschemanames = 0;
3657 : int i;
3658 :
3659 : /*
3660 : * We use the result of current_schemas(), not the search_path GUC,
3661 : * because that might contain wildcards such as "$user", which won't
3662 : * necessarily have the same value during restore. Also, this way avoids
3663 : * listing schemas that may appear in search_path but not actually exist,
3664 : * which seems like a prudent exclusion.
3665 : */
3666 308 : res = ExecuteSqlQueryForSingleRow(AH,
3667 : "SELECT pg_catalog.current_schemas(false)");
3668 :
3669 308 : if (!parsePGArray(PQgetvalue(res, 0, 0), &schemanames, &nschemanames))
3670 0 : pg_fatal("could not parse result of current_schemas()");
3671 :
3672 : /*
3673 : * We use set_config(), not a simple "SET search_path" command, because
3674 : * the latter has less-clean behavior if the search path is empty. While
3675 : * that's likely to get fixed at some point, it seems like a good idea to
3676 : * be as backwards-compatible as possible in what we put into archives.
3677 : */
3678 308 : for (i = 0; i < nschemanames; i++)
3679 : {
3680 0 : if (i > 0)
3681 0 : appendPQExpBufferStr(path, ", ");
3682 0 : appendPQExpBufferStr(path, fmtId(schemanames[i]));
3683 : }
3684 :
3685 308 : appendPQExpBufferStr(qry, "SELECT pg_catalog.set_config('search_path', ");
3686 308 : appendStringLiteralAH(qry, path->data, AH);
3687 308 : appendPQExpBufferStr(qry, ", false);\n");
3688 :
3689 308 : pg_log_info("saving \"search_path = %s\"", path->data);
3690 :
3691 308 : ArchiveEntry(AH, nilCatalogId, createDumpId(),
3692 308 : ARCHIVE_OPTS(.tag = "SEARCHPATH",
3693 : .description = "SEARCHPATH",
3694 : .section = SECTION_PRE_DATA,
3695 : .createStmt = qry->data));
3696 :
3697 : /* Also save it in AH->searchpath, in case we're doing plain text dump */
3698 308 : AH->searchpath = pg_strdup(qry->data);
3699 :
3700 308 : free(schemanames);
3701 308 : PQclear(res);
3702 308 : destroyPQExpBuffer(qry);
3703 308 : destroyPQExpBuffer(path);
3704 308 : }
3705 :
3706 :
3707 : /*
3708 : * getLOs:
3709 : * Collect schema-level data about large objects
3710 : */
3711 : static void
3712 256 : getLOs(Archive *fout)
3713 : {
3714 256 : DumpOptions *dopt = fout->dopt;
3715 256 : PQExpBuffer loQry = createPQExpBuffer();
3716 : PGresult *res;
3717 : int ntups;
3718 : int i;
3719 : int n;
3720 : int i_oid;
3721 : int i_lomowner;
3722 : int i_lomacl;
3723 : int i_acldefault;
3724 :
3725 256 : pg_log_info("reading large objects");
3726 :
3727 : /*
3728 : * Fetch LO OIDs and owner/ACL data. Order the data so that all the blobs
3729 : * with the same owner/ACL appear together.
3730 : */
3731 256 : appendPQExpBufferStr(loQry,
3732 : "SELECT oid, lomowner, lomacl, "
3733 : "acldefault('L', lomowner) AS acldefault "
3734 : "FROM pg_largeobject_metadata "
3735 : "ORDER BY lomowner, lomacl::pg_catalog.text, oid");
3736 :
3737 256 : res = ExecuteSqlQuery(fout, loQry->data, PGRES_TUPLES_OK);
3738 :
3739 256 : i_oid = PQfnumber(res, "oid");
3740 256 : i_lomowner = PQfnumber(res, "lomowner");
3741 256 : i_lomacl = PQfnumber(res, "lomacl");
3742 256 : i_acldefault = PQfnumber(res, "acldefault");
3743 :
3744 256 : ntups = PQntuples(res);
3745 :
3746 : /*
3747 : * Group the blobs into suitably-sized groups that have the same owner and
3748 : * ACL setting, and build a metadata and a data DumpableObject for each
3749 : * group. (If we supported initprivs for blobs, we'd have to insist that
3750 : * groups also share initprivs settings, since the DumpableObject only has
3751 : * room for one.) i is the index of the first tuple in the current group,
3752 : * and n is the number of tuples we include in the group.
3753 : */
3754 402 : for (i = 0; i < ntups; i += n)
3755 : {
3756 146 : Oid thisoid = atooid(PQgetvalue(res, i, i_oid));
3757 146 : char *thisowner = PQgetvalue(res, i, i_lomowner);
3758 146 : char *thisacl = PQgetvalue(res, i, i_lomacl);
3759 : LoInfo *loinfo;
3760 : DumpableObject *lodata;
3761 : char namebuf[64];
3762 :
3763 : /* Scan to find first tuple not to be included in group */
3764 146 : n = 1;
3765 166 : while (n < MAX_BLOBS_PER_ARCHIVE_ENTRY && i + n < ntups)
3766 : {
3767 88 : if (strcmp(thisowner, PQgetvalue(res, i + n, i_lomowner)) != 0 ||
3768 88 : strcmp(thisacl, PQgetvalue(res, i + n, i_lomacl)) != 0)
3769 : break;
3770 20 : n++;
3771 : }
3772 :
3773 : /* Build the metadata DumpableObject */
3774 146 : loinfo = (LoInfo *) pg_malloc(offsetof(LoInfo, looids) + n * sizeof(Oid));
3775 :
3776 146 : loinfo->dobj.objType = DO_LARGE_OBJECT;
3777 146 : loinfo->dobj.catId.tableoid = LargeObjectRelationId;
3778 146 : loinfo->dobj.catId.oid = thisoid;
3779 146 : AssignDumpId(&loinfo->dobj);
3780 :
3781 146 : if (n > 1)
3782 10 : snprintf(namebuf, sizeof(namebuf), "%u..%u", thisoid,
3783 10 : atooid(PQgetvalue(res, i + n - 1, i_oid)));
3784 : else
3785 136 : snprintf(namebuf, sizeof(namebuf), "%u", thisoid);
3786 146 : loinfo->dobj.name = pg_strdup(namebuf);
3787 146 : loinfo->dacl.acl = pg_strdup(thisacl);
3788 146 : loinfo->dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
3789 146 : loinfo->dacl.privtype = 0;
3790 146 : loinfo->dacl.initprivs = NULL;
3791 146 : loinfo->rolname = getRoleName(thisowner);
3792 146 : loinfo->numlos = n;
3793 146 : loinfo->looids[0] = thisoid;
3794 : /* Collect OIDs of the remaining blobs in this group */
3795 166 : for (int k = 1; k < n; k++)
3796 : {
3797 : CatalogId extraID;
3798 :
3799 20 : loinfo->looids[k] = atooid(PQgetvalue(res, i + k, i_oid));
3800 :
3801 : /* Make sure we can look up loinfo by any of the blobs' OIDs */
3802 20 : extraID.tableoid = LargeObjectRelationId;
3803 20 : extraID.oid = loinfo->looids[k];
3804 20 : recordAdditionalCatalogID(extraID, &loinfo->dobj);
3805 : }
3806 :
3807 : /* LOs have data */
3808 146 : loinfo->dobj.components |= DUMP_COMPONENT_DATA;
3809 :
3810 : /* Mark whether LO group has a non-empty ACL */
3811 146 : if (!PQgetisnull(res, i, i_lomacl))
3812 68 : loinfo->dobj.components |= DUMP_COMPONENT_ACL;
3813 :
3814 : /*
3815 : * In binary-upgrade mode for LOs, we do *not* dump out the LO data,
3816 : * as it will be copied by pg_upgrade, which simply copies the
3817 : * pg_largeobject table. We *do* however dump out anything but the
3818 : * data, as pg_upgrade copies just pg_largeobject, but not
3819 : * pg_largeobject_metadata, after the dump is restored.
3820 : */
3821 146 : if (dopt->binary_upgrade)
3822 6 : loinfo->dobj.dump &= ~DUMP_COMPONENT_DATA;
3823 :
3824 : /*
3825 : * Create a "BLOBS" data item for the group, too. This is just a
3826 : * placeholder for sorting; it carries no data now.
3827 : */
3828 146 : lodata = (DumpableObject *) pg_malloc(sizeof(DumpableObject));
3829 146 : lodata->objType = DO_LARGE_OBJECT_DATA;
3830 146 : lodata->catId = nilCatalogId;
3831 146 : AssignDumpId(lodata);
3832 146 : lodata->name = pg_strdup(namebuf);
3833 146 : lodata->components |= DUMP_COMPONENT_DATA;
3834 : /* Set up explicit dependency from data to metadata */
3835 146 : lodata->dependencies = (DumpId *) pg_malloc(sizeof(DumpId));
3836 146 : lodata->dependencies[0] = loinfo->dobj.dumpId;
3837 146 : lodata->nDeps = lodata->allocDeps = 1;
3838 : }
3839 :
3840 256 : PQclear(res);
3841 256 : destroyPQExpBuffer(loQry);
3842 256 : }
3843 :
3844 : /*
3845 : * dumpLO
3846 : *
3847 : * dump the definition (metadata) of the given large object group
3848 : */
3849 : static void
3850 146 : dumpLO(Archive *fout, const LoInfo *loinfo)
3851 : {
3852 146 : PQExpBuffer cquery = createPQExpBuffer();
3853 :
3854 : /*
3855 : * The "definition" is just a newline-separated list of OIDs. We need to
3856 : * put something into the dropStmt too, but it can just be a comment.
3857 : */
3858 312 : for (int i = 0; i < loinfo->numlos; i++)
3859 166 : appendPQExpBuffer(cquery, "%u\n", loinfo->looids[i]);
3860 :
3861 146 : if (loinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
3862 146 : ArchiveEntry(fout, loinfo->dobj.catId, loinfo->dobj.dumpId,
3863 146 : ARCHIVE_OPTS(.tag = loinfo->dobj.name,
3864 : .owner = loinfo->rolname,
3865 : .description = "BLOB METADATA",
3866 : .section = SECTION_DATA,
3867 : .createStmt = cquery->data,
3868 : .dropStmt = "-- dummy"));
3869 :
3870 : /*
3871 : * Dump per-blob comments and seclabels if any. We assume these are rare
3872 : * enough that it's okay to generate retail TOC entries for them.
3873 : */
3874 146 : if (loinfo->dobj.dump & (DUMP_COMPONENT_COMMENT |
3875 : DUMP_COMPONENT_SECLABEL))
3876 : {
3877 176 : for (int i = 0; i < loinfo->numlos; i++)
3878 : {
3879 : CatalogId catId;
3880 : char namebuf[32];
3881 :
3882 : /* Build identifying info for this blob */
3883 98 : catId.tableoid = loinfo->dobj.catId.tableoid;
3884 98 : catId.oid = loinfo->looids[i];
3885 98 : snprintf(namebuf, sizeof(namebuf), "%u", loinfo->looids[i]);
3886 :
3887 98 : if (loinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
3888 98 : dumpComment(fout, "LARGE OBJECT", namebuf,
3889 : NULL, loinfo->rolname,
3890 : catId, 0, loinfo->dobj.dumpId);
3891 :
3892 98 : if (loinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
3893 0 : dumpSecLabel(fout, "LARGE OBJECT", namebuf,
3894 : NULL, loinfo->rolname,
3895 : catId, 0, loinfo->dobj.dumpId);
3896 : }
3897 : }
3898 :
3899 : /*
3900 : * Dump the ACLs if any (remember that all blobs in the group will have
3901 : * the same ACL). If there's just one blob, dump a simple ACL entry; if
3902 : * there's more, make a "LARGE OBJECTS" entry that really contains only
3903 : * the ACL for the first blob. _printTocEntry() will be cued by the tag
3904 : * string to emit a mutated version for each blob.
3905 : */
3906 146 : if (loinfo->dobj.dump & DUMP_COMPONENT_ACL)
3907 : {
3908 : char namebuf[32];
3909 :
3910 : /* Build identifying info for the first blob */
3911 68 : snprintf(namebuf, sizeof(namebuf), "%u", loinfo->looids[0]);
3912 :
3913 68 : if (loinfo->numlos > 1)
3914 : {
3915 : char tagbuf[64];
3916 :
3917 0 : snprintf(tagbuf, sizeof(tagbuf), "LARGE OBJECTS %u..%u",
3918 0 : loinfo->looids[0], loinfo->looids[loinfo->numlos - 1]);
3919 :
3920 0 : dumpACL(fout, loinfo->dobj.dumpId, InvalidDumpId,
3921 : "LARGE OBJECT", namebuf, NULL, NULL,
3922 : tagbuf, loinfo->rolname, &loinfo->dacl);
3923 : }
3924 : else
3925 : {
3926 68 : dumpACL(fout, loinfo->dobj.dumpId, InvalidDumpId,
3927 : "LARGE OBJECT", namebuf, NULL, NULL,
3928 : NULL, loinfo->rolname, &loinfo->dacl);
3929 : }
3930 : }
3931 :
3932 146 : destroyPQExpBuffer(cquery);
3933 146 : }
3934 :
3935 : /*
3936 : * dumpLOs:
3937 : * dump the data contents of the large objects in the given group
3938 : */
3939 : static int
3940 132 : dumpLOs(Archive *fout, const void *arg)
3941 : {
3942 132 : const LoInfo *loinfo = (const LoInfo *) arg;
3943 132 : PGconn *conn = GetConnection(fout);
3944 : char buf[LOBBUFSIZE];
3945 :
3946 132 : pg_log_info("saving large objects \"%s\"", loinfo->dobj.name);
3947 :
3948 280 : for (int i = 0; i < loinfo->numlos; i++)
3949 : {
3950 148 : Oid loOid = loinfo->looids[i];
3951 : int loFd;
3952 : int cnt;
3953 :
3954 : /* Open the LO */
3955 148 : loFd = lo_open(conn, loOid, INV_READ);
3956 148 : if (loFd == -1)
3957 0 : pg_fatal("could not open large object %u: %s",
3958 : loOid, PQerrorMessage(conn));
3959 :
3960 148 : StartLO(fout, loOid);
3961 :
3962 : /* Now read it in chunks, sending data to archive */
3963 : do
3964 : {
3965 226 : cnt = lo_read(conn, loFd, buf, LOBBUFSIZE);
3966 226 : if (cnt < 0)
3967 0 : pg_fatal("error reading large object %u: %s",
3968 : loOid, PQerrorMessage(conn));
3969 :
3970 226 : WriteData(fout, buf, cnt);
3971 226 : } while (cnt > 0);
3972 :
3973 148 : lo_close(conn, loFd);
3974 :
3975 148 : EndLO(fout, loOid);
3976 : }
3977 :
3978 132 : return 1;
3979 : }
3980 :
3981 : /*
3982 : * getPolicies
3983 : * get information about all RLS policies on dumpable tables.
3984 : */
3985 : void
3986 308 : getPolicies(Archive *fout, TableInfo tblinfo[], int numTables)
3987 : {
3988 : PQExpBuffer query;
3989 : PQExpBuffer tbloids;
3990 : PGresult *res;
3991 : PolicyInfo *polinfo;
3992 : int i_oid;
3993 : int i_tableoid;
3994 : int i_polrelid;
3995 : int i_polname;
3996 : int i_polcmd;
3997 : int i_polpermissive;
3998 : int i_polroles;
3999 : int i_polqual;
4000 : int i_polwithcheck;
4001 : int i,
4002 : j,
4003 : ntups;
4004 :
4005 : /* No policies before 9.5 */
4006 308 : if (fout->remoteVersion < 90500)
4007 0 : return;
4008 :
4009 308 : query = createPQExpBuffer();
4010 308 : tbloids = createPQExpBuffer();
4011 :
4012 : /*
4013 : * Identify tables of interest, and check which ones have RLS enabled.
4014 : */
4015 308 : appendPQExpBufferChar(tbloids, '{');
4016 81216 : for (i = 0; i < numTables; i++)
4017 : {
4018 80908 : TableInfo *tbinfo = &tblinfo[i];
4019 :
4020 : /* Ignore row security on tables not to be dumped */
4021 80908 : if (!(tbinfo->dobj.dump & DUMP_COMPONENT_POLICY))
4022 68746 : continue;
4023 :
4024 : /* It can't have RLS or policies if it's not a table */
4025 12162 : if (tbinfo->relkind != RELKIND_RELATION &&
4026 3598 : tbinfo->relkind != RELKIND_PARTITIONED_TABLE)
4027 2544 : continue;
4028 :
4029 : /* Add it to the list of table OIDs to be probed below */
4030 9618 : if (tbloids->len > 1) /* do we have more than the '{'? */
4031 9422 : appendPQExpBufferChar(tbloids, ',');
4032 9618 : appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
4033 :
4034 : /* Is RLS enabled? (That's separate from whether it has policies) */
4035 9618 : if (tbinfo->rowsec)
4036 : {
4037 104 : tbinfo->dobj.components |= DUMP_COMPONENT_POLICY;
4038 :
4039 : /*
4040 : * We represent RLS being enabled on a table by creating a
4041 : * PolicyInfo object with null polname.
4042 : *
4043 : * Note: use tableoid 0 so that this object won't be mistaken for
4044 : * something that pg_depend entries apply to.
4045 : */
4046 104 : polinfo = pg_malloc(sizeof(PolicyInfo));
4047 104 : polinfo->dobj.objType = DO_POLICY;
4048 104 : polinfo->dobj.catId.tableoid = 0;
4049 104 : polinfo->dobj.catId.oid = tbinfo->dobj.catId.oid;
4050 104 : AssignDumpId(&polinfo->dobj);
4051 104 : polinfo->dobj.namespace = tbinfo->dobj.namespace;
4052 104 : polinfo->dobj.name = pg_strdup(tbinfo->dobj.name);
4053 104 : polinfo->poltable = tbinfo;
4054 104 : polinfo->polname = NULL;
4055 104 : polinfo->polcmd = '\0';
4056 104 : polinfo->polpermissive = 0;
4057 104 : polinfo->polroles = NULL;
4058 104 : polinfo->polqual = NULL;
4059 104 : polinfo->polwithcheck = NULL;
4060 : }
4061 : }
4062 308 : appendPQExpBufferChar(tbloids, '}');
4063 :
4064 : /*
4065 : * Now, read all RLS policies belonging to the tables of interest, and
4066 : * create PolicyInfo objects for them. (Note that we must filter the
4067 : * results server-side not locally, because we dare not apply pg_get_expr
4068 : * to tables we don't have lock on.)
4069 : */
4070 308 : pg_log_info("reading row-level security policies");
4071 :
4072 308 : printfPQExpBuffer(query,
4073 : "SELECT pol.oid, pol.tableoid, pol.polrelid, pol.polname, pol.polcmd, ");
4074 308 : if (fout->remoteVersion >= 100000)
4075 308 : appendPQExpBufferStr(query, "pol.polpermissive, ");
4076 : else
4077 0 : appendPQExpBufferStr(query, "'t' as polpermissive, ");
4078 308 : appendPQExpBuffer(query,
4079 : "CASE WHEN pol.polroles = '{0}' THEN NULL ELSE "
4080 : " 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, "
4081 : "pg_catalog.pg_get_expr(pol.polqual, pol.polrelid) AS polqual, "
4082 : "pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid) AS polwithcheck "
4083 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
4084 : "JOIN pg_catalog.pg_policy pol ON (src.tbloid = pol.polrelid)",
4085 : tbloids->data);
4086 :
4087 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4088 :
4089 308 : ntups = PQntuples(res);
4090 308 : if (ntups > 0)
4091 : {
4092 84 : i_oid = PQfnumber(res, "oid");
4093 84 : i_tableoid = PQfnumber(res, "tableoid");
4094 84 : i_polrelid = PQfnumber(res, "polrelid");
4095 84 : i_polname = PQfnumber(res, "polname");
4096 84 : i_polcmd = PQfnumber(res, "polcmd");
4097 84 : i_polpermissive = PQfnumber(res, "polpermissive");
4098 84 : i_polroles = PQfnumber(res, "polroles");
4099 84 : i_polqual = PQfnumber(res, "polqual");
4100 84 : i_polwithcheck = PQfnumber(res, "polwithcheck");
4101 :
4102 84 : polinfo = pg_malloc(ntups * sizeof(PolicyInfo));
4103 :
4104 618 : for (j = 0; j < ntups; j++)
4105 : {
4106 534 : Oid polrelid = atooid(PQgetvalue(res, j, i_polrelid));
4107 534 : TableInfo *tbinfo = findTableByOid(polrelid);
4108 :
4109 534 : tbinfo->dobj.components |= DUMP_COMPONENT_POLICY;
4110 :
4111 534 : polinfo[j].dobj.objType = DO_POLICY;
4112 534 : polinfo[j].dobj.catId.tableoid =
4113 534 : atooid(PQgetvalue(res, j, i_tableoid));
4114 534 : polinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
4115 534 : AssignDumpId(&polinfo[j].dobj);
4116 534 : polinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4117 534 : polinfo[j].poltable = tbinfo;
4118 534 : polinfo[j].polname = pg_strdup(PQgetvalue(res, j, i_polname));
4119 534 : polinfo[j].dobj.name = pg_strdup(polinfo[j].polname);
4120 :
4121 534 : polinfo[j].polcmd = *(PQgetvalue(res, j, i_polcmd));
4122 534 : polinfo[j].polpermissive = *(PQgetvalue(res, j, i_polpermissive)) == 't';
4123 :
4124 534 : if (PQgetisnull(res, j, i_polroles))
4125 238 : polinfo[j].polroles = NULL;
4126 : else
4127 296 : polinfo[j].polroles = pg_strdup(PQgetvalue(res, j, i_polroles));
4128 :
4129 534 : if (PQgetisnull(res, j, i_polqual))
4130 74 : polinfo[j].polqual = NULL;
4131 : else
4132 460 : polinfo[j].polqual = pg_strdup(PQgetvalue(res, j, i_polqual));
4133 :
4134 534 : if (PQgetisnull(res, j, i_polwithcheck))
4135 282 : polinfo[j].polwithcheck = NULL;
4136 : else
4137 252 : polinfo[j].polwithcheck
4138 252 : = pg_strdup(PQgetvalue(res, j, i_polwithcheck));
4139 : }
4140 : }
4141 :
4142 308 : PQclear(res);
4143 :
4144 308 : destroyPQExpBuffer(query);
4145 308 : destroyPQExpBuffer(tbloids);
4146 : }
4147 :
4148 : /*
4149 : * dumpPolicy
4150 : * dump the definition of the given policy
4151 : */
4152 : static void
4153 638 : dumpPolicy(Archive *fout, const PolicyInfo *polinfo)
4154 : {
4155 638 : DumpOptions *dopt = fout->dopt;
4156 638 : TableInfo *tbinfo = polinfo->poltable;
4157 : PQExpBuffer query;
4158 : PQExpBuffer delqry;
4159 : PQExpBuffer polprefix;
4160 : char *qtabname;
4161 : const char *cmd;
4162 : char *tag;
4163 :
4164 : /* Do nothing in data-only dump */
4165 638 : if (dopt->dataOnly)
4166 56 : return;
4167 :
4168 : /*
4169 : * If polname is NULL, then this record is just indicating that ROW LEVEL
4170 : * SECURITY is enabled for the table. Dump as ALTER TABLE <table> ENABLE
4171 : * ROW LEVEL SECURITY.
4172 : */
4173 582 : if (polinfo->polname == NULL)
4174 : {
4175 96 : query = createPQExpBuffer();
4176 :
4177 96 : appendPQExpBuffer(query, "ALTER TABLE %s ENABLE ROW LEVEL SECURITY;",
4178 96 : fmtQualifiedDumpable(tbinfo));
4179 :
4180 : /*
4181 : * We must emit the ROW SECURITY object's dependency on its table
4182 : * explicitly, because it will not match anything in pg_depend (unlike
4183 : * the case for other PolicyInfo objects).
4184 : */
4185 96 : if (polinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4186 96 : ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
4187 96 : ARCHIVE_OPTS(.tag = polinfo->dobj.name,
4188 : .namespace = polinfo->dobj.namespace->dobj.name,
4189 : .owner = tbinfo->rolname,
4190 : .description = "ROW SECURITY",
4191 : .section = SECTION_POST_DATA,
4192 : .createStmt = query->data,
4193 : .deps = &(tbinfo->dobj.dumpId),
4194 : .nDeps = 1));
4195 :
4196 96 : destroyPQExpBuffer(query);
4197 96 : return;
4198 : }
4199 :
4200 486 : if (polinfo->polcmd == '*')
4201 162 : cmd = "";
4202 324 : else if (polinfo->polcmd == 'r')
4203 86 : cmd = " FOR SELECT";
4204 238 : else if (polinfo->polcmd == 'a')
4205 66 : cmd = " FOR INSERT";
4206 172 : else if (polinfo->polcmd == 'w')
4207 86 : cmd = " FOR UPDATE";
4208 86 : else if (polinfo->polcmd == 'd')
4209 86 : cmd = " FOR DELETE";
4210 : else
4211 0 : pg_fatal("unexpected policy command type: %c",
4212 : polinfo->polcmd);
4213 :
4214 486 : query = createPQExpBuffer();
4215 486 : delqry = createPQExpBuffer();
4216 486 : polprefix = createPQExpBuffer();
4217 :
4218 486 : qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
4219 :
4220 486 : appendPQExpBuffer(query, "CREATE POLICY %s", fmtId(polinfo->polname));
4221 :
4222 486 : appendPQExpBuffer(query, " ON %s%s%s", fmtQualifiedDumpable(tbinfo),
4223 486 : !polinfo->polpermissive ? " AS RESTRICTIVE" : "", cmd);
4224 :
4225 486 : if (polinfo->polroles != NULL)
4226 264 : appendPQExpBuffer(query, " TO %s", polinfo->polroles);
4227 :
4228 486 : if (polinfo->polqual != NULL)
4229 420 : appendPQExpBuffer(query, " USING (%s)", polinfo->polqual);
4230 :
4231 486 : if (polinfo->polwithcheck != NULL)
4232 228 : appendPQExpBuffer(query, " WITH CHECK (%s)", polinfo->polwithcheck);
4233 :
4234 486 : appendPQExpBufferStr(query, ";\n");
4235 :
4236 486 : appendPQExpBuffer(delqry, "DROP POLICY %s", fmtId(polinfo->polname));
4237 486 : appendPQExpBuffer(delqry, " ON %s;\n", fmtQualifiedDumpable(tbinfo));
4238 :
4239 486 : appendPQExpBuffer(polprefix, "POLICY %s ON",
4240 486 : fmtId(polinfo->polname));
4241 :
4242 486 : tag = psprintf("%s %s", tbinfo->dobj.name, polinfo->dobj.name);
4243 :
4244 486 : if (polinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4245 486 : ArchiveEntry(fout, polinfo->dobj.catId, polinfo->dobj.dumpId,
4246 486 : ARCHIVE_OPTS(.tag = tag,
4247 : .namespace = polinfo->dobj.namespace->dobj.name,
4248 : .owner = tbinfo->rolname,
4249 : .description = "POLICY",
4250 : .section = SECTION_POST_DATA,
4251 : .createStmt = query->data,
4252 : .dropStmt = delqry->data));
4253 :
4254 486 : if (polinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4255 0 : dumpComment(fout, polprefix->data, qtabname,
4256 0 : tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
4257 : polinfo->dobj.catId, 0, polinfo->dobj.dumpId);
4258 :
4259 486 : free(tag);
4260 486 : destroyPQExpBuffer(query);
4261 486 : destroyPQExpBuffer(delqry);
4262 486 : destroyPQExpBuffer(polprefix);
4263 486 : free(qtabname);
4264 : }
4265 :
4266 : /*
4267 : * getPublications
4268 : * get information about publications
4269 : */
4270 : void
4271 308 : getPublications(Archive *fout)
4272 : {
4273 308 : DumpOptions *dopt = fout->dopt;
4274 : PQExpBuffer query;
4275 : PGresult *res;
4276 : PublicationInfo *pubinfo;
4277 : int i_tableoid;
4278 : int i_oid;
4279 : int i_pubname;
4280 : int i_pubowner;
4281 : int i_puballtables;
4282 : int i_pubinsert;
4283 : int i_pubupdate;
4284 : int i_pubdelete;
4285 : int i_pubtruncate;
4286 : int i_pubviaroot;
4287 : int i_pubgencols;
4288 : int i,
4289 : ntups;
4290 :
4291 308 : if (dopt->no_publications || fout->remoteVersion < 100000)
4292 0 : return;
4293 :
4294 308 : query = createPQExpBuffer();
4295 :
4296 : /* Get the publications. */
4297 308 : appendPQExpBufferStr(query, "SELECT p.tableoid, p.oid, p.pubname, "
4298 : "p.pubowner, p.puballtables, p.pubinsert, "
4299 : "p.pubupdate, p.pubdelete, ");
4300 :
4301 308 : if (fout->remoteVersion >= 110000)
4302 308 : appendPQExpBufferStr(query, "p.pubtruncate, ");
4303 : else
4304 0 : appendPQExpBufferStr(query, "false AS pubtruncate, ");
4305 :
4306 308 : if (fout->remoteVersion >= 130000)
4307 308 : appendPQExpBufferStr(query, "p.pubviaroot, ");
4308 : else
4309 0 : appendPQExpBufferStr(query, "false AS pubviaroot, ");
4310 :
4311 308 : if (fout->remoteVersion >= 180000)
4312 308 : appendPQExpBufferStr(query, "p.pubgencols ");
4313 : else
4314 0 : appendPQExpBufferStr(query, "false AS pubgencols ");
4315 :
4316 308 : appendPQExpBufferStr(query, "FROM pg_publication p");
4317 :
4318 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4319 :
4320 308 : ntups = PQntuples(res);
4321 :
4322 308 : if (ntups == 0)
4323 220 : goto cleanup;
4324 :
4325 88 : i_tableoid = PQfnumber(res, "tableoid");
4326 88 : i_oid = PQfnumber(res, "oid");
4327 88 : i_pubname = PQfnumber(res, "pubname");
4328 88 : i_pubowner = PQfnumber(res, "pubowner");
4329 88 : i_puballtables = PQfnumber(res, "puballtables");
4330 88 : i_pubinsert = PQfnumber(res, "pubinsert");
4331 88 : i_pubupdate = PQfnumber(res, "pubupdate");
4332 88 : i_pubdelete = PQfnumber(res, "pubdelete");
4333 88 : i_pubtruncate = PQfnumber(res, "pubtruncate");
4334 88 : i_pubviaroot = PQfnumber(res, "pubviaroot");
4335 88 : i_pubgencols = PQfnumber(res, "pubgencols");
4336 :
4337 88 : pubinfo = pg_malloc(ntups * sizeof(PublicationInfo));
4338 :
4339 520 : for (i = 0; i < ntups; i++)
4340 : {
4341 432 : pubinfo[i].dobj.objType = DO_PUBLICATION;
4342 432 : pubinfo[i].dobj.catId.tableoid =
4343 432 : atooid(PQgetvalue(res, i, i_tableoid));
4344 432 : pubinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4345 432 : AssignDumpId(&pubinfo[i].dobj);
4346 432 : pubinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_pubname));
4347 432 : pubinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_pubowner));
4348 432 : pubinfo[i].puballtables =
4349 432 : (strcmp(PQgetvalue(res, i, i_puballtables), "t") == 0);
4350 432 : pubinfo[i].pubinsert =
4351 432 : (strcmp(PQgetvalue(res, i, i_pubinsert), "t") == 0);
4352 432 : pubinfo[i].pubupdate =
4353 432 : (strcmp(PQgetvalue(res, i, i_pubupdate), "t") == 0);
4354 432 : pubinfo[i].pubdelete =
4355 432 : (strcmp(PQgetvalue(res, i, i_pubdelete), "t") == 0);
4356 432 : pubinfo[i].pubtruncate =
4357 432 : (strcmp(PQgetvalue(res, i, i_pubtruncate), "t") == 0);
4358 432 : pubinfo[i].pubviaroot =
4359 432 : (strcmp(PQgetvalue(res, i, i_pubviaroot), "t") == 0);
4360 432 : pubinfo[i].pubgencols =
4361 432 : (strcmp(PQgetvalue(res, i, i_pubgencols), "t") == 0);
4362 :
4363 : /* Decide whether we want to dump it */
4364 432 : selectDumpableObject(&(pubinfo[i].dobj), fout);
4365 : }
4366 :
4367 88 : cleanup:
4368 308 : PQclear(res);
4369 :
4370 308 : destroyPQExpBuffer(query);
4371 : }
4372 :
4373 : /*
4374 : * dumpPublication
4375 : * dump the definition of the given publication
4376 : */
4377 : static void
4378 352 : dumpPublication(Archive *fout, const PublicationInfo *pubinfo)
4379 : {
4380 352 : DumpOptions *dopt = fout->dopt;
4381 : PQExpBuffer delq;
4382 : PQExpBuffer query;
4383 : char *qpubname;
4384 352 : bool first = true;
4385 :
4386 : /* Do nothing in data-only dump */
4387 352 : if (dopt->dataOnly)
4388 30 : return;
4389 :
4390 322 : delq = createPQExpBuffer();
4391 322 : query = createPQExpBuffer();
4392 :
4393 322 : qpubname = pg_strdup(fmtId(pubinfo->dobj.name));
4394 :
4395 322 : appendPQExpBuffer(delq, "DROP PUBLICATION %s;\n",
4396 : qpubname);
4397 :
4398 322 : appendPQExpBuffer(query, "CREATE PUBLICATION %s",
4399 : qpubname);
4400 :
4401 322 : if (pubinfo->puballtables)
4402 66 : appendPQExpBufferStr(query, " FOR ALL TABLES");
4403 :
4404 322 : appendPQExpBufferStr(query, " WITH (publish = '");
4405 322 : if (pubinfo->pubinsert)
4406 : {
4407 258 : appendPQExpBufferStr(query, "insert");
4408 258 : first = false;
4409 : }
4410 :
4411 322 : if (pubinfo->pubupdate)
4412 : {
4413 258 : if (!first)
4414 258 : appendPQExpBufferStr(query, ", ");
4415 :
4416 258 : appendPQExpBufferStr(query, "update");
4417 258 : first = false;
4418 : }
4419 :
4420 322 : if (pubinfo->pubdelete)
4421 : {
4422 258 : if (!first)
4423 258 : appendPQExpBufferStr(query, ", ");
4424 :
4425 258 : appendPQExpBufferStr(query, "delete");
4426 258 : first = false;
4427 : }
4428 :
4429 322 : if (pubinfo->pubtruncate)
4430 : {
4431 258 : if (!first)
4432 258 : appendPQExpBufferStr(query, ", ");
4433 :
4434 258 : appendPQExpBufferStr(query, "truncate");
4435 258 : first = false;
4436 : }
4437 :
4438 322 : appendPQExpBufferChar(query, '\'');
4439 :
4440 322 : if (pubinfo->pubviaroot)
4441 0 : appendPQExpBufferStr(query, ", publish_via_partition_root = true");
4442 :
4443 322 : if (pubinfo->pubgencols)
4444 64 : appendPQExpBufferStr(query, ", publish_generated_columns = true");
4445 :
4446 322 : appendPQExpBufferStr(query, ");\n");
4447 :
4448 322 : if (pubinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4449 322 : ArchiveEntry(fout, pubinfo->dobj.catId, pubinfo->dobj.dumpId,
4450 322 : ARCHIVE_OPTS(.tag = pubinfo->dobj.name,
4451 : .owner = pubinfo->rolname,
4452 : .description = "PUBLICATION",
4453 : .section = SECTION_POST_DATA,
4454 : .createStmt = query->data,
4455 : .dropStmt = delq->data));
4456 :
4457 322 : if (pubinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
4458 64 : dumpComment(fout, "PUBLICATION", qpubname,
4459 : NULL, pubinfo->rolname,
4460 : pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
4461 :
4462 322 : if (pubinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
4463 0 : dumpSecLabel(fout, "PUBLICATION", qpubname,
4464 : NULL, pubinfo->rolname,
4465 : pubinfo->dobj.catId, 0, pubinfo->dobj.dumpId);
4466 :
4467 322 : destroyPQExpBuffer(delq);
4468 322 : destroyPQExpBuffer(query);
4469 322 : free(qpubname);
4470 : }
4471 :
4472 : /*
4473 : * getPublicationNamespaces
4474 : * get information about publication membership for dumpable schemas.
4475 : */
4476 : void
4477 308 : getPublicationNamespaces(Archive *fout)
4478 : {
4479 : PQExpBuffer query;
4480 : PGresult *res;
4481 : PublicationSchemaInfo *pubsinfo;
4482 308 : DumpOptions *dopt = fout->dopt;
4483 : int i_tableoid;
4484 : int i_oid;
4485 : int i_pnpubid;
4486 : int i_pnnspid;
4487 : int i,
4488 : j,
4489 : ntups;
4490 :
4491 308 : if (dopt->no_publications || fout->remoteVersion < 150000)
4492 0 : return;
4493 :
4494 308 : query = createPQExpBuffer();
4495 :
4496 : /* Collect all publication membership info. */
4497 308 : appendPQExpBufferStr(query,
4498 : "SELECT tableoid, oid, pnpubid, pnnspid "
4499 : "FROM pg_catalog.pg_publication_namespace");
4500 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4501 :
4502 308 : ntups = PQntuples(res);
4503 :
4504 308 : i_tableoid = PQfnumber(res, "tableoid");
4505 308 : i_oid = PQfnumber(res, "oid");
4506 308 : i_pnpubid = PQfnumber(res, "pnpubid");
4507 308 : i_pnnspid = PQfnumber(res, "pnnspid");
4508 :
4509 : /* this allocation may be more than we need */
4510 308 : pubsinfo = pg_malloc(ntups * sizeof(PublicationSchemaInfo));
4511 308 : j = 0;
4512 :
4513 480 : for (i = 0; i < ntups; i++)
4514 : {
4515 172 : Oid pnpubid = atooid(PQgetvalue(res, i, i_pnpubid));
4516 172 : Oid pnnspid = atooid(PQgetvalue(res, i, i_pnnspid));
4517 : PublicationInfo *pubinfo;
4518 : NamespaceInfo *nspinfo;
4519 :
4520 : /*
4521 : * Ignore any entries for which we aren't interested in either the
4522 : * publication or the rel.
4523 : */
4524 172 : pubinfo = findPublicationByOid(pnpubid);
4525 172 : if (pubinfo == NULL)
4526 0 : continue;
4527 172 : nspinfo = findNamespaceByOid(pnnspid);
4528 172 : if (nspinfo == NULL)
4529 0 : continue;
4530 :
4531 : /*
4532 : * We always dump publication namespaces unless the corresponding
4533 : * namespace is excluded from the dump.
4534 : */
4535 172 : if (nspinfo->dobj.dump == DUMP_COMPONENT_NONE)
4536 30 : continue;
4537 :
4538 : /* OK, make a DumpableObject for this relationship */
4539 142 : pubsinfo[j].dobj.objType = DO_PUBLICATION_TABLE_IN_SCHEMA;
4540 142 : pubsinfo[j].dobj.catId.tableoid =
4541 142 : atooid(PQgetvalue(res, i, i_tableoid));
4542 142 : pubsinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4543 142 : AssignDumpId(&pubsinfo[j].dobj);
4544 142 : pubsinfo[j].dobj.namespace = nspinfo->dobj.namespace;
4545 142 : pubsinfo[j].dobj.name = nspinfo->dobj.name;
4546 142 : pubsinfo[j].publication = pubinfo;
4547 142 : pubsinfo[j].pubschema = nspinfo;
4548 :
4549 : /* Decide whether we want to dump it */
4550 142 : selectDumpablePublicationObject(&(pubsinfo[j].dobj), fout);
4551 :
4552 142 : j++;
4553 : }
4554 :
4555 308 : PQclear(res);
4556 308 : destroyPQExpBuffer(query);
4557 : }
4558 :
4559 : /*
4560 : * getPublicationTables
4561 : * get information about publication membership for dumpable tables.
4562 : */
4563 : void
4564 308 : getPublicationTables(Archive *fout, TableInfo tblinfo[], int numTables)
4565 : {
4566 : PQExpBuffer query;
4567 : PGresult *res;
4568 : PublicationRelInfo *pubrinfo;
4569 308 : DumpOptions *dopt = fout->dopt;
4570 : int i_tableoid;
4571 : int i_oid;
4572 : int i_prpubid;
4573 : int i_prrelid;
4574 : int i_prrelqual;
4575 : int i_prattrs;
4576 : int i,
4577 : j,
4578 : ntups;
4579 :
4580 308 : if (dopt->no_publications || fout->remoteVersion < 100000)
4581 0 : return;
4582 :
4583 308 : query = createPQExpBuffer();
4584 :
4585 : /* Collect all publication membership info. */
4586 308 : if (fout->remoteVersion >= 150000)
4587 308 : appendPQExpBufferStr(query,
4588 : "SELECT tableoid, oid, prpubid, prrelid, "
4589 : "pg_catalog.pg_get_expr(prqual, prrelid) AS prrelqual, "
4590 : "(CASE\n"
4591 : " WHEN pr.prattrs IS NOT NULL THEN\n"
4592 : " (SELECT array_agg(attname)\n"
4593 : " FROM\n"
4594 : " pg_catalog.generate_series(0, pg_catalog.array_upper(pr.prattrs::pg_catalog.int2[], 1)) s,\n"
4595 : " pg_catalog.pg_attribute\n"
4596 : " WHERE attrelid = pr.prrelid AND attnum = prattrs[s])\n"
4597 : " ELSE NULL END) prattrs "
4598 : "FROM pg_catalog.pg_publication_rel pr");
4599 : else
4600 0 : appendPQExpBufferStr(query,
4601 : "SELECT tableoid, oid, prpubid, prrelid, "
4602 : "NULL AS prrelqual, NULL AS prattrs "
4603 : "FROM pg_catalog.pg_publication_rel");
4604 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4605 :
4606 308 : ntups = PQntuples(res);
4607 :
4608 308 : i_tableoid = PQfnumber(res, "tableoid");
4609 308 : i_oid = PQfnumber(res, "oid");
4610 308 : i_prpubid = PQfnumber(res, "prpubid");
4611 308 : i_prrelid = PQfnumber(res, "prrelid");
4612 308 : i_prrelqual = PQfnumber(res, "prrelqual");
4613 308 : i_prattrs = PQfnumber(res, "prattrs");
4614 :
4615 : /* this allocation may be more than we need */
4616 308 : pubrinfo = pg_malloc(ntups * sizeof(PublicationRelInfo));
4617 308 : j = 0;
4618 :
4619 910 : for (i = 0; i < ntups; i++)
4620 : {
4621 602 : Oid prpubid = atooid(PQgetvalue(res, i, i_prpubid));
4622 602 : Oid prrelid = atooid(PQgetvalue(res, i, i_prrelid));
4623 : PublicationInfo *pubinfo;
4624 : TableInfo *tbinfo;
4625 :
4626 : /*
4627 : * Ignore any entries for which we aren't interested in either the
4628 : * publication or the rel.
4629 : */
4630 602 : pubinfo = findPublicationByOid(prpubid);
4631 602 : if (pubinfo == NULL)
4632 0 : continue;
4633 602 : tbinfo = findTableByOid(prrelid);
4634 602 : if (tbinfo == NULL)
4635 0 : continue;
4636 :
4637 : /*
4638 : * Ignore publication membership of tables whose definitions are not
4639 : * to be dumped.
4640 : */
4641 602 : if (!(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
4642 92 : continue;
4643 :
4644 : /* OK, make a DumpableObject for this relationship */
4645 510 : pubrinfo[j].dobj.objType = DO_PUBLICATION_REL;
4646 510 : pubrinfo[j].dobj.catId.tableoid =
4647 510 : atooid(PQgetvalue(res, i, i_tableoid));
4648 510 : pubrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4649 510 : AssignDumpId(&pubrinfo[j].dobj);
4650 510 : pubrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
4651 510 : pubrinfo[j].dobj.name = tbinfo->dobj.name;
4652 510 : pubrinfo[j].publication = pubinfo;
4653 510 : pubrinfo[j].pubtable = tbinfo;
4654 510 : if (PQgetisnull(res, i, i_prrelqual))
4655 292 : pubrinfo[j].pubrelqual = NULL;
4656 : else
4657 218 : pubrinfo[j].pubrelqual = pg_strdup(PQgetvalue(res, i, i_prrelqual));
4658 :
4659 510 : if (!PQgetisnull(res, i, i_prattrs))
4660 : {
4661 : char **attnames;
4662 : int nattnames;
4663 : PQExpBuffer attribs;
4664 :
4665 144 : if (!parsePGArray(PQgetvalue(res, i, i_prattrs),
4666 : &attnames, &nattnames))
4667 0 : pg_fatal("could not parse %s array", "prattrs");
4668 144 : attribs = createPQExpBuffer();
4669 432 : for (int k = 0; k < nattnames; k++)
4670 : {
4671 288 : if (k > 0)
4672 144 : appendPQExpBufferStr(attribs, ", ");
4673 :
4674 288 : appendPQExpBufferStr(attribs, fmtId(attnames[k]));
4675 : }
4676 144 : pubrinfo[j].pubrattrs = attribs->data;
4677 : }
4678 : else
4679 366 : pubrinfo[j].pubrattrs = NULL;
4680 :
4681 : /* Decide whether we want to dump it */
4682 510 : selectDumpablePublicationObject(&(pubrinfo[j].dobj), fout);
4683 :
4684 510 : j++;
4685 : }
4686 :
4687 308 : PQclear(res);
4688 308 : destroyPQExpBuffer(query);
4689 : }
4690 :
4691 : /*
4692 : * dumpPublicationNamespace
4693 : * dump the definition of the given publication schema mapping.
4694 : */
4695 : static void
4696 138 : dumpPublicationNamespace(Archive *fout, const PublicationSchemaInfo *pubsinfo)
4697 : {
4698 138 : DumpOptions *dopt = fout->dopt;
4699 138 : NamespaceInfo *schemainfo = pubsinfo->pubschema;
4700 138 : PublicationInfo *pubinfo = pubsinfo->publication;
4701 : PQExpBuffer query;
4702 : char *tag;
4703 :
4704 : /* Do nothing in data-only dump */
4705 138 : if (dopt->dataOnly)
4706 12 : return;
4707 :
4708 126 : tag = psprintf("%s %s", pubinfo->dobj.name, schemainfo->dobj.name);
4709 :
4710 126 : query = createPQExpBuffer();
4711 :
4712 126 : appendPQExpBuffer(query, "ALTER PUBLICATION %s ", fmtId(pubinfo->dobj.name));
4713 126 : appendPQExpBuffer(query, "ADD TABLES IN SCHEMA %s;\n", fmtId(schemainfo->dobj.name));
4714 :
4715 : /*
4716 : * There is no point in creating drop query as the drop is done by schema
4717 : * drop.
4718 : */
4719 126 : if (pubsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4720 126 : ArchiveEntry(fout, pubsinfo->dobj.catId, pubsinfo->dobj.dumpId,
4721 126 : ARCHIVE_OPTS(.tag = tag,
4722 : .namespace = schemainfo->dobj.name,
4723 : .owner = pubinfo->rolname,
4724 : .description = "PUBLICATION TABLES IN SCHEMA",
4725 : .section = SECTION_POST_DATA,
4726 : .createStmt = query->data));
4727 :
4728 : /* These objects can't currently have comments or seclabels */
4729 :
4730 126 : free(tag);
4731 126 : destroyPQExpBuffer(query);
4732 : }
4733 :
4734 : /*
4735 : * dumpPublicationTable
4736 : * dump the definition of the given publication table mapping
4737 : */
4738 : static void
4739 470 : dumpPublicationTable(Archive *fout, const PublicationRelInfo *pubrinfo)
4740 : {
4741 470 : DumpOptions *dopt = fout->dopt;
4742 470 : PublicationInfo *pubinfo = pubrinfo->publication;
4743 470 : TableInfo *tbinfo = pubrinfo->pubtable;
4744 : PQExpBuffer query;
4745 : char *tag;
4746 :
4747 : /* Do nothing in data-only dump */
4748 470 : if (dopt->dataOnly)
4749 42 : return;
4750 :
4751 428 : tag = psprintf("%s %s", pubinfo->dobj.name, tbinfo->dobj.name);
4752 :
4753 428 : query = createPQExpBuffer();
4754 :
4755 428 : appendPQExpBuffer(query, "ALTER PUBLICATION %s ADD TABLE ONLY",
4756 428 : fmtId(pubinfo->dobj.name));
4757 428 : appendPQExpBuffer(query, " %s",
4758 428 : fmtQualifiedDumpable(tbinfo));
4759 :
4760 428 : if (pubrinfo->pubrattrs)
4761 124 : appendPQExpBuffer(query, " (%s)", pubrinfo->pubrattrs);
4762 :
4763 428 : if (pubrinfo->pubrelqual)
4764 : {
4765 : /*
4766 : * It's necessary to add parentheses around the expression because
4767 : * pg_get_expr won't supply the parentheses for things like WHERE
4768 : * TRUE.
4769 : */
4770 184 : appendPQExpBuffer(query, " WHERE (%s)", pubrinfo->pubrelqual);
4771 : }
4772 428 : appendPQExpBufferStr(query, ";\n");
4773 :
4774 : /*
4775 : * There is no point in creating a drop query as the drop is done by table
4776 : * drop. (If you think to change this, see also _printTocEntry().)
4777 : * Although this object doesn't really have ownership as such, set the
4778 : * owner field anyway to ensure that the command is run by the correct
4779 : * role at restore time.
4780 : */
4781 428 : if (pubrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
4782 428 : ArchiveEntry(fout, pubrinfo->dobj.catId, pubrinfo->dobj.dumpId,
4783 428 : ARCHIVE_OPTS(.tag = tag,
4784 : .namespace = tbinfo->dobj.namespace->dobj.name,
4785 : .owner = pubinfo->rolname,
4786 : .description = "PUBLICATION TABLE",
4787 : .section = SECTION_POST_DATA,
4788 : .createStmt = query->data));
4789 :
4790 : /* These objects can't currently have comments or seclabels */
4791 :
4792 428 : free(tag);
4793 428 : destroyPQExpBuffer(query);
4794 : }
4795 :
4796 : /*
4797 : * Is the currently connected user a superuser?
4798 : */
4799 : static bool
4800 308 : is_superuser(Archive *fout)
4801 : {
4802 308 : ArchiveHandle *AH = (ArchiveHandle *) fout;
4803 : const char *val;
4804 :
4805 308 : val = PQparameterStatus(AH->connection, "is_superuser");
4806 :
4807 308 : if (val && strcmp(val, "on") == 0)
4808 302 : return true;
4809 :
4810 6 : return false;
4811 : }
4812 :
4813 : /*
4814 : * Set the given value to restrict_nonsystem_relation_kind value. Since
4815 : * restrict_nonsystem_relation_kind is introduced in minor version releases,
4816 : * the setting query is effective only where available.
4817 : */
4818 : static void
4819 376 : set_restrict_relation_kind(Archive *AH, const char *value)
4820 : {
4821 376 : PQExpBuffer query = createPQExpBuffer();
4822 : PGresult *res;
4823 :
4824 376 : appendPQExpBuffer(query,
4825 : "SELECT set_config(name, '%s', false) "
4826 : "FROM pg_settings "
4827 : "WHERE name = 'restrict_nonsystem_relation_kind'",
4828 : value);
4829 376 : res = ExecuteSqlQuery(AH, query->data, PGRES_TUPLES_OK);
4830 :
4831 376 : PQclear(res);
4832 376 : destroyPQExpBuffer(query);
4833 376 : }
4834 :
4835 : /*
4836 : * getSubscriptions
4837 : * get information about subscriptions
4838 : */
4839 : void
4840 308 : getSubscriptions(Archive *fout)
4841 : {
4842 308 : DumpOptions *dopt = fout->dopt;
4843 : PQExpBuffer query;
4844 : PGresult *res;
4845 : SubscriptionInfo *subinfo;
4846 : int i_tableoid;
4847 : int i_oid;
4848 : int i_subname;
4849 : int i_subowner;
4850 : int i_subbinary;
4851 : int i_substream;
4852 : int i_subtwophasestate;
4853 : int i_subdisableonerr;
4854 : int i_subpasswordrequired;
4855 : int i_subrunasowner;
4856 : int i_subconninfo;
4857 : int i_subslotname;
4858 : int i_subsynccommit;
4859 : int i_subpublications;
4860 : int i_suborigin;
4861 : int i_suboriginremotelsn;
4862 : int i_subenabled;
4863 : int i_subfailover;
4864 : int i,
4865 : ntups;
4866 :
4867 308 : if (dopt->no_subscriptions || fout->remoteVersion < 100000)
4868 0 : return;
4869 :
4870 308 : if (!is_superuser(fout))
4871 : {
4872 : int n;
4873 :
4874 6 : res = ExecuteSqlQuery(fout,
4875 : "SELECT count(*) FROM pg_subscription "
4876 : "WHERE subdbid = (SELECT oid FROM pg_database"
4877 : " WHERE datname = current_database())",
4878 : PGRES_TUPLES_OK);
4879 6 : n = atoi(PQgetvalue(res, 0, 0));
4880 6 : if (n > 0)
4881 4 : pg_log_warning("subscriptions not dumped because current user is not a superuser");
4882 6 : PQclear(res);
4883 6 : return;
4884 : }
4885 :
4886 302 : query = createPQExpBuffer();
4887 :
4888 : /* Get the subscriptions in current database. */
4889 302 : appendPQExpBufferStr(query,
4890 : "SELECT s.tableoid, s.oid, s.subname,\n"
4891 : " s.subowner,\n"
4892 : " s.subconninfo, s.subslotname, s.subsynccommit,\n"
4893 : " s.subpublications,\n");
4894 :
4895 302 : if (fout->remoteVersion >= 140000)
4896 302 : appendPQExpBufferStr(query, " s.subbinary,\n");
4897 : else
4898 0 : appendPQExpBufferStr(query, " false AS subbinary,\n");
4899 :
4900 302 : if (fout->remoteVersion >= 140000)
4901 302 : appendPQExpBufferStr(query, " s.substream,\n");
4902 : else
4903 0 : appendPQExpBufferStr(query, " 'f' AS substream,\n");
4904 :
4905 302 : if (fout->remoteVersion >= 150000)
4906 302 : appendPQExpBufferStr(query,
4907 : " s.subtwophasestate,\n"
4908 : " s.subdisableonerr,\n");
4909 : else
4910 0 : appendPQExpBuffer(query,
4911 : " '%c' AS subtwophasestate,\n"
4912 : " false AS subdisableonerr,\n",
4913 : LOGICALREP_TWOPHASE_STATE_DISABLED);
4914 :
4915 302 : if (fout->remoteVersion >= 160000)
4916 302 : appendPQExpBufferStr(query,
4917 : " s.subpasswordrequired,\n"
4918 : " s.subrunasowner,\n"
4919 : " s.suborigin,\n");
4920 : else
4921 0 : appendPQExpBuffer(query,
4922 : " 't' AS subpasswordrequired,\n"
4923 : " 't' AS subrunasowner,\n"
4924 : " '%s' AS suborigin,\n",
4925 : LOGICALREP_ORIGIN_ANY);
4926 :
4927 302 : if (dopt->binary_upgrade && fout->remoteVersion >= 170000)
4928 28 : appendPQExpBufferStr(query, " o.remote_lsn AS suboriginremotelsn,\n"
4929 : " s.subenabled,\n");
4930 : else
4931 274 : appendPQExpBufferStr(query, " NULL AS suboriginremotelsn,\n"
4932 : " false AS subenabled,\n");
4933 :
4934 302 : if (fout->remoteVersion >= 170000)
4935 302 : appendPQExpBufferStr(query,
4936 : " s.subfailover\n");
4937 : else
4938 0 : appendPQExpBuffer(query,
4939 : " false AS subfailover\n");
4940 :
4941 302 : appendPQExpBufferStr(query,
4942 : "FROM pg_subscription s\n");
4943 :
4944 302 : if (dopt->binary_upgrade && fout->remoteVersion >= 170000)
4945 28 : appendPQExpBufferStr(query,
4946 : "LEFT JOIN pg_catalog.pg_replication_origin_status o \n"
4947 : " ON o.external_id = 'pg_' || s.oid::text \n");
4948 :
4949 302 : appendPQExpBufferStr(query,
4950 : "WHERE s.subdbid = (SELECT oid FROM pg_database\n"
4951 : " WHERE datname = current_database())");
4952 :
4953 302 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
4954 :
4955 302 : ntups = PQntuples(res);
4956 :
4957 : /*
4958 : * Get subscription fields. We don't include subskiplsn in the dump as
4959 : * after restoring the dump this value may no longer be relevant.
4960 : */
4961 302 : i_tableoid = PQfnumber(res, "tableoid");
4962 302 : i_oid = PQfnumber(res, "oid");
4963 302 : i_subname = PQfnumber(res, "subname");
4964 302 : i_subowner = PQfnumber(res, "subowner");
4965 302 : i_subbinary = PQfnumber(res, "subbinary");
4966 302 : i_substream = PQfnumber(res, "substream");
4967 302 : i_subtwophasestate = PQfnumber(res, "subtwophasestate");
4968 302 : i_subdisableonerr = PQfnumber(res, "subdisableonerr");
4969 302 : i_subpasswordrequired = PQfnumber(res, "subpasswordrequired");
4970 302 : i_subrunasowner = PQfnumber(res, "subrunasowner");
4971 302 : i_subconninfo = PQfnumber(res, "subconninfo");
4972 302 : i_subslotname = PQfnumber(res, "subslotname");
4973 302 : i_subsynccommit = PQfnumber(res, "subsynccommit");
4974 302 : i_subpublications = PQfnumber(res, "subpublications");
4975 302 : i_suborigin = PQfnumber(res, "suborigin");
4976 302 : i_suboriginremotelsn = PQfnumber(res, "suboriginremotelsn");
4977 302 : i_subenabled = PQfnumber(res, "subenabled");
4978 302 : i_subfailover = PQfnumber(res, "subfailover");
4979 :
4980 302 : subinfo = pg_malloc(ntups * sizeof(SubscriptionInfo));
4981 :
4982 552 : for (i = 0; i < ntups; i++)
4983 : {
4984 250 : subinfo[i].dobj.objType = DO_SUBSCRIPTION;
4985 250 : subinfo[i].dobj.catId.tableoid =
4986 250 : atooid(PQgetvalue(res, i, i_tableoid));
4987 250 : subinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
4988 250 : AssignDumpId(&subinfo[i].dobj);
4989 250 : subinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_subname));
4990 250 : subinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_subowner));
4991 :
4992 500 : subinfo[i].subbinary =
4993 250 : pg_strdup(PQgetvalue(res, i, i_subbinary));
4994 500 : subinfo[i].substream =
4995 250 : pg_strdup(PQgetvalue(res, i, i_substream));
4996 500 : subinfo[i].subtwophasestate =
4997 250 : pg_strdup(PQgetvalue(res, i, i_subtwophasestate));
4998 500 : subinfo[i].subdisableonerr =
4999 250 : pg_strdup(PQgetvalue(res, i, i_subdisableonerr));
5000 500 : subinfo[i].subpasswordrequired =
5001 250 : pg_strdup(PQgetvalue(res, i, i_subpasswordrequired));
5002 500 : subinfo[i].subrunasowner =
5003 250 : pg_strdup(PQgetvalue(res, i, i_subrunasowner));
5004 500 : subinfo[i].subconninfo =
5005 250 : pg_strdup(PQgetvalue(res, i, i_subconninfo));
5006 250 : if (PQgetisnull(res, i, i_subslotname))
5007 0 : subinfo[i].subslotname = NULL;
5008 : else
5009 250 : subinfo[i].subslotname =
5010 250 : pg_strdup(PQgetvalue(res, i, i_subslotname));
5011 500 : subinfo[i].subsynccommit =
5012 250 : pg_strdup(PQgetvalue(res, i, i_subsynccommit));
5013 500 : subinfo[i].subpublications =
5014 250 : pg_strdup(PQgetvalue(res, i, i_subpublications));
5015 250 : subinfo[i].suborigin = pg_strdup(PQgetvalue(res, i, i_suborigin));
5016 250 : if (PQgetisnull(res, i, i_suboriginremotelsn))
5017 248 : subinfo[i].suboriginremotelsn = NULL;
5018 : else
5019 2 : subinfo[i].suboriginremotelsn =
5020 2 : pg_strdup(PQgetvalue(res, i, i_suboriginremotelsn));
5021 500 : subinfo[i].subenabled =
5022 250 : pg_strdup(PQgetvalue(res, i, i_subenabled));
5023 500 : subinfo[i].subfailover =
5024 250 : pg_strdup(PQgetvalue(res, i, i_subfailover));
5025 :
5026 : /* Decide whether we want to dump it */
5027 250 : selectDumpableObject(&(subinfo[i].dobj), fout);
5028 : }
5029 302 : PQclear(res);
5030 :
5031 302 : destroyPQExpBuffer(query);
5032 : }
5033 :
5034 : /*
5035 : * getSubscriptionTables
5036 : * Get information about subscription membership for dumpable tables. This
5037 : * will be used only in binary-upgrade mode for PG17 or later versions.
5038 : */
5039 : void
5040 308 : getSubscriptionTables(Archive *fout)
5041 : {
5042 308 : DumpOptions *dopt = fout->dopt;
5043 308 : SubscriptionInfo *subinfo = NULL;
5044 : SubRelInfo *subrinfo;
5045 : PGresult *res;
5046 : int i_srsubid;
5047 : int i_srrelid;
5048 : int i_srsubstate;
5049 : int i_srsublsn;
5050 : int ntups;
5051 308 : Oid last_srsubid = InvalidOid;
5052 :
5053 308 : if (dopt->no_subscriptions || !dopt->binary_upgrade ||
5054 28 : fout->remoteVersion < 170000)
5055 280 : return;
5056 :
5057 28 : res = ExecuteSqlQuery(fout,
5058 : "SELECT srsubid, srrelid, srsubstate, srsublsn "
5059 : "FROM pg_catalog.pg_subscription_rel "
5060 : "ORDER BY srsubid",
5061 : PGRES_TUPLES_OK);
5062 28 : ntups = PQntuples(res);
5063 28 : if (ntups == 0)
5064 26 : goto cleanup;
5065 :
5066 : /* Get pg_subscription_rel attributes */
5067 2 : i_srsubid = PQfnumber(res, "srsubid");
5068 2 : i_srrelid = PQfnumber(res, "srrelid");
5069 2 : i_srsubstate = PQfnumber(res, "srsubstate");
5070 2 : i_srsublsn = PQfnumber(res, "srsublsn");
5071 :
5072 2 : subrinfo = pg_malloc(ntups * sizeof(SubRelInfo));
5073 6 : for (int i = 0; i < ntups; i++)
5074 : {
5075 4 : Oid cur_srsubid = atooid(PQgetvalue(res, i, i_srsubid));
5076 4 : Oid relid = atooid(PQgetvalue(res, i, i_srrelid));
5077 : TableInfo *tblinfo;
5078 :
5079 : /*
5080 : * If we switched to a new subscription, check if the subscription
5081 : * exists.
5082 : */
5083 4 : if (cur_srsubid != last_srsubid)
5084 : {
5085 4 : subinfo = findSubscriptionByOid(cur_srsubid);
5086 4 : if (subinfo == NULL)
5087 0 : pg_fatal("subscription with OID %u does not exist", cur_srsubid);
5088 :
5089 4 : last_srsubid = cur_srsubid;
5090 : }
5091 :
5092 4 : tblinfo = findTableByOid(relid);
5093 4 : if (tblinfo == NULL)
5094 0 : pg_fatal("failed sanity check, table with OID %u not found",
5095 : relid);
5096 :
5097 : /* OK, make a DumpableObject for this relationship */
5098 4 : subrinfo[i].dobj.objType = DO_SUBSCRIPTION_REL;
5099 4 : subrinfo[i].dobj.catId.tableoid = relid;
5100 4 : subrinfo[i].dobj.catId.oid = cur_srsubid;
5101 4 : AssignDumpId(&subrinfo[i].dobj);
5102 4 : subrinfo[i].dobj.name = pg_strdup(subinfo->dobj.name);
5103 4 : subrinfo[i].tblinfo = tblinfo;
5104 4 : subrinfo[i].srsubstate = PQgetvalue(res, i, i_srsubstate)[0];
5105 4 : if (PQgetisnull(res, i, i_srsublsn))
5106 2 : subrinfo[i].srsublsn = NULL;
5107 : else
5108 2 : subrinfo[i].srsublsn = pg_strdup(PQgetvalue(res, i, i_srsublsn));
5109 :
5110 4 : subrinfo[i].subinfo = subinfo;
5111 :
5112 : /* Decide whether we want to dump it */
5113 4 : selectDumpableObject(&(subrinfo[i].dobj), fout);
5114 : }
5115 :
5116 2 : cleanup:
5117 28 : PQclear(res);
5118 : }
5119 :
5120 : /*
5121 : * dumpSubscriptionTable
5122 : * Dump the definition of the given subscription table mapping. This will be
5123 : * used only in binary-upgrade mode for PG17 or later versions.
5124 : */
5125 : static void
5126 4 : dumpSubscriptionTable(Archive *fout, const SubRelInfo *subrinfo)
5127 : {
5128 4 : DumpOptions *dopt = fout->dopt;
5129 4 : SubscriptionInfo *subinfo = subrinfo->subinfo;
5130 : PQExpBuffer query;
5131 : char *tag;
5132 :
5133 : /* Do nothing in data-only dump */
5134 4 : if (dopt->dataOnly)
5135 0 : return;
5136 :
5137 : Assert(fout->dopt->binary_upgrade && fout->remoteVersion >= 170000);
5138 :
5139 4 : tag = psprintf("%s %s", subinfo->dobj.name, subrinfo->dobj.name);
5140 :
5141 4 : query = createPQExpBuffer();
5142 :
5143 4 : if (subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
5144 : {
5145 : /*
5146 : * binary_upgrade_add_sub_rel_state will add the subscription relation
5147 : * to pg_subscription_rel table. This will be used only in
5148 : * binary-upgrade mode.
5149 : */
5150 4 : appendPQExpBufferStr(query,
5151 : "\n-- For binary upgrade, must preserve the subscriber table.\n");
5152 4 : appendPQExpBufferStr(query,
5153 : "SELECT pg_catalog.binary_upgrade_add_sub_rel_state(");
5154 4 : appendStringLiteralAH(query, subrinfo->dobj.name, fout);
5155 4 : appendPQExpBuffer(query,
5156 : ", %u, '%c'",
5157 4 : subrinfo->tblinfo->dobj.catId.oid,
5158 4 : subrinfo->srsubstate);
5159 :
5160 4 : if (subrinfo->srsublsn && subrinfo->srsublsn[0] != '\0')
5161 2 : appendPQExpBuffer(query, ", '%s'", subrinfo->srsublsn);
5162 : else
5163 2 : appendPQExpBuffer(query, ", NULL");
5164 :
5165 4 : appendPQExpBufferStr(query, ");\n");
5166 : }
5167 :
5168 : /*
5169 : * There is no point in creating a drop query as the drop is done by table
5170 : * drop. (If you think to change this, see also _printTocEntry().)
5171 : * Although this object doesn't really have ownership as such, set the
5172 : * owner field anyway to ensure that the command is run by the correct
5173 : * role at restore time.
5174 : */
5175 4 : if (subrinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
5176 4 : ArchiveEntry(fout, subrinfo->dobj.catId, subrinfo->dobj.dumpId,
5177 4 : ARCHIVE_OPTS(.tag = tag,
5178 : .namespace = subrinfo->tblinfo->dobj.namespace->dobj.name,
5179 : .owner = subinfo->rolname,
5180 : .description = "SUBSCRIPTION TABLE",
5181 : .section = SECTION_POST_DATA,
5182 : .createStmt = query->data));
5183 :
5184 : /* These objects can't currently have comments or seclabels */
5185 :
5186 4 : free(tag);
5187 4 : destroyPQExpBuffer(query);
5188 : }
5189 :
5190 : /*
5191 : * dumpSubscription
5192 : * dump the definition of the given subscription
5193 : */
5194 : static void
5195 214 : dumpSubscription(Archive *fout, const SubscriptionInfo *subinfo)
5196 : {
5197 214 : DumpOptions *dopt = fout->dopt;
5198 : PQExpBuffer delq;
5199 : PQExpBuffer query;
5200 : PQExpBuffer publications;
5201 : char *qsubname;
5202 214 : char **pubnames = NULL;
5203 214 : int npubnames = 0;
5204 : int i;
5205 214 : char two_phase_disabled[] = {LOGICALREP_TWOPHASE_STATE_DISABLED, '\0'};
5206 :
5207 : /* Do nothing in data-only dump */
5208 214 : if (dopt->dataOnly)
5209 18 : return;
5210 :
5211 196 : delq = createPQExpBuffer();
5212 196 : query = createPQExpBuffer();
5213 :
5214 196 : qsubname = pg_strdup(fmtId(subinfo->dobj.name));
5215 :
5216 196 : appendPQExpBuffer(delq, "DROP SUBSCRIPTION %s;\n",
5217 : qsubname);
5218 :
5219 196 : appendPQExpBuffer(query, "CREATE SUBSCRIPTION %s CONNECTION ",
5220 : qsubname);
5221 196 : appendStringLiteralAH(query, subinfo->subconninfo, fout);
5222 :
5223 : /* Build list of quoted publications and append them to query. */
5224 196 : if (!parsePGArray(subinfo->subpublications, &pubnames, &npubnames))
5225 0 : pg_fatal("could not parse %s array", "subpublications");
5226 :
5227 196 : publications = createPQExpBuffer();
5228 392 : for (i = 0; i < npubnames; i++)
5229 : {
5230 196 : if (i > 0)
5231 0 : appendPQExpBufferStr(publications, ", ");
5232 :
5233 196 : appendPQExpBufferStr(publications, fmtId(pubnames[i]));
5234 : }
5235 :
5236 196 : appendPQExpBuffer(query, " PUBLICATION %s WITH (connect = false, slot_name = ", publications->data);
5237 196 : if (subinfo->subslotname)
5238 196 : appendStringLiteralAH(query, subinfo->subslotname, fout);
5239 : else
5240 0 : appendPQExpBufferStr(query, "NONE");
5241 :
5242 196 : if (strcmp(subinfo->subbinary, "t") == 0)
5243 0 : appendPQExpBufferStr(query, ", binary = true");
5244 :
5245 196 : if (strcmp(subinfo->substream, "t") == 0)
5246 64 : appendPQExpBufferStr(query, ", streaming = on");
5247 132 : else if (strcmp(subinfo->substream, "p") == 0)
5248 68 : appendPQExpBufferStr(query, ", streaming = parallel");
5249 : else
5250 64 : appendPQExpBufferStr(query, ", streaming = off");
5251 :
5252 196 : if (strcmp(subinfo->subtwophasestate, two_phase_disabled) != 0)
5253 0 : appendPQExpBufferStr(query, ", two_phase = on");
5254 :
5255 196 : if (strcmp(subinfo->subdisableonerr, "t") == 0)
5256 0 : appendPQExpBufferStr(query, ", disable_on_error = true");
5257 :
5258 196 : if (strcmp(subinfo->subpasswordrequired, "t") != 0)
5259 0 : appendPQExpBuffer(query, ", password_required = false");
5260 :
5261 196 : if (strcmp(subinfo->subrunasowner, "t") == 0)
5262 0 : appendPQExpBufferStr(query, ", run_as_owner = true");
5263 :
5264 196 : if (strcmp(subinfo->subfailover, "t") == 0)
5265 2 : appendPQExpBufferStr(query, ", failover = true");
5266 :
5267 196 : if (strcmp(subinfo->subsynccommit, "off") != 0)
5268 0 : appendPQExpBuffer(query, ", synchronous_commit = %s", fmtId(subinfo->subsynccommit));
5269 :
5270 196 : if (pg_strcasecmp(subinfo->suborigin, LOGICALREP_ORIGIN_ANY) != 0)
5271 64 : appendPQExpBuffer(query, ", origin = %s", subinfo->suborigin);
5272 :
5273 196 : appendPQExpBufferStr(query, ");\n");
5274 :
5275 : /*
5276 : * In binary-upgrade mode, we allow the replication to continue after the
5277 : * upgrade.
5278 : */
5279 196 : if (dopt->binary_upgrade && fout->remoteVersion >= 170000)
5280 : {
5281 10 : if (subinfo->suboriginremotelsn)
5282 : {
5283 : /*
5284 : * Preserve the remote_lsn for the subscriber's replication
5285 : * origin. This value is required to start the replication from
5286 : * the position before the upgrade. This value will be stale if
5287 : * the publisher gets upgraded before the subscriber node.
5288 : * However, this shouldn't be a problem as the upgrade of the
5289 : * publisher ensures that all the transactions were replicated
5290 : * before upgrading it.
5291 : */
5292 2 : appendPQExpBufferStr(query,
5293 : "\n-- For binary upgrade, must preserve the remote_lsn for the subscriber's replication origin.\n");
5294 2 : appendPQExpBufferStr(query,
5295 : "SELECT pg_catalog.binary_upgrade_replorigin_advance(");
5296 2 : appendStringLiteralAH(query, subinfo->dobj.name, fout);
5297 2 : appendPQExpBuffer(query, ", '%s');\n", subinfo->suboriginremotelsn);
5298 : }
5299 :
5300 10 : if (strcmp(subinfo->subenabled, "t") == 0)
5301 : {
5302 : /*
5303 : * Enable the subscription to allow the replication to continue
5304 : * after the upgrade.
5305 : */
5306 2 : appendPQExpBufferStr(query,
5307 : "\n-- For binary upgrade, must preserve the subscriber's running state.\n");
5308 2 : appendPQExpBuffer(query, "ALTER SUBSCRIPTION %s ENABLE;\n", qsubname);
5309 : }
5310 : }
5311 :
5312 196 : if (subinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
5313 196 : ArchiveEntry(fout, subinfo->dobj.catId, subinfo->dobj.dumpId,
5314 196 : ARCHIVE_OPTS(.tag = subinfo->dobj.name,
5315 : .owner = subinfo->rolname,
5316 : .description = "SUBSCRIPTION",
5317 : .section = SECTION_POST_DATA,
5318 : .createStmt = query->data,
5319 : .dropStmt = delq->data));
5320 :
5321 196 : if (subinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
5322 64 : dumpComment(fout, "SUBSCRIPTION", qsubname,
5323 : NULL, subinfo->rolname,
5324 : subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
5325 :
5326 196 : if (subinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
5327 0 : dumpSecLabel(fout, "SUBSCRIPTION", qsubname,
5328 : NULL, subinfo->rolname,
5329 : subinfo->dobj.catId, 0, subinfo->dobj.dumpId);
5330 :
5331 196 : destroyPQExpBuffer(publications);
5332 196 : free(pubnames);
5333 :
5334 196 : destroyPQExpBuffer(delq);
5335 196 : destroyPQExpBuffer(query);
5336 196 : free(qsubname);
5337 : }
5338 :
5339 : /*
5340 : * Given a "create query", append as many ALTER ... DEPENDS ON EXTENSION as
5341 : * the object needs.
5342 : */
5343 : static void
5344 9746 : append_depends_on_extension(Archive *fout,
5345 : PQExpBuffer create,
5346 : const DumpableObject *dobj,
5347 : const char *catalog,
5348 : const char *keyword,
5349 : const char *objname)
5350 : {
5351 9746 : if (dobj->depends_on_ext)
5352 : {
5353 : char *nm;
5354 : PGresult *res;
5355 : PQExpBuffer query;
5356 : int ntups;
5357 : int i_extname;
5358 : int i;
5359 :
5360 : /* dodge fmtId() non-reentrancy */
5361 84 : nm = pg_strdup(objname);
5362 :
5363 84 : query = createPQExpBuffer();
5364 84 : appendPQExpBuffer(query,
5365 : "SELECT e.extname "
5366 : "FROM pg_catalog.pg_depend d, pg_catalog.pg_extension e "
5367 : "WHERE d.refobjid = e.oid AND classid = '%s'::pg_catalog.regclass "
5368 : "AND objid = '%u'::pg_catalog.oid AND deptype = 'x' "
5369 : "AND refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass",
5370 : catalog,
5371 : dobj->catId.oid);
5372 84 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5373 84 : ntups = PQntuples(res);
5374 84 : i_extname = PQfnumber(res, "extname");
5375 168 : for (i = 0; i < ntups; i++)
5376 : {
5377 84 : appendPQExpBuffer(create, "\nALTER %s %s DEPENDS ON EXTENSION %s;",
5378 : keyword, nm,
5379 84 : fmtId(PQgetvalue(res, i, i_extname)));
5380 : }
5381 :
5382 84 : PQclear(res);
5383 84 : destroyPQExpBuffer(query);
5384 84 : pg_free(nm);
5385 : }
5386 9746 : }
5387 :
5388 : static Oid
5389 0 : get_next_possible_free_pg_type_oid(Archive *fout, PQExpBuffer upgrade_query)
5390 : {
5391 : /*
5392 : * If the old version didn't assign an array type, but the new version
5393 : * does, we must select an unused type OID to assign. This currently only
5394 : * happens for domains, when upgrading pre-v11 to v11 and up.
5395 : *
5396 : * Note: local state here is kind of ugly, but we must have some, since we
5397 : * mustn't choose the same unused OID more than once.
5398 : */
5399 : static Oid next_possible_free_oid = FirstNormalObjectId;
5400 : PGresult *res;
5401 : bool is_dup;
5402 :
5403 : do
5404 : {
5405 0 : ++next_possible_free_oid;
5406 0 : printfPQExpBuffer(upgrade_query,
5407 : "SELECT EXISTS(SELECT 1 "
5408 : "FROM pg_catalog.pg_type "
5409 : "WHERE oid = '%u'::pg_catalog.oid);",
5410 : next_possible_free_oid);
5411 0 : res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
5412 0 : is_dup = (PQgetvalue(res, 0, 0)[0] == 't');
5413 0 : PQclear(res);
5414 0 : } while (is_dup);
5415 :
5416 0 : return next_possible_free_oid;
5417 : }
5418 :
5419 : static void
5420 1658 : binary_upgrade_set_type_oids_by_type_oid(Archive *fout,
5421 : PQExpBuffer upgrade_buffer,
5422 : Oid pg_type_oid,
5423 : bool force_array_type,
5424 : bool include_multirange_type)
5425 : {
5426 1658 : PQExpBuffer upgrade_query = createPQExpBuffer();
5427 : PGresult *res;
5428 : Oid pg_type_array_oid;
5429 : Oid pg_type_multirange_oid;
5430 : Oid pg_type_multirange_array_oid;
5431 : TypeInfo *tinfo;
5432 :
5433 1658 : appendPQExpBufferStr(upgrade_buffer, "\n-- For binary upgrade, must preserve pg_type oid\n");
5434 1658 : appendPQExpBuffer(upgrade_buffer,
5435 : "SELECT pg_catalog.binary_upgrade_set_next_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5436 : pg_type_oid);
5437 :
5438 1658 : tinfo = findTypeByOid(pg_type_oid);
5439 1658 : if (tinfo)
5440 1658 : pg_type_array_oid = tinfo->typarray;
5441 : else
5442 0 : pg_type_array_oid = InvalidOid;
5443 :
5444 1658 : if (!OidIsValid(pg_type_array_oid) && force_array_type)
5445 0 : pg_type_array_oid = get_next_possible_free_pg_type_oid(fout, upgrade_query);
5446 :
5447 1658 : if (OidIsValid(pg_type_array_oid))
5448 : {
5449 1654 : appendPQExpBufferStr(upgrade_buffer,
5450 : "\n-- For binary upgrade, must preserve pg_type array oid\n");
5451 1654 : appendPQExpBuffer(upgrade_buffer,
5452 : "SELECT pg_catalog.binary_upgrade_set_next_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5453 : pg_type_array_oid);
5454 : }
5455 :
5456 : /*
5457 : * Pre-set the multirange type oid and its own array type oid.
5458 : */
5459 1658 : if (include_multirange_type)
5460 : {
5461 12 : if (fout->remoteVersion >= 140000)
5462 : {
5463 12 : printfPQExpBuffer(upgrade_query,
5464 : "SELECT t.oid, t.typarray "
5465 : "FROM pg_catalog.pg_type t "
5466 : "JOIN pg_catalog.pg_range r "
5467 : "ON t.oid = r.rngmultitypid "
5468 : "WHERE r.rngtypid = '%u'::pg_catalog.oid;",
5469 : pg_type_oid);
5470 :
5471 12 : res = ExecuteSqlQueryForSingleRow(fout, upgrade_query->data);
5472 :
5473 12 : pg_type_multirange_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "oid")));
5474 12 : pg_type_multirange_array_oid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typarray")));
5475 :
5476 12 : PQclear(res);
5477 : }
5478 : else
5479 : {
5480 0 : pg_type_multirange_oid = get_next_possible_free_pg_type_oid(fout, upgrade_query);
5481 0 : pg_type_multirange_array_oid = get_next_possible_free_pg_type_oid(fout, upgrade_query);
5482 : }
5483 :
5484 12 : appendPQExpBufferStr(upgrade_buffer,
5485 : "\n-- For binary upgrade, must preserve multirange pg_type oid\n");
5486 12 : appendPQExpBuffer(upgrade_buffer,
5487 : "SELECT pg_catalog.binary_upgrade_set_next_multirange_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5488 : pg_type_multirange_oid);
5489 12 : appendPQExpBufferStr(upgrade_buffer,
5490 : "\n-- For binary upgrade, must preserve multirange pg_type array oid\n");
5491 12 : appendPQExpBuffer(upgrade_buffer,
5492 : "SELECT pg_catalog.binary_upgrade_set_next_multirange_array_pg_type_oid('%u'::pg_catalog.oid);\n\n",
5493 : pg_type_multirange_array_oid);
5494 : }
5495 :
5496 1658 : destroyPQExpBuffer(upgrade_query);
5497 1658 : }
5498 :
5499 : static void
5500 1522 : binary_upgrade_set_type_oids_by_rel(Archive *fout,
5501 : PQExpBuffer upgrade_buffer,
5502 : const TableInfo *tbinfo)
5503 : {
5504 1522 : Oid pg_type_oid = tbinfo->reltype;
5505 :
5506 1522 : if (OidIsValid(pg_type_oid))
5507 1522 : binary_upgrade_set_type_oids_by_type_oid(fout, upgrade_buffer,
5508 : pg_type_oid, false, false);
5509 1522 : }
5510 :
5511 : /*
5512 : * bsearch() comparator for BinaryUpgradeClassOidItem
5513 : */
5514 : static int
5515 21774 : BinaryUpgradeClassOidItemCmp(const void *p1, const void *p2)
5516 : {
5517 21774 : BinaryUpgradeClassOidItem v1 = *((const BinaryUpgradeClassOidItem *) p1);
5518 21774 : BinaryUpgradeClassOidItem v2 = *((const BinaryUpgradeClassOidItem *) p2);
5519 :
5520 21774 : return pg_cmp_u32(v1.oid, v2.oid);
5521 : }
5522 :
5523 : /*
5524 : * collectBinaryUpgradeClassOids
5525 : *
5526 : * Construct a table of pg_class information required for
5527 : * binary_upgrade_set_pg_class_oids(). The table is sorted by OID for speed in
5528 : * lookup.
5529 : */
5530 : static void
5531 28 : collectBinaryUpgradeClassOids(Archive *fout)
5532 : {
5533 : PGresult *res;
5534 : const char *query;
5535 :
5536 28 : query = "SELECT c.oid, c.relkind, c.relfilenode, c.reltoastrelid, "
5537 : "ct.relfilenode, i.indexrelid, cti.relfilenode "
5538 : "FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_index i "
5539 : "ON (c.reltoastrelid = i.indrelid AND i.indisvalid) "
5540 : "LEFT JOIN pg_catalog.pg_class ct ON (c.reltoastrelid = ct.oid) "
5541 : "LEFT JOIN pg_catalog.pg_class AS cti ON (i.indexrelid = cti.oid) "
5542 : "ORDER BY c.oid;";
5543 :
5544 28 : res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
5545 :
5546 28 : nbinaryUpgradeClassOids = PQntuples(res);
5547 28 : binaryUpgradeClassOids = (BinaryUpgradeClassOidItem *)
5548 28 : pg_malloc(nbinaryUpgradeClassOids * sizeof(BinaryUpgradeClassOidItem));
5549 :
5550 14964 : for (int i = 0; i < nbinaryUpgradeClassOids; i++)
5551 : {
5552 14936 : binaryUpgradeClassOids[i].oid = atooid(PQgetvalue(res, i, 0));
5553 14936 : binaryUpgradeClassOids[i].relkind = *PQgetvalue(res, i, 1);
5554 14936 : binaryUpgradeClassOids[i].relfilenumber = atooid(PQgetvalue(res, i, 2));
5555 14936 : binaryUpgradeClassOids[i].toast_oid = atooid(PQgetvalue(res, i, 3));
5556 14936 : binaryUpgradeClassOids[i].toast_relfilenumber = atooid(PQgetvalue(res, i, 4));
5557 14936 : binaryUpgradeClassOids[i].toast_index_oid = atooid(PQgetvalue(res, i, 5));
5558 14936 : binaryUpgradeClassOids[i].toast_index_relfilenumber = atooid(PQgetvalue(res, i, 6));
5559 : }
5560 :
5561 28 : PQclear(res);
5562 28 : }
5563 :
5564 : static void
5565 2220 : binary_upgrade_set_pg_class_oids(Archive *fout,
5566 : PQExpBuffer upgrade_buffer, Oid pg_class_oid)
5567 : {
5568 2220 : BinaryUpgradeClassOidItem key = {0};
5569 : BinaryUpgradeClassOidItem *entry;
5570 :
5571 : Assert(binaryUpgradeClassOids);
5572 :
5573 : /*
5574 : * Preserve the OID and relfilenumber of the table, table's index, table's
5575 : * toast table and toast table's index if any.
5576 : *
5577 : * One complexity is that the current table definition might not require
5578 : * the creation of a TOAST table, but the old database might have a TOAST
5579 : * table that was created earlier, before some wide columns were dropped.
5580 : * By setting the TOAST oid we force creation of the TOAST heap and index
5581 : * by the new backend, so we can copy the files during binary upgrade
5582 : * without worrying about this case.
5583 : */
5584 2220 : key.oid = pg_class_oid;
5585 2220 : entry = bsearch(&key, binaryUpgradeClassOids, nbinaryUpgradeClassOids,
5586 : sizeof(BinaryUpgradeClassOidItem),
5587 : BinaryUpgradeClassOidItemCmp);
5588 :
5589 2220 : appendPQExpBufferStr(upgrade_buffer,
5590 : "\n-- For binary upgrade, must preserve pg_class oids and relfilenodes\n");
5591 :
5592 2220 : if (entry->relkind != RELKIND_INDEX &&
5593 1720 : entry->relkind != RELKIND_PARTITIONED_INDEX)
5594 : {
5595 1670 : appendPQExpBuffer(upgrade_buffer,
5596 : "SELECT pg_catalog.binary_upgrade_set_next_heap_pg_class_oid('%u'::pg_catalog.oid);\n",
5597 : pg_class_oid);
5598 :
5599 : /*
5600 : * Not every relation has storage. Also, in a pre-v12 database,
5601 : * partitioned tables have a relfilenumber, which should not be
5602 : * preserved when upgrading.
5603 : */
5604 1670 : if (RelFileNumberIsValid(entry->relfilenumber) &&
5605 1362 : entry->relkind != RELKIND_PARTITIONED_TABLE)
5606 1362 : appendPQExpBuffer(upgrade_buffer,
5607 : "SELECT pg_catalog.binary_upgrade_set_next_heap_relfilenode('%u'::pg_catalog.oid);\n",
5608 : entry->relfilenumber);
5609 :
5610 : /*
5611 : * In a pre-v12 database, partitioned tables might be marked as having
5612 : * toast tables, but we should ignore them if so.
5613 : */
5614 1670 : if (OidIsValid(entry->toast_oid) &&
5615 548 : entry->relkind != RELKIND_PARTITIONED_TABLE)
5616 : {
5617 548 : appendPQExpBuffer(upgrade_buffer,
5618 : "SELECT pg_catalog.binary_upgrade_set_next_toast_pg_class_oid('%u'::pg_catalog.oid);\n",
5619 : entry->toast_oid);
5620 548 : appendPQExpBuffer(upgrade_buffer,
5621 : "SELECT pg_catalog.binary_upgrade_set_next_toast_relfilenode('%u'::pg_catalog.oid);\n",
5622 : entry->toast_relfilenumber);
5623 :
5624 : /* every toast table has an index */
5625 548 : appendPQExpBuffer(upgrade_buffer,
5626 : "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
5627 : entry->toast_index_oid);
5628 548 : appendPQExpBuffer(upgrade_buffer,
5629 : "SELECT pg_catalog.binary_upgrade_set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
5630 : entry->toast_index_relfilenumber);
5631 : }
5632 : }
5633 : else
5634 : {
5635 : /* Preserve the OID and relfilenumber of the index */
5636 550 : appendPQExpBuffer(upgrade_buffer,
5637 : "SELECT pg_catalog.binary_upgrade_set_next_index_pg_class_oid('%u'::pg_catalog.oid);\n",
5638 : pg_class_oid);
5639 550 : appendPQExpBuffer(upgrade_buffer,
5640 : "SELECT pg_catalog.binary_upgrade_set_next_index_relfilenode('%u'::pg_catalog.oid);\n",
5641 : entry->relfilenumber);
5642 : }
5643 :
5644 2220 : appendPQExpBufferChar(upgrade_buffer, '\n');
5645 2220 : }
5646 :
5647 : /*
5648 : * If the DumpableObject is a member of an extension, add a suitable
5649 : * ALTER EXTENSION ADD command to the creation commands in upgrade_buffer.
5650 : *
5651 : * For somewhat historical reasons, objname should already be quoted,
5652 : * but not objnamespace (if any).
5653 : */
5654 : static void
5655 2644 : binary_upgrade_extension_member(PQExpBuffer upgrade_buffer,
5656 : const DumpableObject *dobj,
5657 : const char *objtype,
5658 : const char *objname,
5659 : const char *objnamespace)
5660 : {
5661 2644 : DumpableObject *extobj = NULL;
5662 : int i;
5663 :
5664 2644 : if (!dobj->ext_member)
5665 2612 : return;
5666 :
5667 : /*
5668 : * Find the parent extension. We could avoid this search if we wanted to
5669 : * add a link field to DumpableObject, but the space costs of that would
5670 : * be considerable. We assume that member objects could only have a
5671 : * direct dependency on their own extension, not any others.
5672 : */
5673 32 : for (i = 0; i < dobj->nDeps; i++)
5674 : {
5675 32 : extobj = findObjectByDumpId(dobj->dependencies[i]);
5676 32 : if (extobj && extobj->objType == DO_EXTENSION)
5677 32 : break;
5678 0 : extobj = NULL;
5679 : }
5680 32 : if (extobj == NULL)
5681 0 : pg_fatal("could not find parent extension for %s %s",
5682 : objtype, objname);
5683 :
5684 32 : appendPQExpBufferStr(upgrade_buffer,
5685 : "\n-- For binary upgrade, handle extension membership the hard way\n");
5686 32 : appendPQExpBuffer(upgrade_buffer, "ALTER EXTENSION %s ADD %s ",
5687 32 : fmtId(extobj->name),
5688 : objtype);
5689 32 : if (objnamespace && *objnamespace)
5690 26 : appendPQExpBuffer(upgrade_buffer, "%s.", fmtId(objnamespace));
5691 32 : appendPQExpBuffer(upgrade_buffer, "%s;\n", objname);
5692 : }
5693 :
5694 : /*
5695 : * getNamespaces:
5696 : * get information about all namespaces in the system catalogs
5697 : */
5698 : void
5699 310 : getNamespaces(Archive *fout)
5700 : {
5701 : PGresult *res;
5702 : int ntups;
5703 : int i;
5704 : PQExpBuffer query;
5705 : NamespaceInfo *nsinfo;
5706 : int i_tableoid;
5707 : int i_oid;
5708 : int i_nspname;
5709 : int i_nspowner;
5710 : int i_nspacl;
5711 : int i_acldefault;
5712 :
5713 310 : query = createPQExpBuffer();
5714 :
5715 : /*
5716 : * we fetch all namespaces including system ones, so that every object we
5717 : * read in can be linked to a containing namespace.
5718 : */
5719 310 : appendPQExpBufferStr(query, "SELECT n.tableoid, n.oid, n.nspname, "
5720 : "n.nspowner, "
5721 : "n.nspacl, "
5722 : "acldefault('n', n.nspowner) AS acldefault "
5723 : "FROM pg_namespace n");
5724 :
5725 310 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5726 :
5727 310 : ntups = PQntuples(res);
5728 :
5729 310 : nsinfo = (NamespaceInfo *) pg_malloc(ntups * sizeof(NamespaceInfo));
5730 :
5731 310 : i_tableoid = PQfnumber(res, "tableoid");
5732 310 : i_oid = PQfnumber(res, "oid");
5733 310 : i_nspname = PQfnumber(res, "nspname");
5734 310 : i_nspowner = PQfnumber(res, "nspowner");
5735 310 : i_nspacl = PQfnumber(res, "nspacl");
5736 310 : i_acldefault = PQfnumber(res, "acldefault");
5737 :
5738 2844 : for (i = 0; i < ntups; i++)
5739 : {
5740 : const char *nspowner;
5741 :
5742 2534 : nsinfo[i].dobj.objType = DO_NAMESPACE;
5743 2534 : nsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5744 2534 : nsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5745 2534 : AssignDumpId(&nsinfo[i].dobj);
5746 2534 : nsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_nspname));
5747 2534 : nsinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_nspacl));
5748 2534 : nsinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
5749 2534 : nsinfo[i].dacl.privtype = 0;
5750 2534 : nsinfo[i].dacl.initprivs = NULL;
5751 2534 : nspowner = PQgetvalue(res, i, i_nspowner);
5752 2534 : nsinfo[i].nspowner = atooid(nspowner);
5753 2534 : nsinfo[i].rolname = getRoleName(nspowner);
5754 :
5755 : /* Decide whether to dump this namespace */
5756 2534 : selectDumpableNamespace(&nsinfo[i], fout);
5757 :
5758 : /* Mark whether namespace has an ACL */
5759 2534 : if (!PQgetisnull(res, i, i_nspacl))
5760 1036 : nsinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
5761 :
5762 : /*
5763 : * We ignore any pg_init_privs.initprivs entry for the public schema
5764 : * and assume a predetermined default, for several reasons. First,
5765 : * dropping and recreating the schema removes its pg_init_privs entry,
5766 : * but an empty destination database starts with this ACL nonetheless.
5767 : * Second, we support dump/reload of public schema ownership changes.
5768 : * ALTER SCHEMA OWNER filters nspacl through aclnewowner(), but
5769 : * initprivs continues to reflect the initial owner. Hence,
5770 : * synthesize the value that nspacl will have after the restore's
5771 : * ALTER SCHEMA OWNER. Third, this makes the destination database
5772 : * match the source's ACL, even if the latter was an initdb-default
5773 : * ACL, which changed in v15. An upgrade pulls in changes to most
5774 : * system object ACLs that the DBA had not customized. We've made the
5775 : * public schema depart from that, because changing its ACL so easily
5776 : * breaks applications.
5777 : */
5778 2534 : if (strcmp(nsinfo[i].dobj.name, "public") == 0)
5779 : {
5780 302 : PQExpBuffer aclarray = createPQExpBuffer();
5781 302 : PQExpBuffer aclitem = createPQExpBuffer();
5782 :
5783 : /* Standard ACL as of v15 is {owner=UC/owner,=U/owner} */
5784 302 : appendPQExpBufferChar(aclarray, '{');
5785 302 : quoteAclUserName(aclitem, nsinfo[i].rolname);
5786 302 : appendPQExpBufferStr(aclitem, "=UC/");
5787 302 : quoteAclUserName(aclitem, nsinfo[i].rolname);
5788 302 : appendPGArray(aclarray, aclitem->data);
5789 302 : resetPQExpBuffer(aclitem);
5790 302 : appendPQExpBufferStr(aclitem, "=U/");
5791 302 : quoteAclUserName(aclitem, nsinfo[i].rolname);
5792 302 : appendPGArray(aclarray, aclitem->data);
5793 302 : appendPQExpBufferChar(aclarray, '}');
5794 :
5795 302 : nsinfo[i].dacl.privtype = 'i';
5796 302 : nsinfo[i].dacl.initprivs = pstrdup(aclarray->data);
5797 302 : nsinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
5798 :
5799 302 : destroyPQExpBuffer(aclarray);
5800 302 : destroyPQExpBuffer(aclitem);
5801 : }
5802 : }
5803 :
5804 310 : PQclear(res);
5805 310 : destroyPQExpBuffer(query);
5806 310 : }
5807 :
5808 : /*
5809 : * findNamespace:
5810 : * given a namespace OID, look up the info read by getNamespaces
5811 : */
5812 : static NamespaceInfo *
5813 963484 : findNamespace(Oid nsoid)
5814 : {
5815 : NamespaceInfo *nsinfo;
5816 :
5817 963484 : nsinfo = findNamespaceByOid(nsoid);
5818 963484 : if (nsinfo == NULL)
5819 0 : pg_fatal("schema with OID %u does not exist", nsoid);
5820 963484 : return nsinfo;
5821 : }
5822 :
5823 : /*
5824 : * getExtensions:
5825 : * read all extensions in the system catalogs and return them in the
5826 : * ExtensionInfo* structure
5827 : *
5828 : * numExtensions is set to the number of extensions read in
5829 : */
5830 : ExtensionInfo *
5831 310 : getExtensions(Archive *fout, int *numExtensions)
5832 : {
5833 310 : DumpOptions *dopt = fout->dopt;
5834 : PGresult *res;
5835 : int ntups;
5836 : int i;
5837 : PQExpBuffer query;
5838 310 : ExtensionInfo *extinfo = NULL;
5839 : int i_tableoid;
5840 : int i_oid;
5841 : int i_extname;
5842 : int i_nspname;
5843 : int i_extrelocatable;
5844 : int i_extversion;
5845 : int i_extconfig;
5846 : int i_extcondition;
5847 :
5848 310 : query = createPQExpBuffer();
5849 :
5850 310 : appendPQExpBufferStr(query, "SELECT x.tableoid, x.oid, "
5851 : "x.extname, n.nspname, x.extrelocatable, x.extversion, x.extconfig, x.extcondition "
5852 : "FROM pg_extension x "
5853 : "JOIN pg_namespace n ON n.oid = x.extnamespace");
5854 :
5855 310 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5856 :
5857 310 : ntups = PQntuples(res);
5858 310 : if (ntups == 0)
5859 0 : goto cleanup;
5860 :
5861 310 : extinfo = (ExtensionInfo *) pg_malloc(ntups * sizeof(ExtensionInfo));
5862 :
5863 310 : i_tableoid = PQfnumber(res, "tableoid");
5864 310 : i_oid = PQfnumber(res, "oid");
5865 310 : i_extname = PQfnumber(res, "extname");
5866 310 : i_nspname = PQfnumber(res, "nspname");
5867 310 : i_extrelocatable = PQfnumber(res, "extrelocatable");
5868 310 : i_extversion = PQfnumber(res, "extversion");
5869 310 : i_extconfig = PQfnumber(res, "extconfig");
5870 310 : i_extcondition = PQfnumber(res, "extcondition");
5871 :
5872 670 : for (i = 0; i < ntups; i++)
5873 : {
5874 360 : extinfo[i].dobj.objType = DO_EXTENSION;
5875 360 : extinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5876 360 : extinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5877 360 : AssignDumpId(&extinfo[i].dobj);
5878 360 : extinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_extname));
5879 360 : extinfo[i].namespace = pg_strdup(PQgetvalue(res, i, i_nspname));
5880 360 : extinfo[i].relocatable = *(PQgetvalue(res, i, i_extrelocatable)) == 't';
5881 360 : extinfo[i].extversion = pg_strdup(PQgetvalue(res, i, i_extversion));
5882 360 : extinfo[i].extconfig = pg_strdup(PQgetvalue(res, i, i_extconfig));
5883 360 : extinfo[i].extcondition = pg_strdup(PQgetvalue(res, i, i_extcondition));
5884 :
5885 : /* Decide whether we want to dump it */
5886 360 : selectDumpableExtension(&(extinfo[i]), dopt);
5887 : }
5888 :
5889 310 : cleanup:
5890 310 : PQclear(res);
5891 310 : destroyPQExpBuffer(query);
5892 :
5893 310 : *numExtensions = ntups;
5894 :
5895 310 : return extinfo;
5896 : }
5897 :
5898 : /*
5899 : * getTypes:
5900 : * get information about all types in the system catalogs
5901 : *
5902 : * NB: this must run after getFuncs() because we assume we can do
5903 : * findFuncByOid().
5904 : */
5905 : void
5906 308 : getTypes(Archive *fout)
5907 : {
5908 : PGresult *res;
5909 : int ntups;
5910 : int i;
5911 308 : PQExpBuffer query = createPQExpBuffer();
5912 : TypeInfo *tyinfo;
5913 : ShellTypeInfo *stinfo;
5914 : int i_tableoid;
5915 : int i_oid;
5916 : int i_typname;
5917 : int i_typnamespace;
5918 : int i_typacl;
5919 : int i_acldefault;
5920 : int i_typowner;
5921 : int i_typelem;
5922 : int i_typrelid;
5923 : int i_typrelkind;
5924 : int i_typtype;
5925 : int i_typisdefined;
5926 : int i_isarray;
5927 : int i_typarray;
5928 :
5929 : /*
5930 : * we include even the built-in types because those may be used as array
5931 : * elements by user-defined types
5932 : *
5933 : * we filter out the built-in types when we dump out the types
5934 : *
5935 : * same approach for undefined (shell) types and array types
5936 : *
5937 : * Note: as of 8.3 we can reliably detect whether a type is an
5938 : * auto-generated array type by checking the element type's typarray.
5939 : * (Before that the test is capable of generating false positives.) We
5940 : * still check for name beginning with '_', though, so as to avoid the
5941 : * cost of the subselect probe for all standard types. This would have to
5942 : * be revisited if the backend ever allows renaming of array types.
5943 : */
5944 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, typname, "
5945 : "typnamespace, typacl, "
5946 : "acldefault('T', typowner) AS acldefault, "
5947 : "typowner, "
5948 : "typelem, typrelid, typarray, "
5949 : "CASE WHEN typrelid = 0 THEN ' '::\"char\" "
5950 : "ELSE (SELECT relkind FROM pg_class WHERE oid = typrelid) END AS typrelkind, "
5951 : "typtype, typisdefined, "
5952 : "typname[0] = '_' AND typelem != 0 AND "
5953 : "(SELECT typarray FROM pg_type te WHERE oid = pg_type.typelem) = oid AS isarray "
5954 : "FROM pg_type");
5955 :
5956 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
5957 :
5958 308 : ntups = PQntuples(res);
5959 :
5960 308 : tyinfo = (TypeInfo *) pg_malloc(ntups * sizeof(TypeInfo));
5961 :
5962 308 : i_tableoid = PQfnumber(res, "tableoid");
5963 308 : i_oid = PQfnumber(res, "oid");
5964 308 : i_typname = PQfnumber(res, "typname");
5965 308 : i_typnamespace = PQfnumber(res, "typnamespace");
5966 308 : i_typacl = PQfnumber(res, "typacl");
5967 308 : i_acldefault = PQfnumber(res, "acldefault");
5968 308 : i_typowner = PQfnumber(res, "typowner");
5969 308 : i_typelem = PQfnumber(res, "typelem");
5970 308 : i_typrelid = PQfnumber(res, "typrelid");
5971 308 : i_typrelkind = PQfnumber(res, "typrelkind");
5972 308 : i_typtype = PQfnumber(res, "typtype");
5973 308 : i_typisdefined = PQfnumber(res, "typisdefined");
5974 308 : i_isarray = PQfnumber(res, "isarray");
5975 308 : i_typarray = PQfnumber(res, "typarray");
5976 :
5977 222220 : for (i = 0; i < ntups; i++)
5978 : {
5979 221912 : tyinfo[i].dobj.objType = DO_TYPE;
5980 221912 : tyinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
5981 221912 : tyinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
5982 221912 : AssignDumpId(&tyinfo[i].dobj);
5983 221912 : tyinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_typname));
5984 443824 : tyinfo[i].dobj.namespace =
5985 221912 : findNamespace(atooid(PQgetvalue(res, i, i_typnamespace)));
5986 221912 : tyinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_typacl));
5987 221912 : tyinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
5988 221912 : tyinfo[i].dacl.privtype = 0;
5989 221912 : tyinfo[i].dacl.initprivs = NULL;
5990 221912 : tyinfo[i].ftypname = NULL; /* may get filled later */
5991 221912 : tyinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_typowner));
5992 221912 : tyinfo[i].typelem = atooid(PQgetvalue(res, i, i_typelem));
5993 221912 : tyinfo[i].typrelid = atooid(PQgetvalue(res, i, i_typrelid));
5994 221912 : tyinfo[i].typrelkind = *PQgetvalue(res, i, i_typrelkind);
5995 221912 : tyinfo[i].typtype = *PQgetvalue(res, i, i_typtype);
5996 221912 : tyinfo[i].shellType = NULL;
5997 :
5998 221912 : if (strcmp(PQgetvalue(res, i, i_typisdefined), "t") == 0)
5999 221812 : tyinfo[i].isDefined = true;
6000 : else
6001 100 : tyinfo[i].isDefined = false;
6002 :
6003 221912 : if (strcmp(PQgetvalue(res, i, i_isarray), "t") == 0)
6004 106440 : tyinfo[i].isArray = true;
6005 : else
6006 115472 : tyinfo[i].isArray = false;
6007 :
6008 221912 : tyinfo[i].typarray = atooid(PQgetvalue(res, i, i_typarray));
6009 :
6010 221912 : if (tyinfo[i].typtype == TYPTYPE_MULTIRANGE)
6011 2076 : tyinfo[i].isMultirange = true;
6012 : else
6013 219836 : tyinfo[i].isMultirange = false;
6014 :
6015 : /* Decide whether we want to dump it */
6016 221912 : selectDumpableType(&tyinfo[i], fout);
6017 :
6018 : /* Mark whether type has an ACL */
6019 221912 : if (!PQgetisnull(res, i, i_typacl))
6020 394 : tyinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
6021 :
6022 : /*
6023 : * If it's a domain, fetch info about its constraints, if any
6024 : */
6025 221912 : tyinfo[i].nDomChecks = 0;
6026 221912 : tyinfo[i].domChecks = NULL;
6027 221912 : if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6028 26330 : tyinfo[i].typtype == TYPTYPE_DOMAIN)
6029 272 : getDomainConstraints(fout, &(tyinfo[i]));
6030 :
6031 : /*
6032 : * If it's a base type, make a DumpableObject representing a shell
6033 : * definition of the type. We will need to dump that ahead of the I/O
6034 : * functions for the type. Similarly, range types need a shell
6035 : * definition in case they have a canonicalize function.
6036 : *
6037 : * Note: the shell type doesn't have a catId. You might think it
6038 : * should copy the base type's catId, but then it might capture the
6039 : * pg_depend entries for the type, which we don't want.
6040 : */
6041 221912 : if ((tyinfo[i].dobj.dump & DUMP_COMPONENT_DEFINITION) &&
6042 26330 : (tyinfo[i].typtype == TYPTYPE_BASE ||
6043 12746 : tyinfo[i].typtype == TYPTYPE_RANGE))
6044 : {
6045 13804 : stinfo = (ShellTypeInfo *) pg_malloc(sizeof(ShellTypeInfo));
6046 13804 : stinfo->dobj.objType = DO_SHELL_TYPE;
6047 13804 : stinfo->dobj.catId = nilCatalogId;
6048 13804 : AssignDumpId(&stinfo->dobj);
6049 13804 : stinfo->dobj.name = pg_strdup(tyinfo[i].dobj.name);
6050 13804 : stinfo->dobj.namespace = tyinfo[i].dobj.namespace;
6051 13804 : stinfo->baseType = &(tyinfo[i]);
6052 13804 : tyinfo[i].shellType = stinfo;
6053 :
6054 : /*
6055 : * Initially mark the shell type as not to be dumped. We'll only
6056 : * dump it if the I/O or canonicalize functions need to be dumped;
6057 : * this is taken care of while sorting dependencies.
6058 : */
6059 13804 : stinfo->dobj.dump = DUMP_COMPONENT_NONE;
6060 : }
6061 : }
6062 :
6063 308 : PQclear(res);
6064 :
6065 308 : destroyPQExpBuffer(query);
6066 308 : }
6067 :
6068 : /*
6069 : * getOperators:
6070 : * get information about all operators in the system catalogs
6071 : */
6072 : void
6073 308 : getOperators(Archive *fout)
6074 : {
6075 : PGresult *res;
6076 : int ntups;
6077 : int i;
6078 308 : PQExpBuffer query = createPQExpBuffer();
6079 : OprInfo *oprinfo;
6080 : int i_tableoid;
6081 : int i_oid;
6082 : int i_oprname;
6083 : int i_oprnamespace;
6084 : int i_oprowner;
6085 : int i_oprkind;
6086 : int i_oprcode;
6087 :
6088 : /*
6089 : * find all operators, including builtin operators; we filter out
6090 : * system-defined operators at dump-out time.
6091 : */
6092 :
6093 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, oprname, "
6094 : "oprnamespace, "
6095 : "oprowner, "
6096 : "oprkind, "
6097 : "oprcode::oid AS oprcode "
6098 : "FROM pg_operator");
6099 :
6100 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6101 :
6102 308 : ntups = PQntuples(res);
6103 :
6104 308 : oprinfo = (OprInfo *) pg_malloc(ntups * sizeof(OprInfo));
6105 :
6106 308 : i_tableoid = PQfnumber(res, "tableoid");
6107 308 : i_oid = PQfnumber(res, "oid");
6108 308 : i_oprname = PQfnumber(res, "oprname");
6109 308 : i_oprnamespace = PQfnumber(res, "oprnamespace");
6110 308 : i_oprowner = PQfnumber(res, "oprowner");
6111 308 : i_oprkind = PQfnumber(res, "oprkind");
6112 308 : i_oprcode = PQfnumber(res, "oprcode");
6113 :
6114 246680 : for (i = 0; i < ntups; i++)
6115 : {
6116 246372 : oprinfo[i].dobj.objType = DO_OPERATOR;
6117 246372 : oprinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6118 246372 : oprinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6119 246372 : AssignDumpId(&oprinfo[i].dobj);
6120 246372 : oprinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_oprname));
6121 492744 : oprinfo[i].dobj.namespace =
6122 246372 : findNamespace(atooid(PQgetvalue(res, i, i_oprnamespace)));
6123 246372 : oprinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_oprowner));
6124 246372 : oprinfo[i].oprkind = (PQgetvalue(res, i, i_oprkind))[0];
6125 246372 : oprinfo[i].oprcode = atooid(PQgetvalue(res, i, i_oprcode));
6126 :
6127 : /* Decide whether we want to dump it */
6128 246372 : selectDumpableObject(&(oprinfo[i].dobj), fout);
6129 : }
6130 :
6131 308 : PQclear(res);
6132 :
6133 308 : destroyPQExpBuffer(query);
6134 308 : }
6135 :
6136 : /*
6137 : * getCollations:
6138 : * get information about all collations in the system catalogs
6139 : */
6140 : void
6141 308 : getCollations(Archive *fout)
6142 : {
6143 : PGresult *res;
6144 : int ntups;
6145 : int i;
6146 : PQExpBuffer query;
6147 : CollInfo *collinfo;
6148 : int i_tableoid;
6149 : int i_oid;
6150 : int i_collname;
6151 : int i_collnamespace;
6152 : int i_collowner;
6153 :
6154 308 : query = createPQExpBuffer();
6155 :
6156 : /*
6157 : * find all collations, including builtin collations; we filter out
6158 : * system-defined collations at dump-out time.
6159 : */
6160 :
6161 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, collname, "
6162 : "collnamespace, "
6163 : "collowner "
6164 : "FROM pg_collation");
6165 :
6166 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6167 :
6168 308 : ntups = PQntuples(res);
6169 :
6170 308 : collinfo = (CollInfo *) pg_malloc(ntups * sizeof(CollInfo));
6171 :
6172 308 : i_tableoid = PQfnumber(res, "tableoid");
6173 308 : i_oid = PQfnumber(res, "oid");
6174 308 : i_collname = PQfnumber(res, "collname");
6175 308 : i_collnamespace = PQfnumber(res, "collnamespace");
6176 308 : i_collowner = PQfnumber(res, "collowner");
6177 :
6178 244444 : for (i = 0; i < ntups; i++)
6179 : {
6180 244136 : collinfo[i].dobj.objType = DO_COLLATION;
6181 244136 : collinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6182 244136 : collinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6183 244136 : AssignDumpId(&collinfo[i].dobj);
6184 244136 : collinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_collname));
6185 488272 : collinfo[i].dobj.namespace =
6186 244136 : findNamespace(atooid(PQgetvalue(res, i, i_collnamespace)));
6187 244136 : collinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_collowner));
6188 :
6189 : /* Decide whether we want to dump it */
6190 244136 : selectDumpableObject(&(collinfo[i].dobj), fout);
6191 : }
6192 :
6193 308 : PQclear(res);
6194 :
6195 308 : destroyPQExpBuffer(query);
6196 308 : }
6197 :
6198 : /*
6199 : * getConversions:
6200 : * get information about all conversions in the system catalogs
6201 : */
6202 : void
6203 308 : getConversions(Archive *fout)
6204 : {
6205 : PGresult *res;
6206 : int ntups;
6207 : int i;
6208 : PQExpBuffer query;
6209 : ConvInfo *convinfo;
6210 : int i_tableoid;
6211 : int i_oid;
6212 : int i_conname;
6213 : int i_connamespace;
6214 : int i_conowner;
6215 :
6216 308 : query = createPQExpBuffer();
6217 :
6218 : /*
6219 : * find all conversions, including builtin conversions; we filter out
6220 : * system-defined conversions at dump-out time.
6221 : */
6222 :
6223 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, conname, "
6224 : "connamespace, "
6225 : "conowner "
6226 : "FROM pg_conversion");
6227 :
6228 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6229 :
6230 308 : ntups = PQntuples(res);
6231 :
6232 308 : convinfo = (ConvInfo *) pg_malloc(ntups * sizeof(ConvInfo));
6233 :
6234 308 : i_tableoid = PQfnumber(res, "tableoid");
6235 308 : i_oid = PQfnumber(res, "oid");
6236 308 : i_conname = PQfnumber(res, "conname");
6237 308 : i_connamespace = PQfnumber(res, "connamespace");
6238 308 : i_conowner = PQfnumber(res, "conowner");
6239 :
6240 39818 : for (i = 0; i < ntups; i++)
6241 : {
6242 39510 : convinfo[i].dobj.objType = DO_CONVERSION;
6243 39510 : convinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6244 39510 : convinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6245 39510 : AssignDumpId(&convinfo[i].dobj);
6246 39510 : convinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
6247 79020 : convinfo[i].dobj.namespace =
6248 39510 : findNamespace(atooid(PQgetvalue(res, i, i_connamespace)));
6249 39510 : convinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_conowner));
6250 :
6251 : /* Decide whether we want to dump it */
6252 39510 : selectDumpableObject(&(convinfo[i].dobj), fout);
6253 : }
6254 :
6255 308 : PQclear(res);
6256 :
6257 308 : destroyPQExpBuffer(query);
6258 308 : }
6259 :
6260 : /*
6261 : * getAccessMethods:
6262 : * get information about all user-defined access methods
6263 : */
6264 : void
6265 308 : getAccessMethods(Archive *fout)
6266 : {
6267 : PGresult *res;
6268 : int ntups;
6269 : int i;
6270 : PQExpBuffer query;
6271 : AccessMethodInfo *aminfo;
6272 : int i_tableoid;
6273 : int i_oid;
6274 : int i_amname;
6275 : int i_amhandler;
6276 : int i_amtype;
6277 :
6278 : /* Before 9.6, there are no user-defined access methods */
6279 308 : if (fout->remoteVersion < 90600)
6280 0 : return;
6281 :
6282 308 : query = createPQExpBuffer();
6283 :
6284 : /* Select all access methods from pg_am table */
6285 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, amname, amtype, "
6286 : "amhandler::pg_catalog.regproc AS amhandler "
6287 : "FROM pg_am");
6288 :
6289 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6290 :
6291 308 : ntups = PQntuples(res);
6292 :
6293 308 : aminfo = (AccessMethodInfo *) pg_malloc(ntups * sizeof(AccessMethodInfo));
6294 :
6295 308 : i_tableoid = PQfnumber(res, "tableoid");
6296 308 : i_oid = PQfnumber(res, "oid");
6297 308 : i_amname = PQfnumber(res, "amname");
6298 308 : i_amhandler = PQfnumber(res, "amhandler");
6299 308 : i_amtype = PQfnumber(res, "amtype");
6300 :
6301 2700 : for (i = 0; i < ntups; i++)
6302 : {
6303 2392 : aminfo[i].dobj.objType = DO_ACCESS_METHOD;
6304 2392 : aminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6305 2392 : aminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6306 2392 : AssignDumpId(&aminfo[i].dobj);
6307 2392 : aminfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_amname));
6308 2392 : aminfo[i].dobj.namespace = NULL;
6309 2392 : aminfo[i].amhandler = pg_strdup(PQgetvalue(res, i, i_amhandler));
6310 2392 : aminfo[i].amtype = *(PQgetvalue(res, i, i_amtype));
6311 :
6312 : /* Decide whether we want to dump it */
6313 2392 : selectDumpableAccessMethod(&(aminfo[i]), fout);
6314 : }
6315 :
6316 308 : PQclear(res);
6317 :
6318 308 : destroyPQExpBuffer(query);
6319 : }
6320 :
6321 :
6322 : /*
6323 : * getOpclasses:
6324 : * get information about all opclasses in the system catalogs
6325 : */
6326 : void
6327 308 : getOpclasses(Archive *fout)
6328 : {
6329 : PGresult *res;
6330 : int ntups;
6331 : int i;
6332 308 : PQExpBuffer query = createPQExpBuffer();
6333 : OpclassInfo *opcinfo;
6334 : int i_tableoid;
6335 : int i_oid;
6336 : int i_opcname;
6337 : int i_opcnamespace;
6338 : int i_opcowner;
6339 :
6340 : /*
6341 : * find all opclasses, including builtin opclasses; we filter out
6342 : * system-defined opclasses at dump-out time.
6343 : */
6344 :
6345 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, opcname, "
6346 : "opcnamespace, "
6347 : "opcowner "
6348 : "FROM pg_opclass");
6349 :
6350 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6351 :
6352 308 : ntups = PQntuples(res);
6353 :
6354 308 : opcinfo = (OpclassInfo *) pg_malloc(ntups * sizeof(OpclassInfo));
6355 :
6356 308 : i_tableoid = PQfnumber(res, "tableoid");
6357 308 : i_oid = PQfnumber(res, "oid");
6358 308 : i_opcname = PQfnumber(res, "opcname");
6359 308 : i_opcnamespace = PQfnumber(res, "opcnamespace");
6360 308 : i_opcowner = PQfnumber(res, "opcowner");
6361 :
6362 55124 : for (i = 0; i < ntups; i++)
6363 : {
6364 54816 : opcinfo[i].dobj.objType = DO_OPCLASS;
6365 54816 : opcinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6366 54816 : opcinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6367 54816 : AssignDumpId(&opcinfo[i].dobj);
6368 54816 : opcinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opcname));
6369 109632 : opcinfo[i].dobj.namespace =
6370 54816 : findNamespace(atooid(PQgetvalue(res, i, i_opcnamespace)));
6371 54816 : opcinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_opcowner));
6372 :
6373 : /* Decide whether we want to dump it */
6374 54816 : selectDumpableObject(&(opcinfo[i].dobj), fout);
6375 : }
6376 :
6377 308 : PQclear(res);
6378 :
6379 308 : destroyPQExpBuffer(query);
6380 308 : }
6381 :
6382 : /*
6383 : * getOpfamilies:
6384 : * get information about all opfamilies in the system catalogs
6385 : */
6386 : void
6387 308 : getOpfamilies(Archive *fout)
6388 : {
6389 : PGresult *res;
6390 : int ntups;
6391 : int i;
6392 : PQExpBuffer query;
6393 : OpfamilyInfo *opfinfo;
6394 : int i_tableoid;
6395 : int i_oid;
6396 : int i_opfname;
6397 : int i_opfnamespace;
6398 : int i_opfowner;
6399 :
6400 308 : query = createPQExpBuffer();
6401 :
6402 : /*
6403 : * find all opfamilies, including builtin opfamilies; we filter out
6404 : * system-defined opfamilies at dump-out time.
6405 : */
6406 :
6407 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, opfname, "
6408 : "opfnamespace, "
6409 : "opfowner "
6410 : "FROM pg_opfamily");
6411 :
6412 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6413 :
6414 308 : ntups = PQntuples(res);
6415 :
6416 308 : opfinfo = (OpfamilyInfo *) pg_malloc(ntups * sizeof(OpfamilyInfo));
6417 :
6418 308 : i_tableoid = PQfnumber(res, "tableoid");
6419 308 : i_oid = PQfnumber(res, "oid");
6420 308 : i_opfname = PQfnumber(res, "opfname");
6421 308 : i_opfnamespace = PQfnumber(res, "opfnamespace");
6422 308 : i_opfowner = PQfnumber(res, "opfowner");
6423 :
6424 45546 : for (i = 0; i < ntups; i++)
6425 : {
6426 45238 : opfinfo[i].dobj.objType = DO_OPFAMILY;
6427 45238 : opfinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6428 45238 : opfinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6429 45238 : AssignDumpId(&opfinfo[i].dobj);
6430 45238 : opfinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_opfname));
6431 90476 : opfinfo[i].dobj.namespace =
6432 45238 : findNamespace(atooid(PQgetvalue(res, i, i_opfnamespace)));
6433 45238 : opfinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_opfowner));
6434 :
6435 : /* Decide whether we want to dump it */
6436 45238 : selectDumpableObject(&(opfinfo[i].dobj), fout);
6437 : }
6438 :
6439 308 : PQclear(res);
6440 :
6441 308 : destroyPQExpBuffer(query);
6442 308 : }
6443 :
6444 : /*
6445 : * getAggregates:
6446 : * get information about all user-defined aggregates in the system catalogs
6447 : */
6448 : void
6449 308 : getAggregates(Archive *fout)
6450 : {
6451 308 : DumpOptions *dopt = fout->dopt;
6452 : PGresult *res;
6453 : int ntups;
6454 : int i;
6455 308 : PQExpBuffer query = createPQExpBuffer();
6456 : AggInfo *agginfo;
6457 : int i_tableoid;
6458 : int i_oid;
6459 : int i_aggname;
6460 : int i_aggnamespace;
6461 : int i_pronargs;
6462 : int i_proargtypes;
6463 : int i_proowner;
6464 : int i_aggacl;
6465 : int i_acldefault;
6466 :
6467 : /*
6468 : * Find all interesting aggregates. See comment in getFuncs() for the
6469 : * rationale behind the filtering logic.
6470 : */
6471 308 : if (fout->remoteVersion >= 90600)
6472 : {
6473 : const char *agg_check;
6474 :
6475 616 : agg_check = (fout->remoteVersion >= 110000 ? "p.prokind = 'a'"
6476 308 : : "p.proisagg");
6477 :
6478 308 : appendPQExpBuffer(query, "SELECT p.tableoid, p.oid, "
6479 : "p.proname AS aggname, "
6480 : "p.pronamespace AS aggnamespace, "
6481 : "p.pronargs, p.proargtypes, "
6482 : "p.proowner, "
6483 : "p.proacl AS aggacl, "
6484 : "acldefault('f', p.proowner) AS acldefault "
6485 : "FROM pg_proc p "
6486 : "LEFT JOIN pg_init_privs pip ON "
6487 : "(p.oid = pip.objoid "
6488 : "AND pip.classoid = 'pg_proc'::regclass "
6489 : "AND pip.objsubid = 0) "
6490 : "WHERE %s AND ("
6491 : "p.pronamespace != "
6492 : "(SELECT oid FROM pg_namespace "
6493 : "WHERE nspname = 'pg_catalog') OR "
6494 : "p.proacl IS DISTINCT FROM pip.initprivs",
6495 : agg_check);
6496 308 : if (dopt->binary_upgrade)
6497 28 : appendPQExpBufferStr(query,
6498 : " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6499 : "classid = 'pg_proc'::regclass AND "
6500 : "objid = p.oid AND "
6501 : "refclassid = 'pg_extension'::regclass AND "
6502 : "deptype = 'e')");
6503 308 : appendPQExpBufferChar(query, ')');
6504 : }
6505 : else
6506 : {
6507 0 : appendPQExpBufferStr(query, "SELECT tableoid, oid, proname AS aggname, "
6508 : "pronamespace AS aggnamespace, "
6509 : "pronargs, proargtypes, "
6510 : "proowner, "
6511 : "proacl AS aggacl, "
6512 : "acldefault('f', proowner) AS acldefault "
6513 : "FROM pg_proc p "
6514 : "WHERE proisagg AND ("
6515 : "pronamespace != "
6516 : "(SELECT oid FROM pg_namespace "
6517 : "WHERE nspname = 'pg_catalog')");
6518 0 : if (dopt->binary_upgrade)
6519 0 : appendPQExpBufferStr(query,
6520 : " OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6521 : "classid = 'pg_proc'::regclass AND "
6522 : "objid = p.oid AND "
6523 : "refclassid = 'pg_extension'::regclass AND "
6524 : "deptype = 'e')");
6525 0 : appendPQExpBufferChar(query, ')');
6526 : }
6527 :
6528 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6529 :
6530 308 : ntups = PQntuples(res);
6531 :
6532 308 : agginfo = (AggInfo *) pg_malloc(ntups * sizeof(AggInfo));
6533 :
6534 308 : i_tableoid = PQfnumber(res, "tableoid");
6535 308 : i_oid = PQfnumber(res, "oid");
6536 308 : i_aggname = PQfnumber(res, "aggname");
6537 308 : i_aggnamespace = PQfnumber(res, "aggnamespace");
6538 308 : i_pronargs = PQfnumber(res, "pronargs");
6539 308 : i_proargtypes = PQfnumber(res, "proargtypes");
6540 308 : i_proowner = PQfnumber(res, "proowner");
6541 308 : i_aggacl = PQfnumber(res, "aggacl");
6542 308 : i_acldefault = PQfnumber(res, "acldefault");
6543 :
6544 1102 : for (i = 0; i < ntups; i++)
6545 : {
6546 794 : agginfo[i].aggfn.dobj.objType = DO_AGG;
6547 794 : agginfo[i].aggfn.dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6548 794 : agginfo[i].aggfn.dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6549 794 : AssignDumpId(&agginfo[i].aggfn.dobj);
6550 794 : agginfo[i].aggfn.dobj.name = pg_strdup(PQgetvalue(res, i, i_aggname));
6551 1588 : agginfo[i].aggfn.dobj.namespace =
6552 794 : findNamespace(atooid(PQgetvalue(res, i, i_aggnamespace)));
6553 794 : agginfo[i].aggfn.dacl.acl = pg_strdup(PQgetvalue(res, i, i_aggacl));
6554 794 : agginfo[i].aggfn.dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
6555 794 : agginfo[i].aggfn.dacl.privtype = 0;
6556 794 : agginfo[i].aggfn.dacl.initprivs = NULL;
6557 794 : agginfo[i].aggfn.rolname = getRoleName(PQgetvalue(res, i, i_proowner));
6558 794 : agginfo[i].aggfn.lang = InvalidOid; /* not currently interesting */
6559 794 : agginfo[i].aggfn.prorettype = InvalidOid; /* not saved */
6560 794 : agginfo[i].aggfn.nargs = atoi(PQgetvalue(res, i, i_pronargs));
6561 794 : if (agginfo[i].aggfn.nargs == 0)
6562 112 : agginfo[i].aggfn.argtypes = NULL;
6563 : else
6564 : {
6565 682 : agginfo[i].aggfn.argtypes = (Oid *) pg_malloc(agginfo[i].aggfn.nargs * sizeof(Oid));
6566 682 : parseOidArray(PQgetvalue(res, i, i_proargtypes),
6567 682 : agginfo[i].aggfn.argtypes,
6568 682 : agginfo[i].aggfn.nargs);
6569 : }
6570 794 : agginfo[i].aggfn.postponed_def = false; /* might get set during sort */
6571 :
6572 : /* Decide whether we want to dump it */
6573 794 : selectDumpableObject(&(agginfo[i].aggfn.dobj), fout);
6574 :
6575 : /* Mark whether aggregate has an ACL */
6576 794 : if (!PQgetisnull(res, i, i_aggacl))
6577 50 : agginfo[i].aggfn.dobj.components |= DUMP_COMPONENT_ACL;
6578 : }
6579 :
6580 308 : PQclear(res);
6581 :
6582 308 : destroyPQExpBuffer(query);
6583 308 : }
6584 :
6585 : /*
6586 : * getFuncs:
6587 : * get information about all user-defined functions in the system catalogs
6588 : */
6589 : void
6590 308 : getFuncs(Archive *fout)
6591 : {
6592 308 : DumpOptions *dopt = fout->dopt;
6593 : PGresult *res;
6594 : int ntups;
6595 : int i;
6596 308 : PQExpBuffer query = createPQExpBuffer();
6597 : FuncInfo *finfo;
6598 : int i_tableoid;
6599 : int i_oid;
6600 : int i_proname;
6601 : int i_pronamespace;
6602 : int i_proowner;
6603 : int i_prolang;
6604 : int i_pronargs;
6605 : int i_proargtypes;
6606 : int i_prorettype;
6607 : int i_proacl;
6608 : int i_acldefault;
6609 :
6610 : /*
6611 : * Find all interesting functions. This is a bit complicated:
6612 : *
6613 : * 1. Always exclude aggregates; those are handled elsewhere.
6614 : *
6615 : * 2. Always exclude functions that are internally dependent on something
6616 : * else, since presumably those will be created as a result of creating
6617 : * the something else. This currently acts only to suppress constructor
6618 : * functions for range types. Note this is OK only because the
6619 : * constructors don't have any dependencies the range type doesn't have;
6620 : * otherwise we might not get creation ordering correct.
6621 : *
6622 : * 3. Otherwise, we normally exclude functions in pg_catalog. However, if
6623 : * they're members of extensions and we are in binary-upgrade mode then
6624 : * include them, since we want to dump extension members individually in
6625 : * that mode. Also, if they are used by casts or transforms then we need
6626 : * to gather the information about them, though they won't be dumped if
6627 : * they are built-in. Also, in 9.6 and up, include functions in
6628 : * pg_catalog if they have an ACL different from what's shown in
6629 : * pg_init_privs (so we have to join to pg_init_privs; annoying).
6630 : */
6631 308 : if (fout->remoteVersion >= 90600)
6632 : {
6633 : const char *not_agg_check;
6634 :
6635 616 : not_agg_check = (fout->remoteVersion >= 110000 ? "p.prokind <> 'a'"
6636 308 : : "NOT p.proisagg");
6637 :
6638 308 : appendPQExpBuffer(query,
6639 : "SELECT p.tableoid, p.oid, p.proname, p.prolang, "
6640 : "p.pronargs, p.proargtypes, p.prorettype, "
6641 : "p.proacl, "
6642 : "acldefault('f', p.proowner) AS acldefault, "
6643 : "p.pronamespace, "
6644 : "p.proowner "
6645 : "FROM pg_proc p "
6646 : "LEFT JOIN pg_init_privs pip ON "
6647 : "(p.oid = pip.objoid "
6648 : "AND pip.classoid = 'pg_proc'::regclass "
6649 : "AND pip.objsubid = 0) "
6650 : "WHERE %s"
6651 : "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
6652 : "WHERE classid = 'pg_proc'::regclass AND "
6653 : "objid = p.oid AND deptype = 'i')"
6654 : "\n AND ("
6655 : "\n pronamespace != "
6656 : "(SELECT oid FROM pg_namespace "
6657 : "WHERE nspname = 'pg_catalog')"
6658 : "\n OR EXISTS (SELECT 1 FROM pg_cast"
6659 : "\n WHERE pg_cast.oid > %u "
6660 : "\n AND p.oid = pg_cast.castfunc)"
6661 : "\n OR EXISTS (SELECT 1 FROM pg_transform"
6662 : "\n WHERE pg_transform.oid > %u AND "
6663 : "\n (p.oid = pg_transform.trffromsql"
6664 : "\n OR p.oid = pg_transform.trftosql))",
6665 : not_agg_check,
6666 : g_last_builtin_oid,
6667 : g_last_builtin_oid);
6668 308 : if (dopt->binary_upgrade)
6669 28 : appendPQExpBufferStr(query,
6670 : "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6671 : "classid = 'pg_proc'::regclass AND "
6672 : "objid = p.oid AND "
6673 : "refclassid = 'pg_extension'::regclass AND "
6674 : "deptype = 'e')");
6675 308 : appendPQExpBufferStr(query,
6676 : "\n OR p.proacl IS DISTINCT FROM pip.initprivs");
6677 308 : appendPQExpBufferChar(query, ')');
6678 : }
6679 : else
6680 : {
6681 0 : appendPQExpBuffer(query,
6682 : "SELECT tableoid, oid, proname, prolang, "
6683 : "pronargs, proargtypes, prorettype, proacl, "
6684 : "acldefault('f', proowner) AS acldefault, "
6685 : "pronamespace, "
6686 : "proowner "
6687 : "FROM pg_proc p "
6688 : "WHERE NOT proisagg"
6689 : "\n AND NOT EXISTS (SELECT 1 FROM pg_depend "
6690 : "WHERE classid = 'pg_proc'::regclass AND "
6691 : "objid = p.oid AND deptype = 'i')"
6692 : "\n AND ("
6693 : "\n pronamespace != "
6694 : "(SELECT oid FROM pg_namespace "
6695 : "WHERE nspname = 'pg_catalog')"
6696 : "\n OR EXISTS (SELECT 1 FROM pg_cast"
6697 : "\n WHERE pg_cast.oid > '%u'::oid"
6698 : "\n AND p.oid = pg_cast.castfunc)",
6699 : g_last_builtin_oid);
6700 :
6701 0 : if (fout->remoteVersion >= 90500)
6702 0 : appendPQExpBuffer(query,
6703 : "\n OR EXISTS (SELECT 1 FROM pg_transform"
6704 : "\n WHERE pg_transform.oid > '%u'::oid"
6705 : "\n AND (p.oid = pg_transform.trffromsql"
6706 : "\n OR p.oid = pg_transform.trftosql))",
6707 : g_last_builtin_oid);
6708 :
6709 0 : if (dopt->binary_upgrade)
6710 0 : appendPQExpBufferStr(query,
6711 : "\n OR EXISTS(SELECT 1 FROM pg_depend WHERE "
6712 : "classid = 'pg_proc'::regclass AND "
6713 : "objid = p.oid AND "
6714 : "refclassid = 'pg_extension'::regclass AND "
6715 : "deptype = 'e')");
6716 0 : appendPQExpBufferChar(query, ')');
6717 : }
6718 :
6719 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6720 :
6721 308 : ntups = PQntuples(res);
6722 :
6723 308 : finfo = (FuncInfo *) pg_malloc0(ntups * sizeof(FuncInfo));
6724 :
6725 308 : i_tableoid = PQfnumber(res, "tableoid");
6726 308 : i_oid = PQfnumber(res, "oid");
6727 308 : i_proname = PQfnumber(res, "proname");
6728 308 : i_pronamespace = PQfnumber(res, "pronamespace");
6729 308 : i_proowner = PQfnumber(res, "proowner");
6730 308 : i_prolang = PQfnumber(res, "prolang");
6731 308 : i_pronargs = PQfnumber(res, "pronargs");
6732 308 : i_proargtypes = PQfnumber(res, "proargtypes");
6733 308 : i_prorettype = PQfnumber(res, "prorettype");
6734 308 : i_proacl = PQfnumber(res, "proacl");
6735 308 : i_acldefault = PQfnumber(res, "acldefault");
6736 :
6737 8864 : for (i = 0; i < ntups; i++)
6738 : {
6739 8556 : finfo[i].dobj.objType = DO_FUNC;
6740 8556 : finfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
6741 8556 : finfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
6742 8556 : AssignDumpId(&finfo[i].dobj);
6743 8556 : finfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_proname));
6744 17112 : finfo[i].dobj.namespace =
6745 8556 : findNamespace(atooid(PQgetvalue(res, i, i_pronamespace)));
6746 8556 : finfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_proacl));
6747 8556 : finfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
6748 8556 : finfo[i].dacl.privtype = 0;
6749 8556 : finfo[i].dacl.initprivs = NULL;
6750 8556 : finfo[i].rolname = getRoleName(PQgetvalue(res, i, i_proowner));
6751 8556 : finfo[i].lang = atooid(PQgetvalue(res, i, i_prolang));
6752 8556 : finfo[i].prorettype = atooid(PQgetvalue(res, i, i_prorettype));
6753 8556 : finfo[i].nargs = atoi(PQgetvalue(res, i, i_pronargs));
6754 8556 : if (finfo[i].nargs == 0)
6755 2006 : finfo[i].argtypes = NULL;
6756 : else
6757 : {
6758 6550 : finfo[i].argtypes = (Oid *) pg_malloc(finfo[i].nargs * sizeof(Oid));
6759 6550 : parseOidArray(PQgetvalue(res, i, i_proargtypes),
6760 6550 : finfo[i].argtypes, finfo[i].nargs);
6761 : }
6762 8556 : finfo[i].postponed_def = false; /* might get set during sort */
6763 :
6764 : /* Decide whether we want to dump it */
6765 8556 : selectDumpableObject(&(finfo[i].dobj), fout);
6766 :
6767 : /* Mark whether function has an ACL */
6768 8556 : if (!PQgetisnull(res, i, i_proacl))
6769 272 : finfo[i].dobj.components |= DUMP_COMPONENT_ACL;
6770 : }
6771 :
6772 308 : PQclear(res);
6773 :
6774 308 : destroyPQExpBuffer(query);
6775 308 : }
6776 :
6777 : /*
6778 : * getTables
6779 : * read all the tables (no indexes) in the system catalogs,
6780 : * and return them as an array of TableInfo structures
6781 : *
6782 : * *numTables is set to the number of tables read in
6783 : */
6784 : TableInfo *
6785 310 : getTables(Archive *fout, int *numTables)
6786 : {
6787 310 : DumpOptions *dopt = fout->dopt;
6788 : PGresult *res;
6789 : int ntups;
6790 : int i;
6791 310 : PQExpBuffer query = createPQExpBuffer();
6792 : TableInfo *tblinfo;
6793 : int i_reltableoid;
6794 : int i_reloid;
6795 : int i_relname;
6796 : int i_relnamespace;
6797 : int i_relkind;
6798 : int i_reltype;
6799 : int i_relowner;
6800 : int i_relchecks;
6801 : int i_relhasindex;
6802 : int i_relhasrules;
6803 : int i_relpages;
6804 : int i_toastpages;
6805 : int i_owning_tab;
6806 : int i_owning_col;
6807 : int i_reltablespace;
6808 : int i_relhasoids;
6809 : int i_relhastriggers;
6810 : int i_relpersistence;
6811 : int i_relispopulated;
6812 : int i_relreplident;
6813 : int i_relrowsec;
6814 : int i_relforcerowsec;
6815 : int i_relfrozenxid;
6816 : int i_toastfrozenxid;
6817 : int i_toastoid;
6818 : int i_relminmxid;
6819 : int i_toastminmxid;
6820 : int i_reloptions;
6821 : int i_checkoption;
6822 : int i_toastreloptions;
6823 : int i_reloftype;
6824 : int i_foreignserver;
6825 : int i_amname;
6826 : int i_is_identity_sequence;
6827 : int i_relacl;
6828 : int i_acldefault;
6829 : int i_ispartition;
6830 :
6831 : /*
6832 : * Find all the tables and table-like objects.
6833 : *
6834 : * We must fetch all tables in this phase because otherwise we cannot
6835 : * correctly identify inherited columns, owned sequences, etc.
6836 : *
6837 : * We include system catalogs, so that we can work if a user table is
6838 : * defined to inherit from a system catalog (pretty weird, but...)
6839 : *
6840 : * Note: in this phase we should collect only a minimal amount of
6841 : * information about each table, basically just enough to decide if it is
6842 : * interesting. In particular, since we do not yet have lock on any user
6843 : * table, we MUST NOT invoke any server-side data collection functions
6844 : * (for instance, pg_get_partkeydef()). Those are likely to fail or give
6845 : * wrong answers if any concurrent DDL is happening.
6846 : */
6847 :
6848 310 : appendPQExpBufferStr(query,
6849 : "SELECT c.tableoid, c.oid, c.relname, "
6850 : "c.relnamespace, c.relkind, c.reltype, "
6851 : "c.relowner, "
6852 : "c.relchecks, "
6853 : "c.relhasindex, c.relhasrules, c.relpages, "
6854 : "c.relhastriggers, "
6855 : "c.relpersistence, "
6856 : "c.reloftype, "
6857 : "c.relacl, "
6858 : "acldefault(CASE WHEN c.relkind = " CppAsString2(RELKIND_SEQUENCE)
6859 : " THEN 's'::\"char\" ELSE 'r'::\"char\" END, c.relowner) AS acldefault, "
6860 : "CASE WHEN c.relkind = " CppAsString2(RELKIND_FOREIGN_TABLE) " THEN "
6861 : "(SELECT ftserver FROM pg_catalog.pg_foreign_table WHERE ftrelid = c.oid) "
6862 : "ELSE 0 END AS foreignserver, "
6863 : "c.relfrozenxid, tc.relfrozenxid AS tfrozenxid, "
6864 : "tc.oid AS toid, "
6865 : "tc.relpages AS toastpages, "
6866 : "tc.reloptions AS toast_reloptions, "
6867 : "d.refobjid AS owning_tab, "
6868 : "d.refobjsubid AS owning_col, "
6869 : "tsp.spcname AS reltablespace, ");
6870 :
6871 310 : if (fout->remoteVersion >= 120000)
6872 310 : appendPQExpBufferStr(query,
6873 : "false AS relhasoids, ");
6874 : else
6875 0 : appendPQExpBufferStr(query,
6876 : "c.relhasoids, ");
6877 :
6878 310 : if (fout->remoteVersion >= 90300)
6879 310 : appendPQExpBufferStr(query,
6880 : "c.relispopulated, ");
6881 : else
6882 0 : appendPQExpBufferStr(query,
6883 : "'t' as relispopulated, ");
6884 :
6885 310 : if (fout->remoteVersion >= 90400)
6886 310 : appendPQExpBufferStr(query,
6887 : "c.relreplident, ");
6888 : else
6889 0 : appendPQExpBufferStr(query,
6890 : "'d' AS relreplident, ");
6891 :
6892 310 : if (fout->remoteVersion >= 90500)
6893 310 : appendPQExpBufferStr(query,
6894 : "c.relrowsecurity, c.relforcerowsecurity, ");
6895 : else
6896 0 : appendPQExpBufferStr(query,
6897 : "false AS relrowsecurity, "
6898 : "false AS relforcerowsecurity, ");
6899 :
6900 310 : if (fout->remoteVersion >= 90300)
6901 310 : appendPQExpBufferStr(query,
6902 : "c.relminmxid, tc.relminmxid AS tminmxid, ");
6903 : else
6904 0 : appendPQExpBufferStr(query,
6905 : "0 AS relminmxid, 0 AS tminmxid, ");
6906 :
6907 310 : if (fout->remoteVersion >= 90300)
6908 310 : appendPQExpBufferStr(query,
6909 : "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6910 : "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6911 : "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption, ");
6912 : else
6913 0 : appendPQExpBufferStr(query,
6914 : "c.reloptions, NULL AS checkoption, ");
6915 :
6916 310 : if (fout->remoteVersion >= 90600)
6917 310 : appendPQExpBufferStr(query,
6918 : "am.amname, ");
6919 : else
6920 0 : appendPQExpBufferStr(query,
6921 : "NULL AS amname, ");
6922 :
6923 310 : if (fout->remoteVersion >= 90600)
6924 310 : appendPQExpBufferStr(query,
6925 : "(d.deptype = 'i') IS TRUE AS is_identity_sequence, ");
6926 : else
6927 0 : appendPQExpBufferStr(query,
6928 : "false AS is_identity_sequence, ");
6929 :
6930 310 : if (fout->remoteVersion >= 100000)
6931 310 : appendPQExpBufferStr(query,
6932 : "c.relispartition AS ispartition ");
6933 : else
6934 0 : appendPQExpBufferStr(query,
6935 : "false AS ispartition ");
6936 :
6937 : /*
6938 : * Left join to pg_depend to pick up dependency info linking sequences to
6939 : * their owning column, if any (note this dependency is AUTO except for
6940 : * identity sequences, where it's INTERNAL). Also join to pg_tablespace to
6941 : * collect the spcname.
6942 : */
6943 310 : appendPQExpBufferStr(query,
6944 : "\nFROM pg_class c\n"
6945 : "LEFT JOIN pg_depend d ON "
6946 : "(c.relkind = " CppAsString2(RELKIND_SEQUENCE) " AND "
6947 : "d.classid = 'pg_class'::regclass AND d.objid = c.oid AND "
6948 : "d.objsubid = 0 AND "
6949 : "d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i'))\n"
6950 : "LEFT JOIN pg_tablespace tsp ON (tsp.oid = c.reltablespace)\n");
6951 :
6952 : /*
6953 : * In 9.6 and up, left join to pg_am to pick up the amname.
6954 : */
6955 310 : if (fout->remoteVersion >= 90600)
6956 310 : appendPQExpBufferStr(query,
6957 : "LEFT JOIN pg_am am ON (c.relam = am.oid)\n");
6958 :
6959 : /*
6960 : * We purposefully ignore toast OIDs for partitioned tables; the reason is
6961 : * that versions 10 and 11 have them, but later versions do not, so
6962 : * emitting them causes the upgrade to fail.
6963 : */
6964 310 : appendPQExpBufferStr(query,
6965 : "LEFT JOIN pg_class tc ON (c.reltoastrelid = tc.oid"
6966 : " AND tc.relkind = " CppAsString2(RELKIND_TOASTVALUE)
6967 : " AND c.relkind <> " CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n");
6968 :
6969 : /*
6970 : * Restrict to interesting relkinds (in particular, not indexes). Not all
6971 : * relkinds are possible in older servers, but it's not worth the trouble
6972 : * to emit a version-dependent list.
6973 : *
6974 : * Composite-type table entries won't be dumped as such, but we have to
6975 : * make a DumpableObject for them so that we can track dependencies of the
6976 : * composite type (pg_depend entries for columns of the composite type
6977 : * link to the pg_class entry not the pg_type entry).
6978 : */
6979 310 : appendPQExpBufferStr(query,
6980 : "WHERE c.relkind IN ("
6981 : CppAsString2(RELKIND_RELATION) ", "
6982 : CppAsString2(RELKIND_SEQUENCE) ", "
6983 : CppAsString2(RELKIND_VIEW) ", "
6984 : CppAsString2(RELKIND_COMPOSITE_TYPE) ", "
6985 : CppAsString2(RELKIND_MATVIEW) ", "
6986 : CppAsString2(RELKIND_FOREIGN_TABLE) ", "
6987 : CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n"
6988 : "ORDER BY c.oid");
6989 :
6990 310 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
6991 :
6992 310 : ntups = PQntuples(res);
6993 :
6994 310 : *numTables = ntups;
6995 :
6996 : /*
6997 : * Extract data from result and lock dumpable tables. We do the locking
6998 : * before anything else, to minimize the window wherein a table could
6999 : * disappear under us.
7000 : *
7001 : * Note that we have to save info about all tables here, even when dumping
7002 : * only one, because we don't yet know which tables might be inheritance
7003 : * ancestors of the target table.
7004 : */
7005 310 : tblinfo = (TableInfo *) pg_malloc0(ntups * sizeof(TableInfo));
7006 :
7007 310 : i_reltableoid = PQfnumber(res, "tableoid");
7008 310 : i_reloid = PQfnumber(res, "oid");
7009 310 : i_relname = PQfnumber(res, "relname");
7010 310 : i_relnamespace = PQfnumber(res, "relnamespace");
7011 310 : i_relkind = PQfnumber(res, "relkind");
7012 310 : i_reltype = PQfnumber(res, "reltype");
7013 310 : i_relowner = PQfnumber(res, "relowner");
7014 310 : i_relchecks = PQfnumber(res, "relchecks");
7015 310 : i_relhasindex = PQfnumber(res, "relhasindex");
7016 310 : i_relhasrules = PQfnumber(res, "relhasrules");
7017 310 : i_relpages = PQfnumber(res, "relpages");
7018 310 : i_toastpages = PQfnumber(res, "toastpages");
7019 310 : i_owning_tab = PQfnumber(res, "owning_tab");
7020 310 : i_owning_col = PQfnumber(res, "owning_col");
7021 310 : i_reltablespace = PQfnumber(res, "reltablespace");
7022 310 : i_relhasoids = PQfnumber(res, "relhasoids");
7023 310 : i_relhastriggers = PQfnumber(res, "relhastriggers");
7024 310 : i_relpersistence = PQfnumber(res, "relpersistence");
7025 310 : i_relispopulated = PQfnumber(res, "relispopulated");
7026 310 : i_relreplident = PQfnumber(res, "relreplident");
7027 310 : i_relrowsec = PQfnumber(res, "relrowsecurity");
7028 310 : i_relforcerowsec = PQfnumber(res, "relforcerowsecurity");
7029 310 : i_relfrozenxid = PQfnumber(res, "relfrozenxid");
7030 310 : i_toastfrozenxid = PQfnumber(res, "tfrozenxid");
7031 310 : i_toastoid = PQfnumber(res, "toid");
7032 310 : i_relminmxid = PQfnumber(res, "relminmxid");
7033 310 : i_toastminmxid = PQfnumber(res, "tminmxid");
7034 310 : i_reloptions = PQfnumber(res, "reloptions");
7035 310 : i_checkoption = PQfnumber(res, "checkoption");
7036 310 : i_toastreloptions = PQfnumber(res, "toast_reloptions");
7037 310 : i_reloftype = PQfnumber(res, "reloftype");
7038 310 : i_foreignserver = PQfnumber(res, "foreignserver");
7039 310 : i_amname = PQfnumber(res, "amname");
7040 310 : i_is_identity_sequence = PQfnumber(res, "is_identity_sequence");
7041 310 : i_relacl = PQfnumber(res, "relacl");
7042 310 : i_acldefault = PQfnumber(res, "acldefault");
7043 310 : i_ispartition = PQfnumber(res, "ispartition");
7044 :
7045 310 : if (dopt->lockWaitTimeout)
7046 : {
7047 : /*
7048 : * Arrange to fail instead of waiting forever for a table lock.
7049 : *
7050 : * NB: this coding assumes that the only queries issued within the
7051 : * following loop are LOCK TABLEs; else the timeout may be undesirably
7052 : * applied to other things too.
7053 : */
7054 4 : resetPQExpBuffer(query);
7055 4 : appendPQExpBufferStr(query, "SET statement_timeout = ");
7056 4 : appendStringLiteralConn(query, dopt->lockWaitTimeout, GetConnection(fout));
7057 4 : ExecuteSqlStatement(fout, query->data);
7058 : }
7059 :
7060 310 : resetPQExpBuffer(query);
7061 :
7062 81736 : for (i = 0; i < ntups; i++)
7063 : {
7064 81426 : tblinfo[i].dobj.objType = DO_TABLE;
7065 81426 : tblinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_reltableoid));
7066 81426 : tblinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_reloid));
7067 81426 : AssignDumpId(&tblinfo[i].dobj);
7068 81426 : tblinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_relname));
7069 162852 : tblinfo[i].dobj.namespace =
7070 81426 : findNamespace(atooid(PQgetvalue(res, i, i_relnamespace)));
7071 81426 : tblinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_relacl));
7072 81426 : tblinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
7073 81426 : tblinfo[i].dacl.privtype = 0;
7074 81426 : tblinfo[i].dacl.initprivs = NULL;
7075 81426 : tblinfo[i].relkind = *(PQgetvalue(res, i, i_relkind));
7076 81426 : tblinfo[i].reltype = atooid(PQgetvalue(res, i, i_reltype));
7077 81426 : tblinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_relowner));
7078 81426 : tblinfo[i].ncheck = atoi(PQgetvalue(res, i, i_relchecks));
7079 81426 : tblinfo[i].hasindex = (strcmp(PQgetvalue(res, i, i_relhasindex), "t") == 0);
7080 81426 : tblinfo[i].hasrules = (strcmp(PQgetvalue(res, i, i_relhasrules), "t") == 0);
7081 81426 : tblinfo[i].relpages = atoi(PQgetvalue(res, i, i_relpages));
7082 81426 : if (PQgetisnull(res, i, i_toastpages))
7083 64176 : tblinfo[i].toastpages = 0;
7084 : else
7085 17250 : tblinfo[i].toastpages = atoi(PQgetvalue(res, i, i_toastpages));
7086 81426 : if (PQgetisnull(res, i, i_owning_tab))
7087 : {
7088 80678 : tblinfo[i].owning_tab = InvalidOid;
7089 80678 : tblinfo[i].owning_col = 0;
7090 : }
7091 : else
7092 : {
7093 748 : tblinfo[i].owning_tab = atooid(PQgetvalue(res, i, i_owning_tab));
7094 748 : tblinfo[i].owning_col = atoi(PQgetvalue(res, i, i_owning_col));
7095 : }
7096 81426 : tblinfo[i].reltablespace = pg_strdup(PQgetvalue(res, i, i_reltablespace));
7097 81426 : tblinfo[i].hasoids = (strcmp(PQgetvalue(res, i, i_relhasoids), "t") == 0);
7098 81426 : tblinfo[i].hastriggers = (strcmp(PQgetvalue(res, i, i_relhastriggers), "t") == 0);
7099 81426 : tblinfo[i].relpersistence = *(PQgetvalue(res, i, i_relpersistence));
7100 81426 : tblinfo[i].relispopulated = (strcmp(PQgetvalue(res, i, i_relispopulated), "t") == 0);
7101 81426 : tblinfo[i].relreplident = *(PQgetvalue(res, i, i_relreplident));
7102 81426 : tblinfo[i].rowsec = (strcmp(PQgetvalue(res, i, i_relrowsec), "t") == 0);
7103 81426 : tblinfo[i].forcerowsec = (strcmp(PQgetvalue(res, i, i_relforcerowsec), "t") == 0);
7104 81426 : tblinfo[i].frozenxid = atooid(PQgetvalue(res, i, i_relfrozenxid));
7105 81426 : tblinfo[i].toast_frozenxid = atooid(PQgetvalue(res, i, i_toastfrozenxid));
7106 81426 : tblinfo[i].toast_oid = atooid(PQgetvalue(res, i, i_toastoid));
7107 81426 : tblinfo[i].minmxid = atooid(PQgetvalue(res, i, i_relminmxid));
7108 81426 : tblinfo[i].toast_minmxid = atooid(PQgetvalue(res, i, i_toastminmxid));
7109 81426 : tblinfo[i].reloptions = pg_strdup(PQgetvalue(res, i, i_reloptions));
7110 81426 : if (PQgetisnull(res, i, i_checkoption))
7111 81338 : tblinfo[i].checkoption = NULL;
7112 : else
7113 88 : tblinfo[i].checkoption = pg_strdup(PQgetvalue(res, i, i_checkoption));
7114 81426 : tblinfo[i].toast_reloptions = pg_strdup(PQgetvalue(res, i, i_toastreloptions));
7115 81426 : tblinfo[i].reloftype = atooid(PQgetvalue(res, i, i_reloftype));
7116 81426 : tblinfo[i].foreign_server = atooid(PQgetvalue(res, i, i_foreignserver));
7117 81426 : if (PQgetisnull(res, i, i_amname))
7118 48084 : tblinfo[i].amname = NULL;
7119 : else
7120 33342 : tblinfo[i].amname = pg_strdup(PQgetvalue(res, i, i_amname));
7121 81426 : tblinfo[i].is_identity_sequence = (strcmp(PQgetvalue(res, i, i_is_identity_sequence), "t") == 0);
7122 81426 : tblinfo[i].ispartition = (strcmp(PQgetvalue(res, i, i_ispartition), "t") == 0);
7123 :
7124 : /* other fields were zeroed above */
7125 :
7126 : /*
7127 : * Decide whether we want to dump this table.
7128 : */
7129 81426 : if (tblinfo[i].relkind == RELKIND_COMPOSITE_TYPE)
7130 362 : tblinfo[i].dobj.dump = DUMP_COMPONENT_NONE;
7131 : else
7132 81064 : selectDumpableTable(&tblinfo[i], fout);
7133 :
7134 : /*
7135 : * Now, consider the table "interesting" if we need to dump its
7136 : * definition or its data. Later on, we'll skip a lot of data
7137 : * collection for uninteresting tables.
7138 : *
7139 : * Note: the "interesting" flag will also be set by flagInhTables for
7140 : * parents of interesting tables, so that we collect necessary
7141 : * inheritance info even when the parents are not themselves being
7142 : * dumped. This is the main reason why we need an "interesting" flag
7143 : * that's separate from the components-to-dump bitmask.
7144 : */
7145 81426 : tblinfo[i].interesting = (tblinfo[i].dobj.dump &
7146 : (DUMP_COMPONENT_DEFINITION |
7147 81426 : DUMP_COMPONENT_DATA)) != 0;
7148 :
7149 81426 : tblinfo[i].dummy_view = false; /* might get set during sort */
7150 81426 : tblinfo[i].postponed_def = false; /* might get set during sort */
7151 :
7152 : /* Tables have data */
7153 81426 : tblinfo[i].dobj.components |= DUMP_COMPONENT_DATA;
7154 :
7155 : /* Mark whether table has an ACL */
7156 81426 : if (!PQgetisnull(res, i, i_relacl))
7157 64352 : tblinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
7158 81426 : tblinfo[i].hascolumnACLs = false; /* may get set later */
7159 :
7160 : /*
7161 : * Read-lock target tables to make sure they aren't DROPPED or altered
7162 : * in schema before we get around to dumping them.
7163 : *
7164 : * Note that we don't explicitly lock parents of the target tables; we
7165 : * assume our lock on the child is enough to prevent schema
7166 : * alterations to parent tables.
7167 : *
7168 : * NOTE: it'd be kinda nice to lock other relations too, not only
7169 : * plain or partitioned tables, but the backend doesn't presently
7170 : * allow that.
7171 : *
7172 : * We only need to lock the table for certain components; see
7173 : * pg_dump.h
7174 : */
7175 81426 : if ((tblinfo[i].dobj.dump & DUMP_COMPONENTS_REQUIRING_LOCK) &&
7176 12250 : (tblinfo[i].relkind == RELKIND_RELATION ||
7177 3626 : tblinfo[i].relkind == RELKIND_PARTITIONED_TABLE))
7178 : {
7179 : /*
7180 : * Tables are locked in batches. When dumping from a remote
7181 : * server this can save a significant amount of time by reducing
7182 : * the number of round trips.
7183 : */
7184 9684 : if (query->len == 0)
7185 198 : appendPQExpBuffer(query, "LOCK TABLE %s",
7186 198 : fmtQualifiedDumpable(&tblinfo[i]));
7187 : else
7188 : {
7189 9486 : appendPQExpBuffer(query, ", %s",
7190 9486 : fmtQualifiedDumpable(&tblinfo[i]));
7191 :
7192 : /* Arbitrarily end a batch when query length reaches 100K. */
7193 9486 : if (query->len >= 100000)
7194 : {
7195 : /* Lock another batch of tables. */
7196 0 : appendPQExpBufferStr(query, " IN ACCESS SHARE MODE");
7197 0 : ExecuteSqlStatement(fout, query->data);
7198 0 : resetPQExpBuffer(query);
7199 : }
7200 : }
7201 : }
7202 : }
7203 :
7204 310 : if (query->len != 0)
7205 : {
7206 : /* Lock the tables in the last batch. */
7207 198 : appendPQExpBufferStr(query, " IN ACCESS SHARE MODE");
7208 198 : ExecuteSqlStatement(fout, query->data);
7209 : }
7210 :
7211 308 : if (dopt->lockWaitTimeout)
7212 : {
7213 4 : ExecuteSqlStatement(fout, "SET statement_timeout = 0");
7214 : }
7215 :
7216 308 : PQclear(res);
7217 :
7218 308 : destroyPQExpBuffer(query);
7219 :
7220 308 : return tblinfo;
7221 : }
7222 :
7223 : /*
7224 : * getOwnedSeqs
7225 : * identify owned sequences and mark them as dumpable if owning table is
7226 : *
7227 : * We used to do this in getTables(), but it's better to do it after the
7228 : * index used by findTableByOid() has been set up.
7229 : */
7230 : void
7231 308 : getOwnedSeqs(Archive *fout, TableInfo tblinfo[], int numTables)
7232 : {
7233 : int i;
7234 :
7235 : /*
7236 : * Force sequences that are "owned" by table columns to be dumped whenever
7237 : * their owning table is being dumped.
7238 : */
7239 81216 : for (i = 0; i < numTables; i++)
7240 : {
7241 80908 : TableInfo *seqinfo = &tblinfo[i];
7242 : TableInfo *owning_tab;
7243 :
7244 80908 : if (!OidIsValid(seqinfo->owning_tab))
7245 80166 : continue; /* not an owned sequence */
7246 :
7247 742 : owning_tab = findTableByOid(seqinfo->owning_tab);
7248 742 : if (owning_tab == NULL)
7249 0 : pg_fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
7250 : seqinfo->owning_tab, seqinfo->dobj.catId.oid);
7251 :
7252 : /*
7253 : * Only dump identity sequences if we're going to dump the table that
7254 : * it belongs to.
7255 : */
7256 742 : if (owning_tab->dobj.dump == DUMP_COMPONENT_NONE &&
7257 176 : seqinfo->is_identity_sequence)
7258 : {
7259 102 : seqinfo->dobj.dump = DUMP_COMPONENT_NONE;
7260 102 : continue;
7261 : }
7262 :
7263 : /*
7264 : * Otherwise we need to dump the components that are being dumped for
7265 : * the table and any components which the sequence is explicitly
7266 : * marked with.
7267 : *
7268 : * We can't simply use the set of components which are being dumped
7269 : * for the table as the table might be in an extension (and only the
7270 : * non-extension components, eg: ACLs if changed, security labels, and
7271 : * policies, are being dumped) while the sequence is not (and
7272 : * therefore the definition and other components should also be
7273 : * dumped).
7274 : *
7275 : * If the sequence is part of the extension then it should be properly
7276 : * marked by checkExtensionMembership() and this will be a no-op as
7277 : * the table will be equivalently marked.
7278 : */
7279 640 : seqinfo->dobj.dump = seqinfo->dobj.dump | owning_tab->dobj.dump;
7280 :
7281 640 : if (seqinfo->dobj.dump != DUMP_COMPONENT_NONE)
7282 570 : seqinfo->interesting = true;
7283 : }
7284 308 : }
7285 :
7286 : /*
7287 : * getInherits
7288 : * read all the inheritance information
7289 : * from the system catalogs return them in the InhInfo* structure
7290 : *
7291 : * numInherits is set to the number of pairs read in
7292 : */
7293 : InhInfo *
7294 308 : getInherits(Archive *fout, int *numInherits)
7295 : {
7296 : PGresult *res;
7297 : int ntups;
7298 : int i;
7299 308 : PQExpBuffer query = createPQExpBuffer();
7300 : InhInfo *inhinfo;
7301 :
7302 : int i_inhrelid;
7303 : int i_inhparent;
7304 :
7305 : /* find all the inheritance information */
7306 308 : appendPQExpBufferStr(query, "SELECT inhrelid, inhparent FROM pg_inherits");
7307 :
7308 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7309 :
7310 308 : ntups = PQntuples(res);
7311 :
7312 308 : *numInherits = ntups;
7313 :
7314 308 : inhinfo = (InhInfo *) pg_malloc(ntups * sizeof(InhInfo));
7315 :
7316 308 : i_inhrelid = PQfnumber(res, "inhrelid");
7317 308 : i_inhparent = PQfnumber(res, "inhparent");
7318 :
7319 6096 : for (i = 0; i < ntups; i++)
7320 : {
7321 5788 : inhinfo[i].inhrelid = atooid(PQgetvalue(res, i, i_inhrelid));
7322 5788 : inhinfo[i].inhparent = atooid(PQgetvalue(res, i, i_inhparent));
7323 : }
7324 :
7325 308 : PQclear(res);
7326 :
7327 308 : destroyPQExpBuffer(query);
7328 :
7329 308 : return inhinfo;
7330 : }
7331 :
7332 : /*
7333 : * getPartitioningInfo
7334 : * get information about partitioning
7335 : *
7336 : * For the most part, we only collect partitioning info about tables we
7337 : * intend to dump. However, this function has to consider all partitioned
7338 : * tables in the database, because we need to know about parents of partitions
7339 : * we are going to dump even if the parents themselves won't be dumped.
7340 : *
7341 : * Specifically, what we need to know is whether each partitioned table
7342 : * has an "unsafe" partitioning scheme that requires us to force
7343 : * load-via-partition-root mode for its children. Currently the only case
7344 : * for which we force that is hash partitioning on enum columns, since the
7345 : * hash codes depend on enum value OIDs which won't be replicated across
7346 : * dump-and-reload. There are other cases in which load-via-partition-root
7347 : * might be necessary, but we expect users to cope with them.
7348 : */
7349 : void
7350 308 : getPartitioningInfo(Archive *fout)
7351 : {
7352 : PQExpBuffer query;
7353 : PGresult *res;
7354 : int ntups;
7355 :
7356 : /* hash partitioning didn't exist before v11 */
7357 308 : if (fout->remoteVersion < 110000)
7358 0 : return;
7359 : /* needn't bother if schema-only dump */
7360 308 : if (fout->dopt->schemaOnly)
7361 32 : return;
7362 :
7363 276 : query = createPQExpBuffer();
7364 :
7365 : /*
7366 : * Unsafe partitioning schemes are exactly those for which hash enum_ops
7367 : * appears among the partition opclasses. We needn't check partstrat.
7368 : *
7369 : * Note that this query may well retrieve info about tables we aren't
7370 : * going to dump and hence have no lock on. That's okay since we need not
7371 : * invoke any unsafe server-side functions.
7372 : */
7373 276 : appendPQExpBufferStr(query,
7374 : "SELECT partrelid FROM pg_partitioned_table WHERE\n"
7375 : "(SELECT c.oid FROM pg_opclass c JOIN pg_am a "
7376 : "ON c.opcmethod = a.oid\n"
7377 : "WHERE opcname = 'enum_ops' "
7378 : "AND opcnamespace = 'pg_catalog'::regnamespace "
7379 : "AND amname = 'hash') = ANY(partclass)");
7380 :
7381 276 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7382 :
7383 276 : ntups = PQntuples(res);
7384 :
7385 280 : for (int i = 0; i < ntups; i++)
7386 : {
7387 4 : Oid tabrelid = atooid(PQgetvalue(res, i, 0));
7388 : TableInfo *tbinfo;
7389 :
7390 4 : tbinfo = findTableByOid(tabrelid);
7391 4 : if (tbinfo == NULL)
7392 0 : pg_fatal("failed sanity check, table OID %u appearing in pg_partitioned_table not found",
7393 : tabrelid);
7394 4 : tbinfo->unsafe_partitions = true;
7395 : }
7396 :
7397 276 : PQclear(res);
7398 :
7399 276 : destroyPQExpBuffer(query);
7400 : }
7401 :
7402 : /*
7403 : * getIndexes
7404 : * get information about every index on a dumpable table
7405 : *
7406 : * Note: index data is not returned directly to the caller, but it
7407 : * does get entered into the DumpableObject tables.
7408 : */
7409 : void
7410 308 : getIndexes(Archive *fout, TableInfo tblinfo[], int numTables)
7411 : {
7412 308 : PQExpBuffer query = createPQExpBuffer();
7413 308 : PQExpBuffer tbloids = createPQExpBuffer();
7414 : PGresult *res;
7415 : int ntups;
7416 : int curtblindx;
7417 : IndxInfo *indxinfo;
7418 : int i_tableoid,
7419 : i_oid,
7420 : i_indrelid,
7421 : i_indexname,
7422 : i_parentidx,
7423 : i_indexdef,
7424 : i_indnkeyatts,
7425 : i_indnatts,
7426 : i_indkey,
7427 : i_indisclustered,
7428 : i_indisreplident,
7429 : i_indnullsnotdistinct,
7430 : i_contype,
7431 : i_conname,
7432 : i_condeferrable,
7433 : i_condeferred,
7434 : i_conperiod,
7435 : i_contableoid,
7436 : i_conoid,
7437 : i_condef,
7438 : i_tablespace,
7439 : i_indreloptions,
7440 : i_indstatcols,
7441 : i_indstatvals;
7442 :
7443 : /*
7444 : * We want to perform just one query against pg_index. However, we
7445 : * mustn't try to select every row of the catalog and then sort it out on
7446 : * the client side, because some of the server-side functions we need
7447 : * would be unsafe to apply to tables we don't have lock on. Hence, we
7448 : * build an array of the OIDs of tables we care about (and now have lock
7449 : * on!), and use a WHERE clause to constrain which rows are selected.
7450 : */
7451 308 : appendPQExpBufferChar(tbloids, '{');
7452 81216 : for (int i = 0; i < numTables; i++)
7453 : {
7454 80908 : TableInfo *tbinfo = &tblinfo[i];
7455 :
7456 80908 : if (!tbinfo->hasindex)
7457 56966 : continue;
7458 :
7459 : /*
7460 : * We can ignore indexes of uninteresting tables.
7461 : */
7462 23942 : if (!tbinfo->interesting)
7463 20364 : continue;
7464 :
7465 : /* OK, we need info for this table */
7466 3578 : if (tbloids->len > 1) /* do we have more than the '{'? */
7467 3426 : appendPQExpBufferChar(tbloids, ',');
7468 3578 : appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
7469 : }
7470 308 : appendPQExpBufferChar(tbloids, '}');
7471 :
7472 308 : appendPQExpBufferStr(query,
7473 : "SELECT t.tableoid, t.oid, i.indrelid, "
7474 : "t.relname AS indexname, "
7475 : "pg_catalog.pg_get_indexdef(i.indexrelid) AS indexdef, "
7476 : "i.indkey, i.indisclustered, "
7477 : "c.contype, c.conname, "
7478 : "c.condeferrable, c.condeferred, "
7479 : "c.tableoid AS contableoid, "
7480 : "c.oid AS conoid, "
7481 : "pg_catalog.pg_get_constraintdef(c.oid, false) AS condef, "
7482 : "(SELECT spcname FROM pg_catalog.pg_tablespace s WHERE s.oid = t.reltablespace) AS tablespace, "
7483 : "t.reloptions AS indreloptions, ");
7484 :
7485 :
7486 308 : if (fout->remoteVersion >= 90400)
7487 308 : appendPQExpBufferStr(query,
7488 : "i.indisreplident, ");
7489 : else
7490 0 : appendPQExpBufferStr(query,
7491 : "false AS indisreplident, ");
7492 :
7493 308 : if (fout->remoteVersion >= 110000)
7494 308 : appendPQExpBufferStr(query,
7495 : "inh.inhparent AS parentidx, "
7496 : "i.indnkeyatts AS indnkeyatts, "
7497 : "i.indnatts AS indnatts, "
7498 : "(SELECT pg_catalog.array_agg(attnum ORDER BY attnum) "
7499 : " FROM pg_catalog.pg_attribute "
7500 : " WHERE attrelid = i.indexrelid AND "
7501 : " attstattarget >= 0) AS indstatcols, "
7502 : "(SELECT pg_catalog.array_agg(attstattarget ORDER BY attnum) "
7503 : " FROM pg_catalog.pg_attribute "
7504 : " WHERE attrelid = i.indexrelid AND "
7505 : " attstattarget >= 0) AS indstatvals, ");
7506 : else
7507 0 : appendPQExpBufferStr(query,
7508 : "0 AS parentidx, "
7509 : "i.indnatts AS indnkeyatts, "
7510 : "i.indnatts AS indnatts, "
7511 : "'' AS indstatcols, "
7512 : "'' AS indstatvals, ");
7513 :
7514 308 : if (fout->remoteVersion >= 150000)
7515 308 : appendPQExpBufferStr(query,
7516 : "i.indnullsnotdistinct, ");
7517 : else
7518 0 : appendPQExpBufferStr(query,
7519 : "false AS indnullsnotdistinct, ");
7520 :
7521 308 : if (fout->remoteVersion >= 180000)
7522 308 : appendPQExpBufferStr(query,
7523 : "c.conperiod ");
7524 : else
7525 0 : appendPQExpBufferStr(query,
7526 : "NULL AS conperiod ");
7527 :
7528 : /*
7529 : * The point of the messy-looking outer join is to find a constraint that
7530 : * is related by an internal dependency link to the index. If we find one,
7531 : * create a CONSTRAINT entry linked to the INDEX entry. We assume an
7532 : * index won't have more than one internal dependency.
7533 : *
7534 : * Note: the check on conrelid is redundant, but useful because that
7535 : * column is indexed while conindid is not.
7536 : */
7537 308 : if (fout->remoteVersion >= 110000)
7538 : {
7539 308 : appendPQExpBuffer(query,
7540 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
7541 : "JOIN pg_catalog.pg_index i ON (src.tbloid = i.indrelid) "
7542 : "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7543 : "JOIN pg_catalog.pg_class t2 ON (t2.oid = i.indrelid) "
7544 : "LEFT JOIN pg_catalog.pg_constraint c "
7545 : "ON (i.indrelid = c.conrelid AND "
7546 : "i.indexrelid = c.conindid AND "
7547 : "c.contype IN ('p','u','x')) "
7548 : "LEFT JOIN pg_catalog.pg_inherits inh "
7549 : "ON (inh.inhrelid = indexrelid) "
7550 : "WHERE (i.indisvalid OR t2.relkind = 'p') "
7551 : "AND i.indisready "
7552 : "ORDER BY i.indrelid, indexname",
7553 : tbloids->data);
7554 : }
7555 : else
7556 : {
7557 : /*
7558 : * the test on indisready is necessary in 9.2, and harmless in
7559 : * earlier/later versions
7560 : */
7561 0 : appendPQExpBuffer(query,
7562 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
7563 : "JOIN pg_catalog.pg_index i ON (src.tbloid = i.indrelid) "
7564 : "JOIN pg_catalog.pg_class t ON (t.oid = i.indexrelid) "
7565 : "LEFT JOIN pg_catalog.pg_constraint c "
7566 : "ON (i.indrelid = c.conrelid AND "
7567 : "i.indexrelid = c.conindid AND "
7568 : "c.contype IN ('p','u','x')) "
7569 : "WHERE i.indisvalid AND i.indisready "
7570 : "ORDER BY i.indrelid, indexname",
7571 : tbloids->data);
7572 : }
7573 :
7574 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7575 :
7576 308 : ntups = PQntuples(res);
7577 :
7578 308 : i_tableoid = PQfnumber(res, "tableoid");
7579 308 : i_oid = PQfnumber(res, "oid");
7580 308 : i_indrelid = PQfnumber(res, "indrelid");
7581 308 : i_indexname = PQfnumber(res, "indexname");
7582 308 : i_parentidx = PQfnumber(res, "parentidx");
7583 308 : i_indexdef = PQfnumber(res, "indexdef");
7584 308 : i_indnkeyatts = PQfnumber(res, "indnkeyatts");
7585 308 : i_indnatts = PQfnumber(res, "indnatts");
7586 308 : i_indkey = PQfnumber(res, "indkey");
7587 308 : i_indisclustered = PQfnumber(res, "indisclustered");
7588 308 : i_indisreplident = PQfnumber(res, "indisreplident");
7589 308 : i_indnullsnotdistinct = PQfnumber(res, "indnullsnotdistinct");
7590 308 : i_contype = PQfnumber(res, "contype");
7591 308 : i_conname = PQfnumber(res, "conname");
7592 308 : i_condeferrable = PQfnumber(res, "condeferrable");
7593 308 : i_condeferred = PQfnumber(res, "condeferred");
7594 308 : i_conperiod = PQfnumber(res, "conperiod");
7595 308 : i_contableoid = PQfnumber(res, "contableoid");
7596 308 : i_conoid = PQfnumber(res, "conoid");
7597 308 : i_condef = PQfnumber(res, "condef");
7598 308 : i_tablespace = PQfnumber(res, "tablespace");
7599 308 : i_indreloptions = PQfnumber(res, "indreloptions");
7600 308 : i_indstatcols = PQfnumber(res, "indstatcols");
7601 308 : i_indstatvals = PQfnumber(res, "indstatvals");
7602 :
7603 308 : indxinfo = (IndxInfo *) pg_malloc(ntups * sizeof(IndxInfo));
7604 :
7605 : /*
7606 : * Outer loop iterates once per table, not once per row. Incrementing of
7607 : * j is handled by the inner loop.
7608 : */
7609 308 : curtblindx = -1;
7610 3878 : for (int j = 0; j < ntups;)
7611 : {
7612 3570 : Oid indrelid = atooid(PQgetvalue(res, j, i_indrelid));
7613 3570 : TableInfo *tbinfo = NULL;
7614 : int numinds;
7615 :
7616 : /* Count rows for this table */
7617 4752 : for (numinds = 1; numinds < ntups - j; numinds++)
7618 4600 : if (atooid(PQgetvalue(res, j + numinds, i_indrelid)) != indrelid)
7619 3418 : break;
7620 :
7621 : /*
7622 : * Locate the associated TableInfo; we rely on tblinfo[] being in OID
7623 : * order.
7624 : */
7625 43166 : while (++curtblindx < numTables)
7626 : {
7627 43166 : tbinfo = &tblinfo[curtblindx];
7628 43166 : if (tbinfo->dobj.catId.oid == indrelid)
7629 3570 : break;
7630 : }
7631 3570 : if (curtblindx >= numTables)
7632 0 : pg_fatal("unrecognized table OID %u", indrelid);
7633 : /* cross-check that we only got requested tables */
7634 3570 : if (!tbinfo->hasindex ||
7635 3570 : !tbinfo->interesting)
7636 0 : pg_fatal("unexpected index data for table \"%s\"",
7637 : tbinfo->dobj.name);
7638 :
7639 : /* Save data for this table */
7640 3570 : tbinfo->indexes = indxinfo + j;
7641 3570 : tbinfo->numIndexes = numinds;
7642 :
7643 8322 : for (int c = 0; c < numinds; c++, j++)
7644 : {
7645 : char contype;
7646 :
7647 4752 : indxinfo[j].dobj.objType = DO_INDEX;
7648 4752 : indxinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
7649 4752 : indxinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
7650 4752 : AssignDumpId(&indxinfo[j].dobj);
7651 4752 : indxinfo[j].dobj.dump = tbinfo->dobj.dump;
7652 4752 : indxinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_indexname));
7653 4752 : indxinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7654 4752 : indxinfo[j].indextable = tbinfo;
7655 4752 : indxinfo[j].indexdef = pg_strdup(PQgetvalue(res, j, i_indexdef));
7656 4752 : indxinfo[j].indnkeyattrs = atoi(PQgetvalue(res, j, i_indnkeyatts));
7657 4752 : indxinfo[j].indnattrs = atoi(PQgetvalue(res, j, i_indnatts));
7658 4752 : indxinfo[j].tablespace = pg_strdup(PQgetvalue(res, j, i_tablespace));
7659 4752 : indxinfo[j].indreloptions = pg_strdup(PQgetvalue(res, j, i_indreloptions));
7660 4752 : indxinfo[j].indstatcols = pg_strdup(PQgetvalue(res, j, i_indstatcols));
7661 4752 : indxinfo[j].indstatvals = pg_strdup(PQgetvalue(res, j, i_indstatvals));
7662 4752 : indxinfo[j].indkeys = (Oid *) pg_malloc(indxinfo[j].indnattrs * sizeof(Oid));
7663 4752 : parseOidArray(PQgetvalue(res, j, i_indkey),
7664 4752 : indxinfo[j].indkeys, indxinfo[j].indnattrs);
7665 4752 : indxinfo[j].indisclustered = (PQgetvalue(res, j, i_indisclustered)[0] == 't');
7666 4752 : indxinfo[j].indisreplident = (PQgetvalue(res, j, i_indisreplident)[0] == 't');
7667 4752 : indxinfo[j].indnullsnotdistinct = (PQgetvalue(res, j, i_indnullsnotdistinct)[0] == 't');
7668 4752 : indxinfo[j].parentidx = atooid(PQgetvalue(res, j, i_parentidx));
7669 4752 : indxinfo[j].partattaches = (SimplePtrList)
7670 : {
7671 : NULL, NULL
7672 : };
7673 4752 : contype = *(PQgetvalue(res, j, i_contype));
7674 :
7675 4752 : if (contype == 'p' || contype == 'u' || contype == 'x')
7676 2750 : {
7677 : /*
7678 : * If we found a constraint matching the index, create an
7679 : * entry for it.
7680 : */
7681 : ConstraintInfo *constrinfo;
7682 :
7683 2750 : constrinfo = (ConstraintInfo *) pg_malloc(sizeof(ConstraintInfo));
7684 2750 : constrinfo->dobj.objType = DO_CONSTRAINT;
7685 2750 : constrinfo->dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7686 2750 : constrinfo->dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7687 2750 : AssignDumpId(&constrinfo->dobj);
7688 2750 : constrinfo->dobj.dump = tbinfo->dobj.dump;
7689 2750 : constrinfo->dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7690 2750 : constrinfo->dobj.namespace = tbinfo->dobj.namespace;
7691 2750 : constrinfo->contable = tbinfo;
7692 2750 : constrinfo->condomain = NULL;
7693 2750 : constrinfo->contype = contype;
7694 2750 : if (contype == 'x')
7695 20 : constrinfo->condef = pg_strdup(PQgetvalue(res, j, i_condef));
7696 : else
7697 2730 : constrinfo->condef = NULL;
7698 2750 : constrinfo->confrelid = InvalidOid;
7699 2750 : constrinfo->conindex = indxinfo[j].dobj.dumpId;
7700 2750 : constrinfo->condeferrable = *(PQgetvalue(res, j, i_condeferrable)) == 't';
7701 2750 : constrinfo->condeferred = *(PQgetvalue(res, j, i_condeferred)) == 't';
7702 2750 : constrinfo->conperiod = *(PQgetvalue(res, j, i_conperiod)) == 't';
7703 2750 : constrinfo->conislocal = true;
7704 2750 : constrinfo->separate = true;
7705 :
7706 2750 : indxinfo[j].indexconstraint = constrinfo->dobj.dumpId;
7707 : }
7708 : else
7709 : {
7710 : /* Plain secondary index */
7711 2002 : indxinfo[j].indexconstraint = 0;
7712 : }
7713 : }
7714 : }
7715 :
7716 308 : PQclear(res);
7717 :
7718 308 : destroyPQExpBuffer(query);
7719 308 : destroyPQExpBuffer(tbloids);
7720 308 : }
7721 :
7722 : /*
7723 : * getExtendedStatistics
7724 : * get information about extended-statistics objects.
7725 : *
7726 : * Note: extended statistics data is not returned directly to the caller, but
7727 : * it does get entered into the DumpableObject tables.
7728 : */
7729 : void
7730 308 : getExtendedStatistics(Archive *fout)
7731 : {
7732 : PQExpBuffer query;
7733 : PGresult *res;
7734 : StatsExtInfo *statsextinfo;
7735 : int ntups;
7736 : int i_tableoid;
7737 : int i_oid;
7738 : int i_stxname;
7739 : int i_stxnamespace;
7740 : int i_stxowner;
7741 : int i_stxrelid;
7742 : int i_stattarget;
7743 : int i;
7744 :
7745 : /* Extended statistics were new in v10 */
7746 308 : if (fout->remoteVersion < 100000)
7747 0 : return;
7748 :
7749 308 : query = createPQExpBuffer();
7750 :
7751 308 : if (fout->remoteVersion < 130000)
7752 0 : appendPQExpBufferStr(query, "SELECT tableoid, oid, stxname, "
7753 : "stxnamespace, stxowner, stxrelid, NULL AS stxstattarget "
7754 : "FROM pg_catalog.pg_statistic_ext");
7755 : else
7756 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, stxname, "
7757 : "stxnamespace, stxowner, stxrelid, stxstattarget "
7758 : "FROM pg_catalog.pg_statistic_ext");
7759 :
7760 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7761 :
7762 308 : ntups = PQntuples(res);
7763 :
7764 308 : i_tableoid = PQfnumber(res, "tableoid");
7765 308 : i_oid = PQfnumber(res, "oid");
7766 308 : i_stxname = PQfnumber(res, "stxname");
7767 308 : i_stxnamespace = PQfnumber(res, "stxnamespace");
7768 308 : i_stxowner = PQfnumber(res, "stxowner");
7769 308 : i_stxrelid = PQfnumber(res, "stxrelid");
7770 308 : i_stattarget = PQfnumber(res, "stxstattarget");
7771 :
7772 308 : statsextinfo = (StatsExtInfo *) pg_malloc(ntups * sizeof(StatsExtInfo));
7773 :
7774 622 : for (i = 0; i < ntups; i++)
7775 : {
7776 314 : statsextinfo[i].dobj.objType = DO_STATSEXT;
7777 314 : statsextinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
7778 314 : statsextinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
7779 314 : AssignDumpId(&statsextinfo[i].dobj);
7780 314 : statsextinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_stxname));
7781 628 : statsextinfo[i].dobj.namespace =
7782 314 : findNamespace(atooid(PQgetvalue(res, i, i_stxnamespace)));
7783 314 : statsextinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_stxowner));
7784 628 : statsextinfo[i].stattable =
7785 314 : findTableByOid(atooid(PQgetvalue(res, i, i_stxrelid)));
7786 314 : if (PQgetisnull(res, i, i_stattarget))
7787 228 : statsextinfo[i].stattarget = -1;
7788 : else
7789 86 : statsextinfo[i].stattarget = atoi(PQgetvalue(res, i, i_stattarget));
7790 :
7791 : /* Decide whether we want to dump it */
7792 314 : selectDumpableStatisticsObject(&(statsextinfo[i]), fout);
7793 : }
7794 :
7795 308 : PQclear(res);
7796 308 : destroyPQExpBuffer(query);
7797 : }
7798 :
7799 : /*
7800 : * getConstraints
7801 : *
7802 : * Get info about constraints on dumpable tables.
7803 : *
7804 : * Currently handles foreign keys only.
7805 : * Unique and primary key constraints are handled with indexes,
7806 : * while check constraints are processed in getTableAttrs().
7807 : */
7808 : void
7809 308 : getConstraints(Archive *fout, TableInfo tblinfo[], int numTables)
7810 : {
7811 308 : PQExpBuffer query = createPQExpBuffer();
7812 308 : PQExpBuffer tbloids = createPQExpBuffer();
7813 : PGresult *res;
7814 : int ntups;
7815 : int curtblindx;
7816 308 : TableInfo *tbinfo = NULL;
7817 : ConstraintInfo *constrinfo;
7818 : int i_contableoid,
7819 : i_conoid,
7820 : i_conrelid,
7821 : i_conname,
7822 : i_confrelid,
7823 : i_conindid,
7824 : i_condef;
7825 :
7826 : /*
7827 : * We want to perform just one query against pg_constraint. However, we
7828 : * mustn't try to select every row of the catalog and then sort it out on
7829 : * the client side, because some of the server-side functions we need
7830 : * would be unsafe to apply to tables we don't have lock on. Hence, we
7831 : * build an array of the OIDs of tables we care about (and now have lock
7832 : * on!), and use a WHERE clause to constrain which rows are selected.
7833 : */
7834 308 : appendPQExpBufferChar(tbloids, '{');
7835 81216 : for (int i = 0; i < numTables; i++)
7836 : {
7837 80908 : TableInfo *tinfo = &tblinfo[i];
7838 :
7839 : /*
7840 : * For partitioned tables, foreign keys have no triggers so they must
7841 : * be included anyway in case some foreign keys are defined.
7842 : */
7843 80908 : if ((!tinfo->hastriggers &&
7844 78726 : tinfo->relkind != RELKIND_PARTITIONED_TABLE) ||
7845 3134 : !(tinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
7846 78552 : continue;
7847 :
7848 : /* OK, we need info for this table */
7849 2356 : if (tbloids->len > 1) /* do we have more than the '{'? */
7850 2254 : appendPQExpBufferChar(tbloids, ',');
7851 2356 : appendPQExpBuffer(tbloids, "%u", tinfo->dobj.catId.oid);
7852 : }
7853 308 : appendPQExpBufferChar(tbloids, '}');
7854 :
7855 308 : appendPQExpBufferStr(query,
7856 : "SELECT c.tableoid, c.oid, "
7857 : "conrelid, conname, confrelid, ");
7858 308 : if (fout->remoteVersion >= 110000)
7859 308 : appendPQExpBufferStr(query, "conindid, ");
7860 : else
7861 0 : appendPQExpBufferStr(query, "0 AS conindid, ");
7862 308 : appendPQExpBuffer(query,
7863 : "pg_catalog.pg_get_constraintdef(c.oid) AS condef\n"
7864 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
7865 : "JOIN pg_catalog.pg_constraint c ON (src.tbloid = c.conrelid)\n"
7866 : "WHERE contype = 'f' ",
7867 : tbloids->data);
7868 308 : if (fout->remoteVersion >= 110000)
7869 308 : appendPQExpBufferStr(query,
7870 : "AND conparentid = 0 ");
7871 308 : appendPQExpBufferStr(query,
7872 : "ORDER BY conrelid, conname");
7873 :
7874 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
7875 :
7876 308 : ntups = PQntuples(res);
7877 :
7878 308 : i_contableoid = PQfnumber(res, "tableoid");
7879 308 : i_conoid = PQfnumber(res, "oid");
7880 308 : i_conrelid = PQfnumber(res, "conrelid");
7881 308 : i_conname = PQfnumber(res, "conname");
7882 308 : i_confrelid = PQfnumber(res, "confrelid");
7883 308 : i_conindid = PQfnumber(res, "conindid");
7884 308 : i_condef = PQfnumber(res, "condef");
7885 :
7886 308 : constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
7887 :
7888 308 : curtblindx = -1;
7889 652 : for (int j = 0; j < ntups; j++)
7890 : {
7891 344 : Oid conrelid = atooid(PQgetvalue(res, j, i_conrelid));
7892 : TableInfo *reftable;
7893 :
7894 : /*
7895 : * Locate the associated TableInfo; we rely on tblinfo[] being in OID
7896 : * order.
7897 : */
7898 344 : if (tbinfo == NULL || tbinfo->dobj.catId.oid != conrelid)
7899 : {
7900 25118 : while (++curtblindx < numTables)
7901 : {
7902 25118 : tbinfo = &tblinfo[curtblindx];
7903 25118 : if (tbinfo->dobj.catId.oid == conrelid)
7904 324 : break;
7905 : }
7906 324 : if (curtblindx >= numTables)
7907 0 : pg_fatal("unrecognized table OID %u", conrelid);
7908 : }
7909 :
7910 344 : constrinfo[j].dobj.objType = DO_FK_CONSTRAINT;
7911 344 : constrinfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_contableoid));
7912 344 : constrinfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_conoid));
7913 344 : AssignDumpId(&constrinfo[j].dobj);
7914 344 : constrinfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
7915 344 : constrinfo[j].dobj.namespace = tbinfo->dobj.namespace;
7916 344 : constrinfo[j].contable = tbinfo;
7917 344 : constrinfo[j].condomain = NULL;
7918 344 : constrinfo[j].contype = 'f';
7919 344 : constrinfo[j].condef = pg_strdup(PQgetvalue(res, j, i_condef));
7920 344 : constrinfo[j].confrelid = atooid(PQgetvalue(res, j, i_confrelid));
7921 344 : constrinfo[j].conindex = 0;
7922 344 : constrinfo[j].condeferrable = false;
7923 344 : constrinfo[j].condeferred = false;
7924 344 : constrinfo[j].conislocal = true;
7925 344 : constrinfo[j].separate = true;
7926 :
7927 : /*
7928 : * Restoring an FK that points to a partitioned table requires that
7929 : * all partition indexes have been attached beforehand. Ensure that
7930 : * happens by making the constraint depend on each index partition
7931 : * attach object.
7932 : */
7933 344 : reftable = findTableByOid(constrinfo[j].confrelid);
7934 344 : if (reftable && reftable->relkind == RELKIND_PARTITIONED_TABLE)
7935 : {
7936 40 : Oid indexOid = atooid(PQgetvalue(res, j, i_conindid));
7937 :
7938 40 : if (indexOid != InvalidOid)
7939 : {
7940 40 : for (int k = 0; k < reftable->numIndexes; k++)
7941 : {
7942 : IndxInfo *refidx;
7943 :
7944 : /* not our index? */
7945 40 : if (reftable->indexes[k].dobj.catId.oid != indexOid)
7946 0 : continue;
7947 :
7948 40 : refidx = &reftable->indexes[k];
7949 40 : addConstrChildIdxDeps(&constrinfo[j].dobj, refidx);
7950 40 : break;
7951 : }
7952 : }
7953 : }
7954 : }
7955 :
7956 308 : PQclear(res);
7957 :
7958 308 : destroyPQExpBuffer(query);
7959 308 : destroyPQExpBuffer(tbloids);
7960 308 : }
7961 :
7962 : /*
7963 : * addConstrChildIdxDeps
7964 : *
7965 : * Recursive subroutine for getConstraints
7966 : *
7967 : * Given an object representing a foreign key constraint and an index on the
7968 : * partitioned table it references, mark the constraint object as dependent
7969 : * on the DO_INDEX_ATTACH object of each index partition, recursively
7970 : * drilling down to their partitions if any. This ensures that the FK is not
7971 : * restored until the index is fully marked valid.
7972 : */
7973 : static void
7974 90 : addConstrChildIdxDeps(DumpableObject *dobj, const IndxInfo *refidx)
7975 : {
7976 : SimplePtrListCell *cell;
7977 :
7978 : Assert(dobj->objType == DO_FK_CONSTRAINT);
7979 :
7980 310 : for (cell = refidx->partattaches.head; cell; cell = cell->next)
7981 : {
7982 220 : IndexAttachInfo *attach = (IndexAttachInfo *) cell->ptr;
7983 :
7984 220 : addObjectDependency(dobj, attach->dobj.dumpId);
7985 :
7986 220 : if (attach->partitionIdx->partattaches.head != NULL)
7987 50 : addConstrChildIdxDeps(dobj, attach->partitionIdx);
7988 : }
7989 90 : }
7990 :
7991 : /*
7992 : * getDomainConstraints
7993 : *
7994 : * Get info about constraints on a domain.
7995 : */
7996 : static void
7997 272 : getDomainConstraints(Archive *fout, TypeInfo *tyinfo)
7998 : {
7999 : int i;
8000 : ConstraintInfo *constrinfo;
8001 272 : PQExpBuffer query = createPQExpBuffer();
8002 : PGresult *res;
8003 : int i_tableoid,
8004 : i_oid,
8005 : i_conname,
8006 : i_consrc;
8007 : int ntups;
8008 :
8009 272 : if (!fout->is_prepared[PREPQUERY_GETDOMAINCONSTRAINTS])
8010 : {
8011 : /* Set up query for constraint-specific details */
8012 82 : appendPQExpBufferStr(query,
8013 : "PREPARE getDomainConstraints(pg_catalog.oid) AS\n"
8014 : "SELECT tableoid, oid, conname, "
8015 : "pg_catalog.pg_get_constraintdef(oid) AS consrc, "
8016 : "convalidated "
8017 : "FROM pg_catalog.pg_constraint "
8018 : "WHERE contypid = $1 AND contype = 'c' "
8019 : "ORDER BY conname");
8020 :
8021 82 : ExecuteSqlStatement(fout, query->data);
8022 :
8023 82 : fout->is_prepared[PREPQUERY_GETDOMAINCONSTRAINTS] = true;
8024 : }
8025 :
8026 272 : printfPQExpBuffer(query,
8027 : "EXECUTE getDomainConstraints('%u')",
8028 : tyinfo->dobj.catId.oid);
8029 :
8030 272 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8031 :
8032 272 : ntups = PQntuples(res);
8033 :
8034 272 : i_tableoid = PQfnumber(res, "tableoid");
8035 272 : i_oid = PQfnumber(res, "oid");
8036 272 : i_conname = PQfnumber(res, "conname");
8037 272 : i_consrc = PQfnumber(res, "consrc");
8038 :
8039 272 : constrinfo = (ConstraintInfo *) pg_malloc(ntups * sizeof(ConstraintInfo));
8040 :
8041 272 : tyinfo->nDomChecks = ntups;
8042 272 : tyinfo->domChecks = constrinfo;
8043 :
8044 454 : for (i = 0; i < ntups; i++)
8045 : {
8046 182 : bool validated = PQgetvalue(res, i, 4)[0] == 't';
8047 :
8048 182 : constrinfo[i].dobj.objType = DO_CONSTRAINT;
8049 182 : constrinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8050 182 : constrinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8051 182 : AssignDumpId(&constrinfo[i].dobj);
8052 182 : constrinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_conname));
8053 182 : constrinfo[i].dobj.namespace = tyinfo->dobj.namespace;
8054 182 : constrinfo[i].contable = NULL;
8055 182 : constrinfo[i].condomain = tyinfo;
8056 182 : constrinfo[i].contype = 'c';
8057 182 : constrinfo[i].condef = pg_strdup(PQgetvalue(res, i, i_consrc));
8058 182 : constrinfo[i].confrelid = InvalidOid;
8059 182 : constrinfo[i].conindex = 0;
8060 182 : constrinfo[i].condeferrable = false;
8061 182 : constrinfo[i].condeferred = false;
8062 182 : constrinfo[i].conislocal = true;
8063 :
8064 182 : constrinfo[i].separate = !validated;
8065 :
8066 : /*
8067 : * Make the domain depend on the constraint, ensuring it won't be
8068 : * output till any constraint dependencies are OK. If the constraint
8069 : * has not been validated, it's going to be dumped after the domain
8070 : * anyway, so this doesn't matter.
8071 : */
8072 182 : if (validated)
8073 182 : addObjectDependency(&tyinfo->dobj,
8074 182 : constrinfo[i].dobj.dumpId);
8075 : }
8076 :
8077 272 : PQclear(res);
8078 :
8079 272 : destroyPQExpBuffer(query);
8080 272 : }
8081 :
8082 : /*
8083 : * getRules
8084 : * get basic information about every rule in the system
8085 : */
8086 : void
8087 308 : getRules(Archive *fout)
8088 : {
8089 : PGresult *res;
8090 : int ntups;
8091 : int i;
8092 308 : PQExpBuffer query = createPQExpBuffer();
8093 : RuleInfo *ruleinfo;
8094 : int i_tableoid;
8095 : int i_oid;
8096 : int i_rulename;
8097 : int i_ruletable;
8098 : int i_ev_type;
8099 : int i_is_instead;
8100 : int i_ev_enabled;
8101 :
8102 308 : appendPQExpBufferStr(query, "SELECT "
8103 : "tableoid, oid, rulename, "
8104 : "ev_class AS ruletable, ev_type, is_instead, "
8105 : "ev_enabled "
8106 : "FROM pg_rewrite "
8107 : "ORDER BY oid");
8108 :
8109 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8110 :
8111 308 : ntups = PQntuples(res);
8112 :
8113 308 : ruleinfo = (RuleInfo *) pg_malloc(ntups * sizeof(RuleInfo));
8114 :
8115 308 : i_tableoid = PQfnumber(res, "tableoid");
8116 308 : i_oid = PQfnumber(res, "oid");
8117 308 : i_rulename = PQfnumber(res, "rulename");
8118 308 : i_ruletable = PQfnumber(res, "ruletable");
8119 308 : i_ev_type = PQfnumber(res, "ev_type");
8120 308 : i_is_instead = PQfnumber(res, "is_instead");
8121 308 : i_ev_enabled = PQfnumber(res, "ev_enabled");
8122 :
8123 47158 : for (i = 0; i < ntups; i++)
8124 : {
8125 : Oid ruletableoid;
8126 :
8127 46850 : ruleinfo[i].dobj.objType = DO_RULE;
8128 46850 : ruleinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8129 46850 : ruleinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8130 46850 : AssignDumpId(&ruleinfo[i].dobj);
8131 46850 : ruleinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_rulename));
8132 46850 : ruletableoid = atooid(PQgetvalue(res, i, i_ruletable));
8133 46850 : ruleinfo[i].ruletable = findTableByOid(ruletableoid);
8134 46850 : if (ruleinfo[i].ruletable == NULL)
8135 0 : pg_fatal("failed sanity check, parent table with OID %u of pg_rewrite entry with OID %u not found",
8136 : ruletableoid, ruleinfo[i].dobj.catId.oid);
8137 46850 : ruleinfo[i].dobj.namespace = ruleinfo[i].ruletable->dobj.namespace;
8138 46850 : ruleinfo[i].dobj.dump = ruleinfo[i].ruletable->dobj.dump;
8139 46850 : ruleinfo[i].ev_type = *(PQgetvalue(res, i, i_ev_type));
8140 46850 : ruleinfo[i].is_instead = *(PQgetvalue(res, i, i_is_instead)) == 't';
8141 46850 : ruleinfo[i].ev_enabled = *(PQgetvalue(res, i, i_ev_enabled));
8142 46850 : if (ruleinfo[i].ruletable)
8143 : {
8144 : /*
8145 : * If the table is a view or materialized view, force its ON
8146 : * SELECT rule to be sorted before the view itself --- this
8147 : * ensures that any dependencies for the rule affect the table's
8148 : * positioning. Other rules are forced to appear after their
8149 : * table.
8150 : */
8151 46850 : if ((ruleinfo[i].ruletable->relkind == RELKIND_VIEW ||
8152 1348 : ruleinfo[i].ruletable->relkind == RELKIND_MATVIEW) &&
8153 46388 : ruleinfo[i].ev_type == '1' && ruleinfo[i].is_instead)
8154 : {
8155 45688 : addObjectDependency(&ruleinfo[i].ruletable->dobj,
8156 45688 : ruleinfo[i].dobj.dumpId);
8157 : /* We'll merge the rule into CREATE VIEW, if possible */
8158 45688 : ruleinfo[i].separate = false;
8159 : }
8160 : else
8161 : {
8162 1162 : addObjectDependency(&ruleinfo[i].dobj,
8163 1162 : ruleinfo[i].ruletable->dobj.dumpId);
8164 1162 : ruleinfo[i].separate = true;
8165 : }
8166 : }
8167 : else
8168 0 : ruleinfo[i].separate = true;
8169 : }
8170 :
8171 308 : PQclear(res);
8172 :
8173 308 : destroyPQExpBuffer(query);
8174 308 : }
8175 :
8176 : /*
8177 : * getTriggers
8178 : * get information about every trigger on a dumpable table
8179 : *
8180 : * Note: trigger data is not returned directly to the caller, but it
8181 : * does get entered into the DumpableObject tables.
8182 : */
8183 : void
8184 308 : getTriggers(Archive *fout, TableInfo tblinfo[], int numTables)
8185 : {
8186 308 : PQExpBuffer query = createPQExpBuffer();
8187 308 : PQExpBuffer tbloids = createPQExpBuffer();
8188 : PGresult *res;
8189 : int ntups;
8190 : int curtblindx;
8191 : TriggerInfo *tginfo;
8192 : int i_tableoid,
8193 : i_oid,
8194 : i_tgrelid,
8195 : i_tgname,
8196 : i_tgenabled,
8197 : i_tgispartition,
8198 : i_tgdef;
8199 :
8200 : /*
8201 : * We want to perform just one query against pg_trigger. However, we
8202 : * mustn't try to select every row of the catalog and then sort it out on
8203 : * the client side, because some of the server-side functions we need
8204 : * would be unsafe to apply to tables we don't have lock on. Hence, we
8205 : * build an array of the OIDs of tables we care about (and now have lock
8206 : * on!), and use a WHERE clause to constrain which rows are selected.
8207 : */
8208 308 : appendPQExpBufferChar(tbloids, '{');
8209 81216 : for (int i = 0; i < numTables; i++)
8210 : {
8211 80908 : TableInfo *tbinfo = &tblinfo[i];
8212 :
8213 80908 : if (!tbinfo->hastriggers ||
8214 2182 : !(tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION))
8215 79246 : continue;
8216 :
8217 : /* OK, we need info for this table */
8218 1662 : if (tbloids->len > 1) /* do we have more than the '{'? */
8219 1564 : appendPQExpBufferChar(tbloids, ',');
8220 1662 : appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
8221 : }
8222 308 : appendPQExpBufferChar(tbloids, '}');
8223 :
8224 308 : if (fout->remoteVersion >= 150000)
8225 : {
8226 : /*
8227 : * NB: think not to use pretty=true in pg_get_triggerdef. It could
8228 : * result in non-forward-compatible dumps of WHEN clauses due to
8229 : * under-parenthesization.
8230 : *
8231 : * NB: We need to see partition triggers in case the tgenabled flag
8232 : * has been changed from the parent.
8233 : */
8234 308 : appendPQExpBuffer(query,
8235 : "SELECT t.tgrelid, t.tgname, "
8236 : "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8237 : "t.tgenabled, t.tableoid, t.oid, "
8238 : "t.tgparentid <> 0 AS tgispartition\n"
8239 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8240 : "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8241 : "LEFT JOIN pg_catalog.pg_trigger u ON (u.oid = t.tgparentid) "
8242 : "WHERE ((NOT t.tgisinternal AND t.tgparentid = 0) "
8243 : "OR t.tgenabled != u.tgenabled) "
8244 : "ORDER BY t.tgrelid, t.tgname",
8245 : tbloids->data);
8246 : }
8247 0 : else if (fout->remoteVersion >= 130000)
8248 : {
8249 : /*
8250 : * NB: think not to use pretty=true in pg_get_triggerdef. It could
8251 : * result in non-forward-compatible dumps of WHEN clauses due to
8252 : * under-parenthesization.
8253 : *
8254 : * NB: We need to see tgisinternal triggers in partitions, in case the
8255 : * tgenabled flag has been changed from the parent.
8256 : */
8257 0 : appendPQExpBuffer(query,
8258 : "SELECT t.tgrelid, t.tgname, "
8259 : "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8260 : "t.tgenabled, t.tableoid, t.oid, t.tgisinternal as tgispartition\n"
8261 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8262 : "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8263 : "LEFT JOIN pg_catalog.pg_trigger u ON (u.oid = t.tgparentid) "
8264 : "WHERE (NOT t.tgisinternal OR t.tgenabled != u.tgenabled) "
8265 : "ORDER BY t.tgrelid, t.tgname",
8266 : tbloids->data);
8267 : }
8268 0 : else if (fout->remoteVersion >= 110000)
8269 : {
8270 : /*
8271 : * NB: We need to see tgisinternal triggers in partitions, in case the
8272 : * tgenabled flag has been changed from the parent. No tgparentid in
8273 : * version 11-12, so we have to match them via pg_depend.
8274 : *
8275 : * See above about pretty=true in pg_get_triggerdef.
8276 : */
8277 0 : appendPQExpBuffer(query,
8278 : "SELECT t.tgrelid, t.tgname, "
8279 : "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8280 : "t.tgenabled, t.tableoid, t.oid, t.tgisinternal as tgispartition "
8281 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8282 : "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8283 : "LEFT JOIN pg_catalog.pg_depend AS d ON "
8284 : " d.classid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
8285 : " d.refclassid = 'pg_catalog.pg_trigger'::pg_catalog.regclass AND "
8286 : " d.objid = t.oid "
8287 : "LEFT JOIN pg_catalog.pg_trigger AS pt ON pt.oid = refobjid "
8288 : "WHERE (NOT t.tgisinternal OR t.tgenabled != pt.tgenabled) "
8289 : "ORDER BY t.tgrelid, t.tgname",
8290 : tbloids->data);
8291 : }
8292 : else
8293 : {
8294 : /* See above about pretty=true in pg_get_triggerdef */
8295 0 : appendPQExpBuffer(query,
8296 : "SELECT t.tgrelid, t.tgname, "
8297 : "pg_catalog.pg_get_triggerdef(t.oid, false) AS tgdef, "
8298 : "t.tgenabled, false as tgispartition, "
8299 : "t.tableoid, t.oid "
8300 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8301 : "JOIN pg_catalog.pg_trigger t ON (src.tbloid = t.tgrelid) "
8302 : "WHERE NOT tgisinternal "
8303 : "ORDER BY t.tgrelid, t.tgname",
8304 : tbloids->data);
8305 : }
8306 :
8307 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8308 :
8309 308 : ntups = PQntuples(res);
8310 :
8311 308 : i_tableoid = PQfnumber(res, "tableoid");
8312 308 : i_oid = PQfnumber(res, "oid");
8313 308 : i_tgrelid = PQfnumber(res, "tgrelid");
8314 308 : i_tgname = PQfnumber(res, "tgname");
8315 308 : i_tgenabled = PQfnumber(res, "tgenabled");
8316 308 : i_tgispartition = PQfnumber(res, "tgispartition");
8317 308 : i_tgdef = PQfnumber(res, "tgdef");
8318 :
8319 308 : tginfo = (TriggerInfo *) pg_malloc(ntups * sizeof(TriggerInfo));
8320 :
8321 : /*
8322 : * Outer loop iterates once per table, not once per row. Incrementing of
8323 : * j is handled by the inner loop.
8324 : */
8325 308 : curtblindx = -1;
8326 890 : for (int j = 0; j < ntups;)
8327 : {
8328 582 : Oid tgrelid = atooid(PQgetvalue(res, j, i_tgrelid));
8329 582 : TableInfo *tbinfo = NULL;
8330 : int numtrigs;
8331 :
8332 : /* Count rows for this table */
8333 986 : for (numtrigs = 1; numtrigs < ntups - j; numtrigs++)
8334 888 : if (atooid(PQgetvalue(res, j + numtrigs, i_tgrelid)) != tgrelid)
8335 484 : break;
8336 :
8337 : /*
8338 : * Locate the associated TableInfo; we rely on tblinfo[] being in OID
8339 : * order.
8340 : */
8341 30014 : while (++curtblindx < numTables)
8342 : {
8343 30014 : tbinfo = &tblinfo[curtblindx];
8344 30014 : if (tbinfo->dobj.catId.oid == tgrelid)
8345 582 : break;
8346 : }
8347 582 : if (curtblindx >= numTables)
8348 0 : pg_fatal("unrecognized table OID %u", tgrelid);
8349 :
8350 : /* Save data for this table */
8351 582 : tbinfo->triggers = tginfo + j;
8352 582 : tbinfo->numTriggers = numtrigs;
8353 :
8354 1568 : for (int c = 0; c < numtrigs; c++, j++)
8355 : {
8356 986 : tginfo[j].dobj.objType = DO_TRIGGER;
8357 986 : tginfo[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
8358 986 : tginfo[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
8359 986 : AssignDumpId(&tginfo[j].dobj);
8360 986 : tginfo[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_tgname));
8361 986 : tginfo[j].dobj.namespace = tbinfo->dobj.namespace;
8362 986 : tginfo[j].tgtable = tbinfo;
8363 986 : tginfo[j].tgenabled = *(PQgetvalue(res, j, i_tgenabled));
8364 986 : tginfo[j].tgispartition = *(PQgetvalue(res, j, i_tgispartition)) == 't';
8365 986 : tginfo[j].tgdef = pg_strdup(PQgetvalue(res, j, i_tgdef));
8366 : }
8367 : }
8368 :
8369 308 : PQclear(res);
8370 :
8371 308 : destroyPQExpBuffer(query);
8372 308 : destroyPQExpBuffer(tbloids);
8373 308 : }
8374 :
8375 : /*
8376 : * getEventTriggers
8377 : * get information about event triggers
8378 : */
8379 : void
8380 308 : getEventTriggers(Archive *fout)
8381 : {
8382 : int i;
8383 : PQExpBuffer query;
8384 : PGresult *res;
8385 : EventTriggerInfo *evtinfo;
8386 : int i_tableoid,
8387 : i_oid,
8388 : i_evtname,
8389 : i_evtevent,
8390 : i_evtowner,
8391 : i_evttags,
8392 : i_evtfname,
8393 : i_evtenabled;
8394 : int ntups;
8395 :
8396 : /* Before 9.3, there are no event triggers */
8397 308 : if (fout->remoteVersion < 90300)
8398 0 : return;
8399 :
8400 308 : query = createPQExpBuffer();
8401 :
8402 308 : appendPQExpBufferStr(query,
8403 : "SELECT e.tableoid, e.oid, evtname, evtenabled, "
8404 : "evtevent, evtowner, "
8405 : "array_to_string(array("
8406 : "select quote_literal(x) "
8407 : " from unnest(evttags) as t(x)), ', ') as evttags, "
8408 : "e.evtfoid::regproc as evtfname "
8409 : "FROM pg_event_trigger e "
8410 : "ORDER BY e.oid");
8411 :
8412 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8413 :
8414 308 : ntups = PQntuples(res);
8415 :
8416 308 : evtinfo = (EventTriggerInfo *) pg_malloc(ntups * sizeof(EventTriggerInfo));
8417 :
8418 308 : i_tableoid = PQfnumber(res, "tableoid");
8419 308 : i_oid = PQfnumber(res, "oid");
8420 308 : i_evtname = PQfnumber(res, "evtname");
8421 308 : i_evtevent = PQfnumber(res, "evtevent");
8422 308 : i_evtowner = PQfnumber(res, "evtowner");
8423 308 : i_evttags = PQfnumber(res, "evttags");
8424 308 : i_evtfname = PQfnumber(res, "evtfname");
8425 308 : i_evtenabled = PQfnumber(res, "evtenabled");
8426 :
8427 408 : for (i = 0; i < ntups; i++)
8428 : {
8429 100 : evtinfo[i].dobj.objType = DO_EVENT_TRIGGER;
8430 100 : evtinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8431 100 : evtinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8432 100 : AssignDumpId(&evtinfo[i].dobj);
8433 100 : evtinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_evtname));
8434 100 : evtinfo[i].evtname = pg_strdup(PQgetvalue(res, i, i_evtname));
8435 100 : evtinfo[i].evtevent = pg_strdup(PQgetvalue(res, i, i_evtevent));
8436 100 : evtinfo[i].evtowner = getRoleName(PQgetvalue(res, i, i_evtowner));
8437 100 : evtinfo[i].evttags = pg_strdup(PQgetvalue(res, i, i_evttags));
8438 100 : evtinfo[i].evtfname = pg_strdup(PQgetvalue(res, i, i_evtfname));
8439 100 : evtinfo[i].evtenabled = *(PQgetvalue(res, i, i_evtenabled));
8440 :
8441 : /* Decide whether we want to dump it */
8442 100 : selectDumpableObject(&(evtinfo[i].dobj), fout);
8443 : }
8444 :
8445 308 : PQclear(res);
8446 :
8447 308 : destroyPQExpBuffer(query);
8448 : }
8449 :
8450 : /*
8451 : * getProcLangs
8452 : * get basic information about every procedural language in the system
8453 : *
8454 : * NB: this must run after getFuncs() because we assume we can do
8455 : * findFuncByOid().
8456 : */
8457 : void
8458 308 : getProcLangs(Archive *fout)
8459 : {
8460 : PGresult *res;
8461 : int ntups;
8462 : int i;
8463 308 : PQExpBuffer query = createPQExpBuffer();
8464 : ProcLangInfo *planginfo;
8465 : int i_tableoid;
8466 : int i_oid;
8467 : int i_lanname;
8468 : int i_lanpltrusted;
8469 : int i_lanplcallfoid;
8470 : int i_laninline;
8471 : int i_lanvalidator;
8472 : int i_lanacl;
8473 : int i_acldefault;
8474 : int i_lanowner;
8475 :
8476 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8477 : "lanname, lanpltrusted, lanplcallfoid, "
8478 : "laninline, lanvalidator, "
8479 : "lanacl, "
8480 : "acldefault('l', lanowner) AS acldefault, "
8481 : "lanowner "
8482 : "FROM pg_language "
8483 : "WHERE lanispl "
8484 : "ORDER BY oid");
8485 :
8486 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8487 :
8488 308 : ntups = PQntuples(res);
8489 :
8490 308 : planginfo = (ProcLangInfo *) pg_malloc(ntups * sizeof(ProcLangInfo));
8491 :
8492 308 : i_tableoid = PQfnumber(res, "tableoid");
8493 308 : i_oid = PQfnumber(res, "oid");
8494 308 : i_lanname = PQfnumber(res, "lanname");
8495 308 : i_lanpltrusted = PQfnumber(res, "lanpltrusted");
8496 308 : i_lanplcallfoid = PQfnumber(res, "lanplcallfoid");
8497 308 : i_laninline = PQfnumber(res, "laninline");
8498 308 : i_lanvalidator = PQfnumber(res, "lanvalidator");
8499 308 : i_lanacl = PQfnumber(res, "lanacl");
8500 308 : i_acldefault = PQfnumber(res, "acldefault");
8501 308 : i_lanowner = PQfnumber(res, "lanowner");
8502 :
8503 702 : for (i = 0; i < ntups; i++)
8504 : {
8505 394 : planginfo[i].dobj.objType = DO_PROCLANG;
8506 394 : planginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8507 394 : planginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8508 394 : AssignDumpId(&planginfo[i].dobj);
8509 :
8510 394 : planginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_lanname));
8511 394 : planginfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_lanacl));
8512 394 : planginfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
8513 394 : planginfo[i].dacl.privtype = 0;
8514 394 : planginfo[i].dacl.initprivs = NULL;
8515 394 : planginfo[i].lanpltrusted = *(PQgetvalue(res, i, i_lanpltrusted)) == 't';
8516 394 : planginfo[i].lanplcallfoid = atooid(PQgetvalue(res, i, i_lanplcallfoid));
8517 394 : planginfo[i].laninline = atooid(PQgetvalue(res, i, i_laninline));
8518 394 : planginfo[i].lanvalidator = atooid(PQgetvalue(res, i, i_lanvalidator));
8519 394 : planginfo[i].lanowner = getRoleName(PQgetvalue(res, i, i_lanowner));
8520 :
8521 : /* Decide whether we want to dump it */
8522 394 : selectDumpableProcLang(&(planginfo[i]), fout);
8523 :
8524 : /* Mark whether language has an ACL */
8525 394 : if (!PQgetisnull(res, i, i_lanacl))
8526 86 : planginfo[i].dobj.components |= DUMP_COMPONENT_ACL;
8527 : }
8528 :
8529 308 : PQclear(res);
8530 :
8531 308 : destroyPQExpBuffer(query);
8532 308 : }
8533 :
8534 : /*
8535 : * getCasts
8536 : * get basic information about most casts in the system
8537 : *
8538 : * Skip casts from a range to its multirange, since we'll create those
8539 : * automatically.
8540 : */
8541 : void
8542 308 : getCasts(Archive *fout)
8543 : {
8544 : PGresult *res;
8545 : int ntups;
8546 : int i;
8547 308 : PQExpBuffer query = createPQExpBuffer();
8548 : CastInfo *castinfo;
8549 : int i_tableoid;
8550 : int i_oid;
8551 : int i_castsource;
8552 : int i_casttarget;
8553 : int i_castfunc;
8554 : int i_castcontext;
8555 : int i_castmethod;
8556 :
8557 308 : if (fout->remoteVersion >= 140000)
8558 : {
8559 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8560 : "castsource, casttarget, castfunc, castcontext, "
8561 : "castmethod "
8562 : "FROM pg_cast c "
8563 : "WHERE NOT EXISTS ( "
8564 : "SELECT 1 FROM pg_range r "
8565 : "WHERE c.castsource = r.rngtypid "
8566 : "AND c.casttarget = r.rngmultitypid "
8567 : ") "
8568 : "ORDER BY 3,4");
8569 : }
8570 : else
8571 : {
8572 0 : appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8573 : "castsource, casttarget, castfunc, castcontext, "
8574 : "castmethod "
8575 : "FROM pg_cast ORDER BY 3,4");
8576 : }
8577 :
8578 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8579 :
8580 308 : ntups = PQntuples(res);
8581 :
8582 308 : castinfo = (CastInfo *) pg_malloc(ntups * sizeof(CastInfo));
8583 :
8584 308 : i_tableoid = PQfnumber(res, "tableoid");
8585 308 : i_oid = PQfnumber(res, "oid");
8586 308 : i_castsource = PQfnumber(res, "castsource");
8587 308 : i_casttarget = PQfnumber(res, "casttarget");
8588 308 : i_castfunc = PQfnumber(res, "castfunc");
8589 308 : i_castcontext = PQfnumber(res, "castcontext");
8590 308 : i_castmethod = PQfnumber(res, "castmethod");
8591 :
8592 69162 : for (i = 0; i < ntups; i++)
8593 : {
8594 : PQExpBufferData namebuf;
8595 : TypeInfo *sTypeInfo;
8596 : TypeInfo *tTypeInfo;
8597 :
8598 68854 : castinfo[i].dobj.objType = DO_CAST;
8599 68854 : castinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8600 68854 : castinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8601 68854 : AssignDumpId(&castinfo[i].dobj);
8602 68854 : castinfo[i].castsource = atooid(PQgetvalue(res, i, i_castsource));
8603 68854 : castinfo[i].casttarget = atooid(PQgetvalue(res, i, i_casttarget));
8604 68854 : castinfo[i].castfunc = atooid(PQgetvalue(res, i, i_castfunc));
8605 68854 : castinfo[i].castcontext = *(PQgetvalue(res, i, i_castcontext));
8606 68854 : castinfo[i].castmethod = *(PQgetvalue(res, i, i_castmethod));
8607 :
8608 : /*
8609 : * Try to name cast as concatenation of typnames. This is only used
8610 : * for purposes of sorting. If we fail to find either type, the name
8611 : * will be an empty string.
8612 : */
8613 68854 : initPQExpBuffer(&namebuf);
8614 68854 : sTypeInfo = findTypeByOid(castinfo[i].castsource);
8615 68854 : tTypeInfo = findTypeByOid(castinfo[i].casttarget);
8616 68854 : if (sTypeInfo && tTypeInfo)
8617 68854 : appendPQExpBuffer(&namebuf, "%s %s",
8618 : sTypeInfo->dobj.name, tTypeInfo->dobj.name);
8619 68854 : castinfo[i].dobj.name = namebuf.data;
8620 :
8621 : /* Decide whether we want to dump it */
8622 68854 : selectDumpableCast(&(castinfo[i]), fout);
8623 : }
8624 :
8625 308 : PQclear(res);
8626 :
8627 308 : destroyPQExpBuffer(query);
8628 308 : }
8629 :
8630 : static char *
8631 174 : get_language_name(Archive *fout, Oid langid)
8632 : {
8633 : PQExpBuffer query;
8634 : PGresult *res;
8635 : char *lanname;
8636 :
8637 174 : query = createPQExpBuffer();
8638 174 : appendPQExpBuffer(query, "SELECT lanname FROM pg_language WHERE oid = %u", langid);
8639 174 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
8640 174 : lanname = pg_strdup(fmtId(PQgetvalue(res, 0, 0)));
8641 174 : destroyPQExpBuffer(query);
8642 174 : PQclear(res);
8643 :
8644 174 : return lanname;
8645 : }
8646 :
8647 : /*
8648 : * getTransforms
8649 : * get basic information about every transform in the system
8650 : */
8651 : void
8652 308 : getTransforms(Archive *fout)
8653 : {
8654 : PGresult *res;
8655 : int ntups;
8656 : int i;
8657 : PQExpBuffer query;
8658 : TransformInfo *transforminfo;
8659 : int i_tableoid;
8660 : int i_oid;
8661 : int i_trftype;
8662 : int i_trflang;
8663 : int i_trffromsql;
8664 : int i_trftosql;
8665 :
8666 : /* Transforms didn't exist pre-9.5 */
8667 308 : if (fout->remoteVersion < 90500)
8668 0 : return;
8669 :
8670 308 : query = createPQExpBuffer();
8671 :
8672 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, "
8673 : "trftype, trflang, trffromsql::oid, trftosql::oid "
8674 : "FROM pg_transform "
8675 : "ORDER BY 3,4");
8676 :
8677 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
8678 :
8679 308 : ntups = PQntuples(res);
8680 :
8681 308 : transforminfo = (TransformInfo *) pg_malloc(ntups * sizeof(TransformInfo));
8682 :
8683 308 : i_tableoid = PQfnumber(res, "tableoid");
8684 308 : i_oid = PQfnumber(res, "oid");
8685 308 : i_trftype = PQfnumber(res, "trftype");
8686 308 : i_trflang = PQfnumber(res, "trflang");
8687 308 : i_trffromsql = PQfnumber(res, "trffromsql");
8688 308 : i_trftosql = PQfnumber(res, "trftosql");
8689 :
8690 408 : for (i = 0; i < ntups; i++)
8691 : {
8692 : PQExpBufferData namebuf;
8693 : TypeInfo *typeInfo;
8694 : char *lanname;
8695 :
8696 100 : transforminfo[i].dobj.objType = DO_TRANSFORM;
8697 100 : transforminfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
8698 100 : transforminfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
8699 100 : AssignDumpId(&transforminfo[i].dobj);
8700 100 : transforminfo[i].trftype = atooid(PQgetvalue(res, i, i_trftype));
8701 100 : transforminfo[i].trflang = atooid(PQgetvalue(res, i, i_trflang));
8702 100 : transforminfo[i].trffromsql = atooid(PQgetvalue(res, i, i_trffromsql));
8703 100 : transforminfo[i].trftosql = atooid(PQgetvalue(res, i, i_trftosql));
8704 :
8705 : /*
8706 : * Try to name transform as concatenation of type and language name.
8707 : * This is only used for purposes of sorting. If we fail to find
8708 : * either, the name will be an empty string.
8709 : */
8710 100 : initPQExpBuffer(&namebuf);
8711 100 : typeInfo = findTypeByOid(transforminfo[i].trftype);
8712 100 : lanname = get_language_name(fout, transforminfo[i].trflang);
8713 100 : if (typeInfo && lanname)
8714 100 : appendPQExpBuffer(&namebuf, "%s %s",
8715 : typeInfo->dobj.name, lanname);
8716 100 : transforminfo[i].dobj.name = namebuf.data;
8717 100 : free(lanname);
8718 :
8719 : /* Decide whether we want to dump it */
8720 100 : selectDumpableObject(&(transforminfo[i].dobj), fout);
8721 : }
8722 :
8723 308 : PQclear(res);
8724 :
8725 308 : destroyPQExpBuffer(query);
8726 : }
8727 :
8728 : /*
8729 : * getTableAttrs -
8730 : * for each interesting table, read info about its attributes
8731 : * (names, types, default values, CHECK constraints, etc)
8732 : *
8733 : * modifies tblinfo
8734 : */
8735 : void
8736 308 : getTableAttrs(Archive *fout, TableInfo *tblinfo, int numTables)
8737 : {
8738 308 : DumpOptions *dopt = fout->dopt;
8739 308 : PQExpBuffer q = createPQExpBuffer();
8740 308 : PQExpBuffer tbloids = createPQExpBuffer();
8741 308 : PQExpBuffer checkoids = createPQExpBuffer();
8742 : PGresult *res;
8743 : int ntups;
8744 : int curtblindx;
8745 : int i_attrelid;
8746 : int i_attnum;
8747 : int i_attname;
8748 : int i_atttypname;
8749 : int i_attstattarget;
8750 : int i_attstorage;
8751 : int i_typstorage;
8752 : int i_attidentity;
8753 : int i_attgenerated;
8754 : int i_attisdropped;
8755 : int i_attlen;
8756 : int i_attalign;
8757 : int i_attislocal;
8758 : int i_notnull_name;
8759 : int i_notnull_noinherit;
8760 : int i_notnull_islocal;
8761 : int i_attoptions;
8762 : int i_attcollation;
8763 : int i_attcompression;
8764 : int i_attfdwoptions;
8765 : int i_attmissingval;
8766 : int i_atthasdef;
8767 :
8768 : /*
8769 : * We want to perform just one query against pg_attribute, and then just
8770 : * one against pg_attrdef (for DEFAULTs) and two against pg_constraint
8771 : * (for CHECK constraints and for NOT NULL constraints). However, we
8772 : * mustn't try to select every row of those catalogs and then sort it out
8773 : * on the client side, because some of the server-side functions we need
8774 : * would be unsafe to apply to tables we don't have lock on. Hence, we
8775 : * build an array of the OIDs of tables we care about (and now have lock
8776 : * on!), and use a WHERE clause to constrain which rows are selected.
8777 : */
8778 308 : appendPQExpBufferChar(tbloids, '{');
8779 308 : appendPQExpBufferChar(checkoids, '{');
8780 81216 : for (int i = 0; i < numTables; i++)
8781 : {
8782 80908 : TableInfo *tbinfo = &tblinfo[i];
8783 :
8784 : /* Don't bother to collect info for sequences */
8785 80908 : if (tbinfo->relkind == RELKIND_SEQUENCE)
8786 1184 : continue;
8787 :
8788 : /* Don't bother with uninteresting tables, either */
8789 79724 : if (!tbinfo->interesting)
8790 68236 : continue;
8791 :
8792 : /* OK, we need info for this table */
8793 11488 : if (tbloids->len > 1) /* do we have more than the '{'? */
8794 11284 : appendPQExpBufferChar(tbloids, ',');
8795 11488 : appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
8796 :
8797 11488 : if (tbinfo->ncheck > 0)
8798 : {
8799 : /* Also make a list of the ones with check constraints */
8800 904 : if (checkoids->len > 1) /* do we have more than the '{'? */
8801 772 : appendPQExpBufferChar(checkoids, ',');
8802 904 : appendPQExpBuffer(checkoids, "%u", tbinfo->dobj.catId.oid);
8803 : }
8804 : }
8805 308 : appendPQExpBufferChar(tbloids, '}');
8806 308 : appendPQExpBufferChar(checkoids, '}');
8807 :
8808 : /*
8809 : * Find all the user attributes and their types.
8810 : *
8811 : * Since we only want to dump COLLATE clauses for attributes whose
8812 : * collation is different from their type's default, we use a CASE here to
8813 : * suppress uninteresting attcollations cheaply.
8814 : */
8815 308 : appendPQExpBufferStr(q,
8816 : "SELECT\n"
8817 : "a.attrelid,\n"
8818 : "a.attnum,\n"
8819 : "a.attname,\n"
8820 : "a.attstattarget,\n"
8821 : "a.attstorage,\n"
8822 : "t.typstorage,\n"
8823 : "a.atthasdef,\n"
8824 : "a.attisdropped,\n"
8825 : "a.attlen,\n"
8826 : "a.attalign,\n"
8827 : "a.attislocal,\n"
8828 : "pg_catalog.format_type(t.oid, a.atttypmod) AS atttypname,\n"
8829 : "array_to_string(a.attoptions, ', ') AS attoptions,\n"
8830 : "CASE WHEN a.attcollation <> t.typcollation "
8831 : "THEN a.attcollation ELSE 0 END AS attcollation,\n"
8832 : "pg_catalog.array_to_string(ARRAY("
8833 : "SELECT pg_catalog.quote_ident(option_name) || "
8834 : "' ' || pg_catalog.quote_literal(option_value) "
8835 : "FROM pg_catalog.pg_options_to_table(attfdwoptions) "
8836 : "ORDER BY option_name"
8837 : "), E',\n ') AS attfdwoptions,\n");
8838 :
8839 : /*
8840 : * Find out any NOT NULL markings for each column. In 18 and up we read
8841 : * pg_constraint to obtain the constraint name. notnull_noinherit is set
8842 : * according to the NO INHERIT property. For versions prior to 18, we
8843 : * store an empty string as the name when a constraint is marked as
8844 : * attnotnull (this cues dumpTableSchema to print the NOT NULL clause
8845 : * without a name); also, such cases are never NO INHERIT.
8846 : *
8847 : * We track in notnull_islocal whether the constraint was defined directly
8848 : * in this table or via an ancestor, for binary upgrade. flagInhAttrs
8849 : * might modify this later for servers older than 18; it's also in charge
8850 : * of determining the correct inhcount.
8851 : */
8852 308 : if (fout->remoteVersion >= 180000)
8853 308 : appendPQExpBufferStr(q,
8854 : "co.conname AS notnull_name,\n"
8855 : "co.connoinherit AS notnull_noinherit,\n"
8856 : "co.conislocal AS notnull_islocal,\n");
8857 : else
8858 0 : appendPQExpBufferStr(q,
8859 : "CASE WHEN a.attnotnull THEN '' ELSE NULL END AS notnull_name,\n"
8860 : "false AS notnull_noinherit,\n"
8861 : "a.attislocal AS notnull_islocal,\n");
8862 :
8863 308 : if (fout->remoteVersion >= 140000)
8864 308 : appendPQExpBufferStr(q,
8865 : "a.attcompression AS attcompression,\n");
8866 : else
8867 0 : appendPQExpBufferStr(q,
8868 : "'' AS attcompression,\n");
8869 :
8870 308 : if (fout->remoteVersion >= 100000)
8871 308 : appendPQExpBufferStr(q,
8872 : "a.attidentity,\n");
8873 : else
8874 0 : appendPQExpBufferStr(q,
8875 : "'' AS attidentity,\n");
8876 :
8877 308 : if (fout->remoteVersion >= 110000)
8878 308 : appendPQExpBufferStr(q,
8879 : "CASE WHEN a.atthasmissing AND NOT a.attisdropped "
8880 : "THEN a.attmissingval ELSE null END AS attmissingval,\n");
8881 : else
8882 0 : appendPQExpBufferStr(q,
8883 : "NULL AS attmissingval,\n");
8884 :
8885 308 : if (fout->remoteVersion >= 120000)
8886 308 : appendPQExpBufferStr(q,
8887 : "a.attgenerated\n");
8888 : else
8889 0 : appendPQExpBufferStr(q,
8890 : "'' AS attgenerated\n");
8891 :
8892 : /* need left join to pg_type to not fail on dropped columns ... */
8893 308 : appendPQExpBuffer(q,
8894 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
8895 : "JOIN pg_catalog.pg_attribute a ON (src.tbloid = a.attrelid) "
8896 : "LEFT JOIN pg_catalog.pg_type t "
8897 : "ON (a.atttypid = t.oid)\n",
8898 : tbloids->data);
8899 :
8900 : /*
8901 : * In versions 18 and up, we need pg_constraint for explicit NOT NULL
8902 : * entries. Also, we need to know if the NOT NULL for each column is
8903 : * backing a primary key.
8904 : */
8905 308 : if (fout->remoteVersion >= 180000)
8906 308 : appendPQExpBufferStr(q,
8907 : " LEFT JOIN pg_catalog.pg_constraint co ON "
8908 : "(a.attrelid = co.conrelid\n"
8909 : " AND co.contype = 'n' AND "
8910 : "co.conkey = array[a.attnum])\n");
8911 :
8912 308 : appendPQExpBufferStr(q,
8913 : "WHERE a.attnum > 0::pg_catalog.int2\n"
8914 : "ORDER BY a.attrelid, a.attnum");
8915 :
8916 308 : res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
8917 :
8918 308 : ntups = PQntuples(res);
8919 :
8920 308 : i_attrelid = PQfnumber(res, "attrelid");
8921 308 : i_attnum = PQfnumber(res, "attnum");
8922 308 : i_attname = PQfnumber(res, "attname");
8923 308 : i_atttypname = PQfnumber(res, "atttypname");
8924 308 : i_attstattarget = PQfnumber(res, "attstattarget");
8925 308 : i_attstorage = PQfnumber(res, "attstorage");
8926 308 : i_typstorage = PQfnumber(res, "typstorage");
8927 308 : i_attidentity = PQfnumber(res, "attidentity");
8928 308 : i_attgenerated = PQfnumber(res, "attgenerated");
8929 308 : i_attisdropped = PQfnumber(res, "attisdropped");
8930 308 : i_attlen = PQfnumber(res, "attlen");
8931 308 : i_attalign = PQfnumber(res, "attalign");
8932 308 : i_attislocal = PQfnumber(res, "attislocal");
8933 308 : i_notnull_name = PQfnumber(res, "notnull_name");
8934 308 : i_notnull_noinherit = PQfnumber(res, "notnull_noinherit");
8935 308 : i_notnull_islocal = PQfnumber(res, "notnull_islocal");
8936 308 : i_attoptions = PQfnumber(res, "attoptions");
8937 308 : i_attcollation = PQfnumber(res, "attcollation");
8938 308 : i_attcompression = PQfnumber(res, "attcompression");
8939 308 : i_attfdwoptions = PQfnumber(res, "attfdwoptions");
8940 308 : i_attmissingval = PQfnumber(res, "attmissingval");
8941 308 : i_atthasdef = PQfnumber(res, "atthasdef");
8942 :
8943 : /* Within the next loop, we'll accumulate OIDs of tables with defaults */
8944 308 : resetPQExpBuffer(tbloids);
8945 308 : appendPQExpBufferChar(tbloids, '{');
8946 :
8947 : /*
8948 : * Outer loop iterates once per table, not once per row. Incrementing of
8949 : * r is handled by the inner loop.
8950 : */
8951 308 : curtblindx = -1;
8952 11532 : for (int r = 0; r < ntups;)
8953 : {
8954 11224 : Oid attrelid = atooid(PQgetvalue(res, r, i_attrelid));
8955 11224 : TableInfo *tbinfo = NULL;
8956 : int numatts;
8957 : bool hasdefaults;
8958 :
8959 : /* Count rows for this table */
8960 45038 : for (numatts = 1; numatts < ntups - r; numatts++)
8961 44840 : if (atooid(PQgetvalue(res, r + numatts, i_attrelid)) != attrelid)
8962 11026 : break;
8963 :
8964 : /*
8965 : * Locate the associated TableInfo; we rely on tblinfo[] being in OID
8966 : * order.
8967 : */
8968 53744 : while (++curtblindx < numTables)
8969 : {
8970 53744 : tbinfo = &tblinfo[curtblindx];
8971 53744 : if (tbinfo->dobj.catId.oid == attrelid)
8972 11224 : break;
8973 : }
8974 11224 : if (curtblindx >= numTables)
8975 0 : pg_fatal("unrecognized table OID %u", attrelid);
8976 : /* cross-check that we only got requested tables */
8977 11224 : if (tbinfo->relkind == RELKIND_SEQUENCE ||
8978 11224 : !tbinfo->interesting)
8979 0 : pg_fatal("unexpected column data for table \"%s\"",
8980 : tbinfo->dobj.name);
8981 :
8982 : /* Save data for this table */
8983 11224 : tbinfo->numatts = numatts;
8984 11224 : tbinfo->attnames = (char **) pg_malloc(numatts * sizeof(char *));
8985 11224 : tbinfo->atttypnames = (char **) pg_malloc(numatts * sizeof(char *));
8986 11224 : tbinfo->attstattarget = (int *) pg_malloc(numatts * sizeof(int));
8987 11224 : tbinfo->attstorage = (char *) pg_malloc(numatts * sizeof(char));
8988 11224 : tbinfo->typstorage = (char *) pg_malloc(numatts * sizeof(char));
8989 11224 : tbinfo->attidentity = (char *) pg_malloc(numatts * sizeof(char));
8990 11224 : tbinfo->attgenerated = (char *) pg_malloc(numatts * sizeof(char));
8991 11224 : tbinfo->attisdropped = (bool *) pg_malloc(numatts * sizeof(bool));
8992 11224 : tbinfo->attlen = (int *) pg_malloc(numatts * sizeof(int));
8993 11224 : tbinfo->attalign = (char *) pg_malloc(numatts * sizeof(char));
8994 11224 : tbinfo->attislocal = (bool *) pg_malloc(numatts * sizeof(bool));
8995 11224 : tbinfo->attoptions = (char **) pg_malloc(numatts * sizeof(char *));
8996 11224 : tbinfo->attcollation = (Oid *) pg_malloc(numatts * sizeof(Oid));
8997 11224 : tbinfo->attcompression = (char *) pg_malloc(numatts * sizeof(char));
8998 11224 : tbinfo->attfdwoptions = (char **) pg_malloc(numatts * sizeof(char *));
8999 11224 : tbinfo->attmissingval = (char **) pg_malloc(numatts * sizeof(char *));
9000 11224 : tbinfo->notnull_constrs = (char **) pg_malloc(numatts * sizeof(char *));
9001 11224 : tbinfo->notnull_noinh = (bool *) pg_malloc(numatts * sizeof(bool));
9002 11224 : tbinfo->notnull_islocal = (bool *) pg_malloc(numatts * sizeof(bool));
9003 11224 : tbinfo->attrdefs = (AttrDefInfo **) pg_malloc(numatts * sizeof(AttrDefInfo *));
9004 11224 : hasdefaults = false;
9005 :
9006 56262 : for (int j = 0; j < numatts; j++, r++)
9007 : {
9008 45038 : if (j + 1 != atoi(PQgetvalue(res, r, i_attnum)))
9009 0 : pg_fatal("invalid column numbering in table \"%s\"",
9010 : tbinfo->dobj.name);
9011 45038 : tbinfo->attnames[j] = pg_strdup(PQgetvalue(res, r, i_attname));
9012 45038 : tbinfo->atttypnames[j] = pg_strdup(PQgetvalue(res, r, i_atttypname));
9013 45038 : if (PQgetisnull(res, r, i_attstattarget))
9014 44964 : tbinfo->attstattarget[j] = -1;
9015 : else
9016 74 : tbinfo->attstattarget[j] = atoi(PQgetvalue(res, r, i_attstattarget));
9017 45038 : tbinfo->attstorage[j] = *(PQgetvalue(res, r, i_attstorage));
9018 45038 : tbinfo->typstorage[j] = *(PQgetvalue(res, r, i_typstorage));
9019 45038 : tbinfo->attidentity[j] = *(PQgetvalue(res, r, i_attidentity));
9020 45038 : tbinfo->attgenerated[j] = *(PQgetvalue(res, r, i_attgenerated));
9021 45038 : tbinfo->needs_override = tbinfo->needs_override || (tbinfo->attidentity[j] == ATTRIBUTE_IDENTITY_ALWAYS);
9022 45038 : tbinfo->attisdropped[j] = (PQgetvalue(res, r, i_attisdropped)[0] == 't');
9023 45038 : tbinfo->attlen[j] = atoi(PQgetvalue(res, r, i_attlen));
9024 45038 : tbinfo->attalign[j] = *(PQgetvalue(res, r, i_attalign));
9025 45038 : tbinfo->attislocal[j] = (PQgetvalue(res, r, i_attislocal)[0] == 't');
9026 :
9027 : /* Handle not-null constraint name and flags */
9028 45038 : determineNotNullFlags(fout, res, r,
9029 : tbinfo, j,
9030 : i_notnull_name, i_notnull_noinherit,
9031 : i_notnull_islocal);
9032 :
9033 45038 : tbinfo->attoptions[j] = pg_strdup(PQgetvalue(res, r, i_attoptions));
9034 45038 : tbinfo->attcollation[j] = atooid(PQgetvalue(res, r, i_attcollation));
9035 45038 : tbinfo->attcompression[j] = *(PQgetvalue(res, r, i_attcompression));
9036 45038 : tbinfo->attfdwoptions[j] = pg_strdup(PQgetvalue(res, r, i_attfdwoptions));
9037 45038 : tbinfo->attmissingval[j] = pg_strdup(PQgetvalue(res, r, i_attmissingval));
9038 45038 : tbinfo->attrdefs[j] = NULL; /* fix below */
9039 45038 : if (PQgetvalue(res, r, i_atthasdef)[0] == 't')
9040 1686 : hasdefaults = true;
9041 : }
9042 :
9043 11224 : if (hasdefaults)
9044 : {
9045 : /* Collect OIDs of interesting tables that have defaults */
9046 1390 : if (tbloids->len > 1) /* do we have more than the '{'? */
9047 1294 : appendPQExpBufferChar(tbloids, ',');
9048 1390 : appendPQExpBuffer(tbloids, "%u", tbinfo->dobj.catId.oid);
9049 : }
9050 : }
9051 :
9052 308 : PQclear(res);
9053 :
9054 : /*
9055 : * Now get info about column defaults. This is skipped for a data-only
9056 : * dump, as it is only needed for table schemas.
9057 : */
9058 308 : if (!dopt->dataOnly && tbloids->len > 1)
9059 : {
9060 : AttrDefInfo *attrdefs;
9061 : int numDefaults;
9062 88 : TableInfo *tbinfo = NULL;
9063 :
9064 88 : pg_log_info("finding table default expressions");
9065 :
9066 88 : appendPQExpBufferChar(tbloids, '}');
9067 :
9068 88 : printfPQExpBuffer(q, "SELECT a.tableoid, a.oid, adrelid, adnum, "
9069 : "pg_catalog.pg_get_expr(adbin, adrelid) AS adsrc\n"
9070 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
9071 : "JOIN pg_catalog.pg_attrdef a ON (src.tbloid = a.adrelid)\n"
9072 : "ORDER BY a.adrelid, a.adnum",
9073 : tbloids->data);
9074 :
9075 88 : res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
9076 :
9077 88 : numDefaults = PQntuples(res);
9078 88 : attrdefs = (AttrDefInfo *) pg_malloc(numDefaults * sizeof(AttrDefInfo));
9079 :
9080 88 : curtblindx = -1;
9081 1694 : for (int j = 0; j < numDefaults; j++)
9082 : {
9083 1606 : Oid adtableoid = atooid(PQgetvalue(res, j, 0));
9084 1606 : Oid adoid = atooid(PQgetvalue(res, j, 1));
9085 1606 : Oid adrelid = atooid(PQgetvalue(res, j, 2));
9086 1606 : int adnum = atoi(PQgetvalue(res, j, 3));
9087 1606 : char *adsrc = PQgetvalue(res, j, 4);
9088 :
9089 : /*
9090 : * Locate the associated TableInfo; we rely on tblinfo[] being in
9091 : * OID order.
9092 : */
9093 1606 : if (tbinfo == NULL || tbinfo->dobj.catId.oid != adrelid)
9094 : {
9095 29510 : while (++curtblindx < numTables)
9096 : {
9097 29510 : tbinfo = &tblinfo[curtblindx];
9098 29510 : if (tbinfo->dobj.catId.oid == adrelid)
9099 1322 : break;
9100 : }
9101 1322 : if (curtblindx >= numTables)
9102 0 : pg_fatal("unrecognized table OID %u", adrelid);
9103 : }
9104 :
9105 1606 : if (adnum <= 0 || adnum > tbinfo->numatts)
9106 0 : pg_fatal("invalid adnum value %d for table \"%s\"",
9107 : adnum, tbinfo->dobj.name);
9108 :
9109 : /*
9110 : * dropped columns shouldn't have defaults, but just in case,
9111 : * ignore 'em
9112 : */
9113 1606 : if (tbinfo->attisdropped[adnum - 1])
9114 0 : continue;
9115 :
9116 1606 : attrdefs[j].dobj.objType = DO_ATTRDEF;
9117 1606 : attrdefs[j].dobj.catId.tableoid = adtableoid;
9118 1606 : attrdefs[j].dobj.catId.oid = adoid;
9119 1606 : AssignDumpId(&attrdefs[j].dobj);
9120 1606 : attrdefs[j].adtable = tbinfo;
9121 1606 : attrdefs[j].adnum = adnum;
9122 1606 : attrdefs[j].adef_expr = pg_strdup(adsrc);
9123 :
9124 1606 : attrdefs[j].dobj.name = pg_strdup(tbinfo->dobj.name);
9125 1606 : attrdefs[j].dobj.namespace = tbinfo->dobj.namespace;
9126 :
9127 1606 : attrdefs[j].dobj.dump = tbinfo->dobj.dump;
9128 :
9129 : /*
9130 : * Figure out whether the default/generation expression should be
9131 : * dumped as part of the main CREATE TABLE (or similar) command or
9132 : * as a separate ALTER TABLE (or similar) command. The preference
9133 : * is to put it into the CREATE command, but in some cases that's
9134 : * not possible.
9135 : */
9136 1606 : if (tbinfo->attgenerated[adnum - 1])
9137 : {
9138 : /*
9139 : * Column generation expressions cannot be dumped separately,
9140 : * because there is no syntax for it. By setting separate to
9141 : * false here we prevent the "default" from being processed as
9142 : * its own dumpable object. Later, flagInhAttrs() will mark
9143 : * it as not to be dumped at all, if possible (that is, if it
9144 : * can be inherited from a parent).
9145 : */
9146 690 : attrdefs[j].separate = false;
9147 : }
9148 916 : else if (tbinfo->relkind == RELKIND_VIEW)
9149 : {
9150 : /*
9151 : * Defaults on a VIEW must always be dumped as separate ALTER
9152 : * TABLE commands.
9153 : */
9154 66 : attrdefs[j].separate = true;
9155 : }
9156 850 : else if (!shouldPrintColumn(dopt, tbinfo, adnum - 1))
9157 : {
9158 : /* column will be suppressed, print default separately */
9159 8 : attrdefs[j].separate = true;
9160 : }
9161 : else
9162 : {
9163 842 : attrdefs[j].separate = false;
9164 : }
9165 :
9166 1606 : if (!attrdefs[j].separate)
9167 : {
9168 : /*
9169 : * Mark the default as needing to appear before the table, so
9170 : * that any dependencies it has must be emitted before the
9171 : * CREATE TABLE. If this is not possible, we'll change to
9172 : * "separate" mode while sorting dependencies.
9173 : */
9174 1532 : addObjectDependency(&tbinfo->dobj,
9175 1532 : attrdefs[j].dobj.dumpId);
9176 : }
9177 :
9178 1606 : tbinfo->attrdefs[adnum - 1] = &attrdefs[j];
9179 : }
9180 :
9181 88 : PQclear(res);
9182 : }
9183 :
9184 : /*
9185 : * Get info about table CHECK constraints. This is skipped for a
9186 : * data-only dump, as it is only needed for table schemas.
9187 : */
9188 308 : if (!dopt->dataOnly && checkoids->len > 2)
9189 : {
9190 : ConstraintInfo *constrs;
9191 : int numConstrs;
9192 : int i_tableoid;
9193 : int i_oid;
9194 : int i_conrelid;
9195 : int i_conname;
9196 : int i_consrc;
9197 : int i_conislocal;
9198 : int i_convalidated;
9199 :
9200 122 : pg_log_info("finding table check constraints");
9201 :
9202 122 : resetPQExpBuffer(q);
9203 122 : appendPQExpBuffer(q,
9204 : "SELECT c.tableoid, c.oid, conrelid, conname, "
9205 : "pg_catalog.pg_get_constraintdef(c.oid) AS consrc, "
9206 : "conislocal, convalidated "
9207 : "FROM unnest('%s'::pg_catalog.oid[]) AS src(tbloid)\n"
9208 : "JOIN pg_catalog.pg_constraint c ON (src.tbloid = c.conrelid)\n"
9209 : "WHERE contype = 'c' "
9210 : "ORDER BY c.conrelid, c.conname",
9211 : checkoids->data);
9212 :
9213 122 : res = ExecuteSqlQuery(fout, q->data, PGRES_TUPLES_OK);
9214 :
9215 122 : numConstrs = PQntuples(res);
9216 122 : constrs = (ConstraintInfo *) pg_malloc(numConstrs * sizeof(ConstraintInfo));
9217 :
9218 122 : i_tableoid = PQfnumber(res, "tableoid");
9219 122 : i_oid = PQfnumber(res, "oid");
9220 122 : i_conrelid = PQfnumber(res, "conrelid");
9221 122 : i_conname = PQfnumber(res, "conname");
9222 122 : i_consrc = PQfnumber(res, "consrc");
9223 122 : i_conislocal = PQfnumber(res, "conislocal");
9224 122 : i_convalidated = PQfnumber(res, "convalidated");
9225 :
9226 : /* As above, this loop iterates once per table, not once per row */
9227 122 : curtblindx = -1;
9228 974 : for (int j = 0; j < numConstrs;)
9229 : {
9230 852 : Oid conrelid = atooid(PQgetvalue(res, j, i_conrelid));
9231 852 : TableInfo *tbinfo = NULL;
9232 : int numcons;
9233 :
9234 : /* Count rows for this table */
9235 1116 : for (numcons = 1; numcons < numConstrs - j; numcons++)
9236 994 : if (atooid(PQgetvalue(res, j + numcons, i_conrelid)) != conrelid)
9237 730 : break;
9238 :
9239 : /*
9240 : * Locate the associated TableInfo; we rely on tblinfo[] being in
9241 : * OID order.
9242 : */
9243 35028 : while (++curtblindx < numTables)
9244 : {
9245 35028 : tbinfo = &tblinfo[curtblindx];
9246 35028 : if (tbinfo->dobj.catId.oid == conrelid)
9247 852 : break;
9248 : }
9249 852 : if (curtblindx >= numTables)
9250 0 : pg_fatal("unrecognized table OID %u", conrelid);
9251 :
9252 852 : if (numcons != tbinfo->ncheck)
9253 : {
9254 0 : pg_log_error(ngettext("expected %d check constraint on table \"%s\" but found %d",
9255 : "expected %d check constraints on table \"%s\" but found %d",
9256 : tbinfo->ncheck),
9257 : tbinfo->ncheck, tbinfo->dobj.name, numcons);
9258 0 : pg_log_error_hint("The system catalogs might be corrupted.");
9259 0 : exit_nicely(1);
9260 : }
9261 :
9262 852 : tbinfo->checkexprs = constrs + j;
9263 :
9264 1968 : for (int c = 0; c < numcons; c++, j++)
9265 : {
9266 1116 : bool validated = PQgetvalue(res, j, i_convalidated)[0] == 't';
9267 :
9268 1116 : constrs[j].dobj.objType = DO_CONSTRAINT;
9269 1116 : constrs[j].dobj.catId.tableoid = atooid(PQgetvalue(res, j, i_tableoid));
9270 1116 : constrs[j].dobj.catId.oid = atooid(PQgetvalue(res, j, i_oid));
9271 1116 : AssignDumpId(&constrs[j].dobj);
9272 1116 : constrs[j].dobj.name = pg_strdup(PQgetvalue(res, j, i_conname));
9273 1116 : constrs[j].dobj.namespace = tbinfo->dobj.namespace;
9274 1116 : constrs[j].contable = tbinfo;
9275 1116 : constrs[j].condomain = NULL;
9276 1116 : constrs[j].contype = 'c';
9277 1116 : constrs[j].condef = pg_strdup(PQgetvalue(res, j, i_consrc));
9278 1116 : constrs[j].confrelid = InvalidOid;
9279 1116 : constrs[j].conindex = 0;
9280 1116 : constrs[j].condeferrable = false;
9281 1116 : constrs[j].condeferred = false;
9282 1116 : constrs[j].conislocal = (PQgetvalue(res, j, i_conislocal)[0] == 't');
9283 :
9284 : /*
9285 : * An unvalidated constraint needs to be dumped separately, so
9286 : * that potentially-violating existing data is loaded before
9287 : * the constraint.
9288 : */
9289 1116 : constrs[j].separate = !validated;
9290 :
9291 1116 : constrs[j].dobj.dump = tbinfo->dobj.dump;
9292 :
9293 : /*
9294 : * Mark the constraint as needing to appear before the table
9295 : * --- this is so that any other dependencies of the
9296 : * constraint will be emitted before we try to create the
9297 : * table. If the constraint is to be dumped separately, it
9298 : * will be dumped after data is loaded anyway, so don't do it.
9299 : * (There's an automatic dependency in the opposite direction
9300 : * anyway, so don't need to add one manually here.)
9301 : */
9302 1116 : if (!constrs[j].separate)
9303 1046 : addObjectDependency(&tbinfo->dobj,
9304 1046 : constrs[j].dobj.dumpId);
9305 :
9306 : /*
9307 : * We will detect later whether the constraint must be split
9308 : * out from the table definition.
9309 : */
9310 : }
9311 : }
9312 :
9313 122 : PQclear(res);
9314 : }
9315 :
9316 308 : destroyPQExpBuffer(q);
9317 308 : destroyPQExpBuffer(tbloids);
9318 308 : destroyPQExpBuffer(checkoids);
9319 308 : }
9320 :
9321 : /*
9322 : * Based on the getTableAttrs query's row corresponding to one column, set
9323 : * the name and flags to handle a not-null constraint for that column in
9324 : * the tbinfo struct.
9325 : *
9326 : * Result row 'r' is for tbinfo's attribute 'j'.
9327 : *
9328 : * There are three possibilities:
9329 : * 1) the column has no not-null constraints. In that case, ->notnull_constrs
9330 : * (the constraint name) remains NULL.
9331 : * 2) The column has a constraint with no name (this is the case when
9332 : * constraints come from pre-18 servers). In this case, ->notnull_constrs
9333 : * is set to the empty string; dumpTableSchema will print just "NOT NULL".
9334 : * 3) The column has a constraint with a known name; in that case
9335 : * notnull_constrs carries that name and dumpTableSchema will print
9336 : * "CONSTRAINT the_name NOT NULL". However, if the name is the default
9337 : * (table_column_not_null), there's no need to print that name in the dump,
9338 : * so notnull_constrs is set to the empty string and it behaves as the case
9339 : * above.
9340 : *
9341 : * In a child table that inherits from a parent already containing NOT NULL
9342 : * constraints and the columns in the child don't have their own NOT NULL
9343 : * declarations, we suppress printing constraints in the child: the
9344 : * constraints are acquired at the point where the child is attached to the
9345 : * parent. This is tracked in ->notnull_inh (which is set in flagInhAttrs for
9346 : * servers pre-18).
9347 : *
9348 : * Any of these constraints might have the NO INHERIT bit. If so we set
9349 : * ->notnull_noinh and NO INHERIT will be printed by dumpTableSchema.
9350 : *
9351 : * In case 3 above, the name comparison is a bit of a hack; it actually fails
9352 : * to do the right thing in all but the trivial case. However, the downside
9353 : * of getting it wrong is simply that the name is printed rather than
9354 : * suppressed, so it's not a big deal.
9355 : */
9356 : static void
9357 45038 : determineNotNullFlags(Archive *fout, PGresult *res, int r,
9358 : TableInfo *tbinfo, int j,
9359 : int i_notnull_name, int i_notnull_noinherit,
9360 : int i_notnull_islocal)
9361 : {
9362 45038 : DumpOptions *dopt = fout->dopt;
9363 :
9364 : /*
9365 : * notnull_noinh is straight from the query result. notnull_islocal also,
9366 : * though flagInhAttrs may change that one later in versions < 18.
9367 : */
9368 45038 : tbinfo->notnull_noinh[j] = PQgetvalue(res, r, i_notnull_noinherit)[0] == 't';
9369 45038 : tbinfo->notnull_islocal[j] = PQgetvalue(res, r, i_notnull_islocal)[0] == 't';
9370 :
9371 : /*
9372 : * Determine a constraint name to use. If the column is not marked not-
9373 : * null, we set NULL which cues ... to do nothing. An empty string says
9374 : * to print an unnamed NOT NULL, and anything else is a constraint name to
9375 : * use.
9376 : */
9377 45038 : if (fout->remoteVersion < 180000)
9378 : {
9379 : /*
9380 : * < 18 doesn't have not-null names, so an unnamed constraint is
9381 : * sufficient.
9382 : */
9383 0 : if (PQgetisnull(res, r, i_notnull_name))
9384 0 : tbinfo->notnull_constrs[j] = NULL;
9385 : else
9386 0 : tbinfo->notnull_constrs[j] = "";
9387 : }
9388 : else
9389 : {
9390 45038 : if (PQgetisnull(res, r, i_notnull_name))
9391 40796 : tbinfo->notnull_constrs[j] = NULL;
9392 : else
9393 : {
9394 : /*
9395 : * In binary upgrade of inheritance child tables, must have a
9396 : * constraint name that we can UPDATE later.
9397 : */
9398 4242 : if (dopt->binary_upgrade &&
9399 480 : !tbinfo->ispartition &&
9400 344 : !tbinfo->notnull_islocal)
9401 : {
9402 0 : tbinfo->notnull_constrs[j] =
9403 0 : pstrdup(PQgetvalue(res, r, i_notnull_name));
9404 : }
9405 : else
9406 : {
9407 : char *default_name;
9408 :
9409 : /* XXX should match ChooseConstraintName better */
9410 4242 : default_name = psprintf("%s_%s_not_null", tbinfo->dobj.name,
9411 4242 : tbinfo->attnames[j]);
9412 4242 : if (strcmp(default_name,
9413 4242 : PQgetvalue(res, r, i_notnull_name)) == 0)
9414 2856 : tbinfo->notnull_constrs[j] = "";
9415 : else
9416 : {
9417 1386 : tbinfo->notnull_constrs[j] =
9418 1386 : pstrdup(PQgetvalue(res, r, i_notnull_name));
9419 : }
9420 : }
9421 : }
9422 : }
9423 45038 : }
9424 :
9425 : /*
9426 : * Test whether a column should be printed as part of table's CREATE TABLE.
9427 : * Column number is zero-based.
9428 : *
9429 : * Normally this is always true, but it's false for dropped columns, as well
9430 : * as those that were inherited without any local definition. (If we print
9431 : * such a column it will mistakenly get pg_attribute.attislocal set to true.)
9432 : * For partitions, it's always true, because we want the partitions to be
9433 : * created independently and ATTACH PARTITION used afterwards.
9434 : *
9435 : * In binary_upgrade mode, we must print all columns and fix the attislocal/
9436 : * attisdropped state later, so as to keep control of the physical column
9437 : * order.
9438 : *
9439 : * This function exists because there are scattered nonobvious places that
9440 : * must be kept in sync with this decision.
9441 : */
9442 : bool
9443 75352 : shouldPrintColumn(const DumpOptions *dopt, const TableInfo *tbinfo, int colno)
9444 : {
9445 75352 : if (dopt->binary_upgrade)
9446 11652 : return true;
9447 63700 : if (tbinfo->attisdropped[colno])
9448 688 : return false;
9449 63012 : return (tbinfo->attislocal[colno] || tbinfo->ispartition);
9450 : }
9451 :
9452 :
9453 : /*
9454 : * getTSParsers:
9455 : * get information about all text search parsers in the system catalogs
9456 : */
9457 : void
9458 308 : getTSParsers(Archive *fout)
9459 : {
9460 : PGresult *res;
9461 : int ntups;
9462 : int i;
9463 : PQExpBuffer query;
9464 : TSParserInfo *prsinfo;
9465 : int i_tableoid;
9466 : int i_oid;
9467 : int i_prsname;
9468 : int i_prsnamespace;
9469 : int i_prsstart;
9470 : int i_prstoken;
9471 : int i_prsend;
9472 : int i_prsheadline;
9473 : int i_prslextype;
9474 :
9475 308 : query = createPQExpBuffer();
9476 :
9477 : /*
9478 : * find all text search objects, including builtin ones; we filter out
9479 : * system-defined objects at dump-out time.
9480 : */
9481 :
9482 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, prsname, prsnamespace, "
9483 : "prsstart::oid, prstoken::oid, "
9484 : "prsend::oid, prsheadline::oid, prslextype::oid "
9485 : "FROM pg_ts_parser");
9486 :
9487 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9488 :
9489 308 : ntups = PQntuples(res);
9490 :
9491 308 : prsinfo = (TSParserInfo *) pg_malloc(ntups * sizeof(TSParserInfo));
9492 :
9493 308 : i_tableoid = PQfnumber(res, "tableoid");
9494 308 : i_oid = PQfnumber(res, "oid");
9495 308 : i_prsname = PQfnumber(res, "prsname");
9496 308 : i_prsnamespace = PQfnumber(res, "prsnamespace");
9497 308 : i_prsstart = PQfnumber(res, "prsstart");
9498 308 : i_prstoken = PQfnumber(res, "prstoken");
9499 308 : i_prsend = PQfnumber(res, "prsend");
9500 308 : i_prsheadline = PQfnumber(res, "prsheadline");
9501 308 : i_prslextype = PQfnumber(res, "prslextype");
9502 :
9503 702 : for (i = 0; i < ntups; i++)
9504 : {
9505 394 : prsinfo[i].dobj.objType = DO_TSPARSER;
9506 394 : prsinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9507 394 : prsinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9508 394 : AssignDumpId(&prsinfo[i].dobj);
9509 394 : prsinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_prsname));
9510 788 : prsinfo[i].dobj.namespace =
9511 394 : findNamespace(atooid(PQgetvalue(res, i, i_prsnamespace)));
9512 394 : prsinfo[i].prsstart = atooid(PQgetvalue(res, i, i_prsstart));
9513 394 : prsinfo[i].prstoken = atooid(PQgetvalue(res, i, i_prstoken));
9514 394 : prsinfo[i].prsend = atooid(PQgetvalue(res, i, i_prsend));
9515 394 : prsinfo[i].prsheadline = atooid(PQgetvalue(res, i, i_prsheadline));
9516 394 : prsinfo[i].prslextype = atooid(PQgetvalue(res, i, i_prslextype));
9517 :
9518 : /* Decide whether we want to dump it */
9519 394 : selectDumpableObject(&(prsinfo[i].dobj), fout);
9520 : }
9521 :
9522 308 : PQclear(res);
9523 :
9524 308 : destroyPQExpBuffer(query);
9525 308 : }
9526 :
9527 : /*
9528 : * getTSDictionaries:
9529 : * get information about all text search dictionaries in the system catalogs
9530 : */
9531 : void
9532 308 : getTSDictionaries(Archive *fout)
9533 : {
9534 : PGresult *res;
9535 : int ntups;
9536 : int i;
9537 : PQExpBuffer query;
9538 : TSDictInfo *dictinfo;
9539 : int i_tableoid;
9540 : int i_oid;
9541 : int i_dictname;
9542 : int i_dictnamespace;
9543 : int i_dictowner;
9544 : int i_dicttemplate;
9545 : int i_dictinitoption;
9546 :
9547 308 : query = createPQExpBuffer();
9548 :
9549 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, dictname, "
9550 : "dictnamespace, dictowner, "
9551 : "dicttemplate, dictinitoption "
9552 : "FROM pg_ts_dict");
9553 :
9554 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9555 :
9556 308 : ntups = PQntuples(res);
9557 :
9558 308 : dictinfo = (TSDictInfo *) pg_malloc(ntups * sizeof(TSDictInfo));
9559 :
9560 308 : i_tableoid = PQfnumber(res, "tableoid");
9561 308 : i_oid = PQfnumber(res, "oid");
9562 308 : i_dictname = PQfnumber(res, "dictname");
9563 308 : i_dictnamespace = PQfnumber(res, "dictnamespace");
9564 308 : i_dictowner = PQfnumber(res, "dictowner");
9565 308 : i_dictinitoption = PQfnumber(res, "dictinitoption");
9566 308 : i_dicttemplate = PQfnumber(res, "dicttemplate");
9567 :
9568 9452 : for (i = 0; i < ntups; i++)
9569 : {
9570 9144 : dictinfo[i].dobj.objType = DO_TSDICT;
9571 9144 : dictinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9572 9144 : dictinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9573 9144 : AssignDumpId(&dictinfo[i].dobj);
9574 9144 : dictinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_dictname));
9575 18288 : dictinfo[i].dobj.namespace =
9576 9144 : findNamespace(atooid(PQgetvalue(res, i, i_dictnamespace)));
9577 9144 : dictinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_dictowner));
9578 9144 : dictinfo[i].dicttemplate = atooid(PQgetvalue(res, i, i_dicttemplate));
9579 9144 : if (PQgetisnull(res, i, i_dictinitoption))
9580 394 : dictinfo[i].dictinitoption = NULL;
9581 : else
9582 8750 : dictinfo[i].dictinitoption = pg_strdup(PQgetvalue(res, i, i_dictinitoption));
9583 :
9584 : /* Decide whether we want to dump it */
9585 9144 : selectDumpableObject(&(dictinfo[i].dobj), fout);
9586 : }
9587 :
9588 308 : PQclear(res);
9589 :
9590 308 : destroyPQExpBuffer(query);
9591 308 : }
9592 :
9593 : /*
9594 : * getTSTemplates:
9595 : * get information about all text search templates in the system catalogs
9596 : */
9597 : void
9598 308 : getTSTemplates(Archive *fout)
9599 : {
9600 : PGresult *res;
9601 : int ntups;
9602 : int i;
9603 : PQExpBuffer query;
9604 : TSTemplateInfo *tmplinfo;
9605 : int i_tableoid;
9606 : int i_oid;
9607 : int i_tmplname;
9608 : int i_tmplnamespace;
9609 : int i_tmplinit;
9610 : int i_tmpllexize;
9611 :
9612 308 : query = createPQExpBuffer();
9613 :
9614 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, tmplname, "
9615 : "tmplnamespace, tmplinit::oid, tmpllexize::oid "
9616 : "FROM pg_ts_template");
9617 :
9618 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9619 :
9620 308 : ntups = PQntuples(res);
9621 :
9622 308 : tmplinfo = (TSTemplateInfo *) pg_malloc(ntups * sizeof(TSTemplateInfo));
9623 :
9624 308 : i_tableoid = PQfnumber(res, "tableoid");
9625 308 : i_oid = PQfnumber(res, "oid");
9626 308 : i_tmplname = PQfnumber(res, "tmplname");
9627 308 : i_tmplnamespace = PQfnumber(res, "tmplnamespace");
9628 308 : i_tmplinit = PQfnumber(res, "tmplinit");
9629 308 : i_tmpllexize = PQfnumber(res, "tmpllexize");
9630 :
9631 1934 : for (i = 0; i < ntups; i++)
9632 : {
9633 1626 : tmplinfo[i].dobj.objType = DO_TSTEMPLATE;
9634 1626 : tmplinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9635 1626 : tmplinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9636 1626 : AssignDumpId(&tmplinfo[i].dobj);
9637 1626 : tmplinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_tmplname));
9638 3252 : tmplinfo[i].dobj.namespace =
9639 1626 : findNamespace(atooid(PQgetvalue(res, i, i_tmplnamespace)));
9640 1626 : tmplinfo[i].tmplinit = atooid(PQgetvalue(res, i, i_tmplinit));
9641 1626 : tmplinfo[i].tmpllexize = atooid(PQgetvalue(res, i, i_tmpllexize));
9642 :
9643 : /* Decide whether we want to dump it */
9644 1626 : selectDumpableObject(&(tmplinfo[i].dobj), fout);
9645 : }
9646 :
9647 308 : PQclear(res);
9648 :
9649 308 : destroyPQExpBuffer(query);
9650 308 : }
9651 :
9652 : /*
9653 : * getTSConfigurations:
9654 : * get information about all text search configurations
9655 : */
9656 : void
9657 308 : getTSConfigurations(Archive *fout)
9658 : {
9659 : PGresult *res;
9660 : int ntups;
9661 : int i;
9662 : PQExpBuffer query;
9663 : TSConfigInfo *cfginfo;
9664 : int i_tableoid;
9665 : int i_oid;
9666 : int i_cfgname;
9667 : int i_cfgnamespace;
9668 : int i_cfgowner;
9669 : int i_cfgparser;
9670 :
9671 308 : query = createPQExpBuffer();
9672 :
9673 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, cfgname, "
9674 : "cfgnamespace, cfgowner, cfgparser "
9675 : "FROM pg_ts_config");
9676 :
9677 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9678 :
9679 308 : ntups = PQntuples(res);
9680 :
9681 308 : cfginfo = (TSConfigInfo *) pg_malloc(ntups * sizeof(TSConfigInfo));
9682 :
9683 308 : i_tableoid = PQfnumber(res, "tableoid");
9684 308 : i_oid = PQfnumber(res, "oid");
9685 308 : i_cfgname = PQfnumber(res, "cfgname");
9686 308 : i_cfgnamespace = PQfnumber(res, "cfgnamespace");
9687 308 : i_cfgowner = PQfnumber(res, "cfgowner");
9688 308 : i_cfgparser = PQfnumber(res, "cfgparser");
9689 :
9690 9382 : for (i = 0; i < ntups; i++)
9691 : {
9692 9074 : cfginfo[i].dobj.objType = DO_TSCONFIG;
9693 9074 : cfginfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9694 9074 : cfginfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9695 9074 : AssignDumpId(&cfginfo[i].dobj);
9696 9074 : cfginfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_cfgname));
9697 18148 : cfginfo[i].dobj.namespace =
9698 9074 : findNamespace(atooid(PQgetvalue(res, i, i_cfgnamespace)));
9699 9074 : cfginfo[i].rolname = getRoleName(PQgetvalue(res, i, i_cfgowner));
9700 9074 : cfginfo[i].cfgparser = atooid(PQgetvalue(res, i, i_cfgparser));
9701 :
9702 : /* Decide whether we want to dump it */
9703 9074 : selectDumpableObject(&(cfginfo[i].dobj), fout);
9704 : }
9705 :
9706 308 : PQclear(res);
9707 :
9708 308 : destroyPQExpBuffer(query);
9709 308 : }
9710 :
9711 : /*
9712 : * getForeignDataWrappers:
9713 : * get information about all foreign-data wrappers in the system catalogs
9714 : */
9715 : void
9716 308 : getForeignDataWrappers(Archive *fout)
9717 : {
9718 : PGresult *res;
9719 : int ntups;
9720 : int i;
9721 : PQExpBuffer query;
9722 : FdwInfo *fdwinfo;
9723 : int i_tableoid;
9724 : int i_oid;
9725 : int i_fdwname;
9726 : int i_fdwowner;
9727 : int i_fdwhandler;
9728 : int i_fdwvalidator;
9729 : int i_fdwacl;
9730 : int i_acldefault;
9731 : int i_fdwoptions;
9732 :
9733 308 : query = createPQExpBuffer();
9734 :
9735 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, fdwname, "
9736 : "fdwowner, "
9737 : "fdwhandler::pg_catalog.regproc, "
9738 : "fdwvalidator::pg_catalog.regproc, "
9739 : "fdwacl, "
9740 : "acldefault('F', fdwowner) AS acldefault, "
9741 : "array_to_string(ARRAY("
9742 : "SELECT quote_ident(option_name) || ' ' || "
9743 : "quote_literal(option_value) "
9744 : "FROM pg_options_to_table(fdwoptions) "
9745 : "ORDER BY option_name"
9746 : "), E',\n ') AS fdwoptions "
9747 : "FROM pg_foreign_data_wrapper");
9748 :
9749 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9750 :
9751 308 : ntups = PQntuples(res);
9752 :
9753 308 : fdwinfo = (FdwInfo *) pg_malloc(ntups * sizeof(FdwInfo));
9754 :
9755 308 : i_tableoid = PQfnumber(res, "tableoid");
9756 308 : i_oid = PQfnumber(res, "oid");
9757 308 : i_fdwname = PQfnumber(res, "fdwname");
9758 308 : i_fdwowner = PQfnumber(res, "fdwowner");
9759 308 : i_fdwhandler = PQfnumber(res, "fdwhandler");
9760 308 : i_fdwvalidator = PQfnumber(res, "fdwvalidator");
9761 308 : i_fdwacl = PQfnumber(res, "fdwacl");
9762 308 : i_acldefault = PQfnumber(res, "acldefault");
9763 308 : i_fdwoptions = PQfnumber(res, "fdwoptions");
9764 :
9765 446 : for (i = 0; i < ntups; i++)
9766 : {
9767 138 : fdwinfo[i].dobj.objType = DO_FDW;
9768 138 : fdwinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9769 138 : fdwinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9770 138 : AssignDumpId(&fdwinfo[i].dobj);
9771 138 : fdwinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_fdwname));
9772 138 : fdwinfo[i].dobj.namespace = NULL;
9773 138 : fdwinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_fdwacl));
9774 138 : fdwinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
9775 138 : fdwinfo[i].dacl.privtype = 0;
9776 138 : fdwinfo[i].dacl.initprivs = NULL;
9777 138 : fdwinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_fdwowner));
9778 138 : fdwinfo[i].fdwhandler = pg_strdup(PQgetvalue(res, i, i_fdwhandler));
9779 138 : fdwinfo[i].fdwvalidator = pg_strdup(PQgetvalue(res, i, i_fdwvalidator));
9780 138 : fdwinfo[i].fdwoptions = pg_strdup(PQgetvalue(res, i, i_fdwoptions));
9781 :
9782 : /* Decide whether we want to dump it */
9783 138 : selectDumpableObject(&(fdwinfo[i].dobj), fout);
9784 :
9785 : /* Mark whether FDW has an ACL */
9786 138 : if (!PQgetisnull(res, i, i_fdwacl))
9787 86 : fdwinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
9788 : }
9789 :
9790 308 : PQclear(res);
9791 :
9792 308 : destroyPQExpBuffer(query);
9793 308 : }
9794 :
9795 : /*
9796 : * getForeignServers:
9797 : * get information about all foreign servers in the system catalogs
9798 : */
9799 : void
9800 308 : getForeignServers(Archive *fout)
9801 : {
9802 : PGresult *res;
9803 : int ntups;
9804 : int i;
9805 : PQExpBuffer query;
9806 : ForeignServerInfo *srvinfo;
9807 : int i_tableoid;
9808 : int i_oid;
9809 : int i_srvname;
9810 : int i_srvowner;
9811 : int i_srvfdw;
9812 : int i_srvtype;
9813 : int i_srvversion;
9814 : int i_srvacl;
9815 : int i_acldefault;
9816 : int i_srvoptions;
9817 :
9818 308 : query = createPQExpBuffer();
9819 :
9820 308 : appendPQExpBufferStr(query, "SELECT tableoid, oid, srvname, "
9821 : "srvowner, "
9822 : "srvfdw, srvtype, srvversion, srvacl, "
9823 : "acldefault('S', srvowner) AS acldefault, "
9824 : "array_to_string(ARRAY("
9825 : "SELECT quote_ident(option_name) || ' ' || "
9826 : "quote_literal(option_value) "
9827 : "FROM pg_options_to_table(srvoptions) "
9828 : "ORDER BY option_name"
9829 : "), E',\n ') AS srvoptions "
9830 : "FROM pg_foreign_server");
9831 :
9832 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9833 :
9834 308 : ntups = PQntuples(res);
9835 :
9836 308 : srvinfo = (ForeignServerInfo *) pg_malloc(ntups * sizeof(ForeignServerInfo));
9837 :
9838 308 : i_tableoid = PQfnumber(res, "tableoid");
9839 308 : i_oid = PQfnumber(res, "oid");
9840 308 : i_srvname = PQfnumber(res, "srvname");
9841 308 : i_srvowner = PQfnumber(res, "srvowner");
9842 308 : i_srvfdw = PQfnumber(res, "srvfdw");
9843 308 : i_srvtype = PQfnumber(res, "srvtype");
9844 308 : i_srvversion = PQfnumber(res, "srvversion");
9845 308 : i_srvacl = PQfnumber(res, "srvacl");
9846 308 : i_acldefault = PQfnumber(res, "acldefault");
9847 308 : i_srvoptions = PQfnumber(res, "srvoptions");
9848 :
9849 454 : for (i = 0; i < ntups; i++)
9850 : {
9851 146 : srvinfo[i].dobj.objType = DO_FOREIGN_SERVER;
9852 146 : srvinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9853 146 : srvinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9854 146 : AssignDumpId(&srvinfo[i].dobj);
9855 146 : srvinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_srvname));
9856 146 : srvinfo[i].dobj.namespace = NULL;
9857 146 : srvinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_srvacl));
9858 146 : srvinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
9859 146 : srvinfo[i].dacl.privtype = 0;
9860 146 : srvinfo[i].dacl.initprivs = NULL;
9861 146 : srvinfo[i].rolname = getRoleName(PQgetvalue(res, i, i_srvowner));
9862 146 : srvinfo[i].srvfdw = atooid(PQgetvalue(res, i, i_srvfdw));
9863 146 : srvinfo[i].srvtype = pg_strdup(PQgetvalue(res, i, i_srvtype));
9864 146 : srvinfo[i].srvversion = pg_strdup(PQgetvalue(res, i, i_srvversion));
9865 146 : srvinfo[i].srvoptions = pg_strdup(PQgetvalue(res, i, i_srvoptions));
9866 :
9867 : /* Decide whether we want to dump it */
9868 146 : selectDumpableObject(&(srvinfo[i].dobj), fout);
9869 :
9870 : /* Servers have user mappings */
9871 146 : srvinfo[i].dobj.components |= DUMP_COMPONENT_USERMAP;
9872 :
9873 : /* Mark whether server has an ACL */
9874 146 : if (!PQgetisnull(res, i, i_srvacl))
9875 86 : srvinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
9876 : }
9877 :
9878 308 : PQclear(res);
9879 :
9880 308 : destroyPQExpBuffer(query);
9881 308 : }
9882 :
9883 : /*
9884 : * getDefaultACLs:
9885 : * get information about all default ACL information in the system catalogs
9886 : */
9887 : void
9888 308 : getDefaultACLs(Archive *fout)
9889 : {
9890 308 : DumpOptions *dopt = fout->dopt;
9891 : DefaultACLInfo *daclinfo;
9892 : PQExpBuffer query;
9893 : PGresult *res;
9894 : int i_oid;
9895 : int i_tableoid;
9896 : int i_defaclrole;
9897 : int i_defaclnamespace;
9898 : int i_defaclobjtype;
9899 : int i_defaclacl;
9900 : int i_acldefault;
9901 : int i,
9902 : ntups;
9903 :
9904 308 : query = createPQExpBuffer();
9905 :
9906 : /*
9907 : * Global entries (with defaclnamespace=0) replace the hard-wired default
9908 : * ACL for their object type. We should dump them as deltas from the
9909 : * default ACL, since that will be used as a starting point for
9910 : * interpreting the ALTER DEFAULT PRIVILEGES commands. On the other hand,
9911 : * non-global entries can only add privileges not revoke them. We must
9912 : * dump those as-is (i.e., as deltas from an empty ACL).
9913 : *
9914 : * We can use defaclobjtype as the object type for acldefault(), except
9915 : * for the case of 'S' (DEFACLOBJ_SEQUENCE) which must be converted to
9916 : * 's'.
9917 : */
9918 308 : appendPQExpBufferStr(query,
9919 : "SELECT oid, tableoid, "
9920 : "defaclrole, "
9921 : "defaclnamespace, "
9922 : "defaclobjtype, "
9923 : "defaclacl, "
9924 : "CASE WHEN defaclnamespace = 0 THEN "
9925 : "acldefault(CASE WHEN defaclobjtype = 'S' "
9926 : "THEN 's'::\"char\" ELSE defaclobjtype END, "
9927 : "defaclrole) ELSE '{}' END AS acldefault "
9928 : "FROM pg_default_acl");
9929 :
9930 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
9931 :
9932 308 : ntups = PQntuples(res);
9933 :
9934 308 : daclinfo = (DefaultACLInfo *) pg_malloc(ntups * sizeof(DefaultACLInfo));
9935 :
9936 308 : i_oid = PQfnumber(res, "oid");
9937 308 : i_tableoid = PQfnumber(res, "tableoid");
9938 308 : i_defaclrole = PQfnumber(res, "defaclrole");
9939 308 : i_defaclnamespace = PQfnumber(res, "defaclnamespace");
9940 308 : i_defaclobjtype = PQfnumber(res, "defaclobjtype");
9941 308 : i_defaclacl = PQfnumber(res, "defaclacl");
9942 308 : i_acldefault = PQfnumber(res, "acldefault");
9943 :
9944 652 : for (i = 0; i < ntups; i++)
9945 : {
9946 344 : Oid nspid = atooid(PQgetvalue(res, i, i_defaclnamespace));
9947 :
9948 344 : daclinfo[i].dobj.objType = DO_DEFAULT_ACL;
9949 344 : daclinfo[i].dobj.catId.tableoid = atooid(PQgetvalue(res, i, i_tableoid));
9950 344 : daclinfo[i].dobj.catId.oid = atooid(PQgetvalue(res, i, i_oid));
9951 344 : AssignDumpId(&daclinfo[i].dobj);
9952 : /* cheesy ... is it worth coming up with a better object name? */
9953 344 : daclinfo[i].dobj.name = pg_strdup(PQgetvalue(res, i, i_defaclobjtype));
9954 :
9955 344 : if (nspid != InvalidOid)
9956 172 : daclinfo[i].dobj.namespace = findNamespace(nspid);
9957 : else
9958 172 : daclinfo[i].dobj.namespace = NULL;
9959 :
9960 344 : daclinfo[i].dacl.acl = pg_strdup(PQgetvalue(res, i, i_defaclacl));
9961 344 : daclinfo[i].dacl.acldefault = pg_strdup(PQgetvalue(res, i, i_acldefault));
9962 344 : daclinfo[i].dacl.privtype = 0;
9963 344 : daclinfo[i].dacl.initprivs = NULL;
9964 344 : daclinfo[i].defaclrole = getRoleName(PQgetvalue(res, i, i_defaclrole));
9965 344 : daclinfo[i].defaclobjtype = *(PQgetvalue(res, i, i_defaclobjtype));
9966 :
9967 : /* Default ACLs are ACLs, of course */
9968 344 : daclinfo[i].dobj.components |= DUMP_COMPONENT_ACL;
9969 :
9970 : /* Decide whether we want to dump it */
9971 344 : selectDumpableDefaultACL(&(daclinfo[i]), dopt);
9972 : }
9973 :
9974 308 : PQclear(res);
9975 :
9976 308 : destroyPQExpBuffer(query);
9977 308 : }
9978 :
9979 : /*
9980 : * getRoleName -- look up the name of a role, given its OID
9981 : *
9982 : * In current usage, we don't expect failures, so error out for a bad OID.
9983 : */
9984 : static const char *
9985 965896 : getRoleName(const char *roleoid_str)
9986 : {
9987 965896 : Oid roleoid = atooid(roleoid_str);
9988 :
9989 : /*
9990 : * Do binary search to find the appropriate item.
9991 : */
9992 965896 : if (nrolenames > 0)
9993 : {
9994 965896 : RoleNameItem *low = &rolenames[0];
9995 965896 : RoleNameItem *high = &rolenames[nrolenames - 1];
9996 :
9997 3863950 : while (low <= high)
9998 : {
9999 3863950 : RoleNameItem *middle = low + (high - low) / 2;
10000 :
10001 3863950 : if (roleoid < middle->roleoid)
10002 2895630 : high = middle - 1;
10003 968320 : else if (roleoid > middle->roleoid)
10004 2424 : low = middle + 1;
10005 : else
10006 965896 : return middle->rolename; /* found a match */
10007 : }
10008 : }
10009 :
10010 0 : pg_fatal("role with OID %u does not exist", roleoid);
10011 : return NULL; /* keep compiler quiet */
10012 : }
10013 :
10014 : /*
10015 : * collectRoleNames --
10016 : *
10017 : * Construct a table of all known roles.
10018 : * The table is sorted by OID for speed in lookup.
10019 : */
10020 : static void
10021 310 : collectRoleNames(Archive *fout)
10022 : {
10023 : PGresult *res;
10024 : const char *query;
10025 : int i;
10026 :
10027 310 : query = "SELECT oid, rolname FROM pg_catalog.pg_roles ORDER BY 1";
10028 :
10029 310 : res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
10030 :
10031 310 : nrolenames = PQntuples(res);
10032 :
10033 310 : rolenames = (RoleNameItem *) pg_malloc(nrolenames * sizeof(RoleNameItem));
10034 :
10035 5980 : for (i = 0; i < nrolenames; i++)
10036 : {
10037 5670 : rolenames[i].roleoid = atooid(PQgetvalue(res, i, 0));
10038 5670 : rolenames[i].rolename = pg_strdup(PQgetvalue(res, i, 1));
10039 : }
10040 :
10041 310 : PQclear(res);
10042 310 : }
10043 :
10044 : /*
10045 : * getAdditionalACLs
10046 : *
10047 : * We have now created all the DumpableObjects, and collected the ACL data
10048 : * that appears in the directly-associated catalog entries. However, there's
10049 : * more ACL-related info to collect. If any of a table's columns have ACLs,
10050 : * we must set the TableInfo's DUMP_COMPONENT_ACL components flag, as well as
10051 : * its hascolumnACLs flag (we won't store the ACLs themselves here, though).
10052 : * Also, in versions having the pg_init_privs catalog, read that and load the
10053 : * information into the relevant DumpableObjects.
10054 : */
10055 : static void
10056 304 : getAdditionalACLs(Archive *fout)
10057 : {
10058 304 : PQExpBuffer query = createPQExpBuffer();
10059 : PGresult *res;
10060 : int ntups,
10061 : i;
10062 :
10063 : /* Check for per-column ACLs */
10064 304 : appendPQExpBufferStr(query,
10065 : "SELECT DISTINCT attrelid FROM pg_attribute "
10066 : "WHERE attacl IS NOT NULL");
10067 :
10068 304 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10069 :
10070 304 : ntups = PQntuples(res);
10071 936 : for (i = 0; i < ntups; i++)
10072 : {
10073 632 : Oid relid = atooid(PQgetvalue(res, i, 0));
10074 : TableInfo *tblinfo;
10075 :
10076 632 : tblinfo = findTableByOid(relid);
10077 : /* OK to ignore tables we haven't got a DumpableObject for */
10078 632 : if (tblinfo)
10079 : {
10080 632 : tblinfo->dobj.components |= DUMP_COMPONENT_ACL;
10081 632 : tblinfo->hascolumnACLs = true;
10082 : }
10083 : }
10084 304 : PQclear(res);
10085 :
10086 : /* Fetch initial-privileges data */
10087 304 : if (fout->remoteVersion >= 90600)
10088 : {
10089 304 : printfPQExpBuffer(query,
10090 : "SELECT objoid, classoid, objsubid, privtype, initprivs "
10091 : "FROM pg_init_privs");
10092 :
10093 304 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10094 :
10095 304 : ntups = PQntuples(res);
10096 69016 : for (i = 0; i < ntups; i++)
10097 : {
10098 68712 : Oid objoid = atooid(PQgetvalue(res, i, 0));
10099 68712 : Oid classoid = atooid(PQgetvalue(res, i, 1));
10100 68712 : int objsubid = atoi(PQgetvalue(res, i, 2));
10101 68712 : char privtype = *(PQgetvalue(res, i, 3));
10102 68712 : char *initprivs = PQgetvalue(res, i, 4);
10103 : CatalogId objId;
10104 : DumpableObject *dobj;
10105 :
10106 68712 : objId.tableoid = classoid;
10107 68712 : objId.oid = objoid;
10108 68712 : dobj = findObjectByCatalogId(objId);
10109 : /* OK to ignore entries we haven't got a DumpableObject for */
10110 68712 : if (dobj)
10111 : {
10112 : /* Cope with sub-object initprivs */
10113 49644 : if (objsubid != 0)
10114 : {
10115 5216 : if (dobj->objType == DO_TABLE)
10116 : {
10117 : /* For a column initprivs, set the table's ACL flags */
10118 5216 : dobj->components |= DUMP_COMPONENT_ACL;
10119 5216 : ((TableInfo *) dobj)->hascolumnACLs = true;
10120 : }
10121 : else
10122 0 : pg_log_warning("unsupported pg_init_privs entry: %u %u %d",
10123 : classoid, objoid, objsubid);
10124 5512 : continue;
10125 : }
10126 :
10127 : /*
10128 : * We ignore any pg_init_privs.initprivs entry for the public
10129 : * schema, as explained in getNamespaces().
10130 : */
10131 44428 : if (dobj->objType == DO_NAMESPACE &&
10132 600 : strcmp(dobj->name, "public") == 0)
10133 296 : continue;
10134 :
10135 : /* Else it had better be of a type we think has ACLs */
10136 44132 : if (dobj->objType == DO_NAMESPACE ||
10137 43828 : dobj->objType == DO_TYPE ||
10138 43780 : dobj->objType == DO_FUNC ||
10139 43600 : dobj->objType == DO_AGG ||
10140 43552 : dobj->objType == DO_TABLE ||
10141 0 : dobj->objType == DO_PROCLANG ||
10142 0 : dobj->objType == DO_FDW ||
10143 0 : dobj->objType == DO_FOREIGN_SERVER)
10144 44132 : {
10145 44132 : DumpableObjectWithAcl *daobj = (DumpableObjectWithAcl *) dobj;
10146 :
10147 44132 : daobj->dacl.privtype = privtype;
10148 44132 : daobj->dacl.initprivs = pstrdup(initprivs);
10149 : }
10150 : else
10151 0 : pg_log_warning("unsupported pg_init_privs entry: %u %u %d",
10152 : classoid, objoid, objsubid);
10153 : }
10154 : }
10155 304 : PQclear(res);
10156 : }
10157 :
10158 304 : destroyPQExpBuffer(query);
10159 304 : }
10160 :
10161 : /*
10162 : * dumpCommentExtended --
10163 : *
10164 : * This routine is used to dump any comments associated with the
10165 : * object handed to this routine. The routine takes the object type
10166 : * and object name (ready to print, except for schema decoration), plus
10167 : * the namespace and owner of the object (for labeling the ArchiveEntry),
10168 : * plus catalog ID and subid which are the lookup key for pg_description,
10169 : * plus the dump ID for the object (for setting a dependency).
10170 : * If a matching pg_description entry is found, it is dumped.
10171 : *
10172 : * Note: in some cases, such as comments for triggers and rules, the "type"
10173 : * string really looks like, e.g., "TRIGGER name ON". This is a bit of a hack
10174 : * but it doesn't seem worth complicating the API for all callers to make
10175 : * it cleaner.
10176 : *
10177 : * Note: although this routine takes a dumpId for dependency purposes,
10178 : * that purpose is just to mark the dependency in the emitted dump file
10179 : * for possible future use by pg_restore. We do NOT use it for determining
10180 : * ordering of the comment in the dump file, because this routine is called
10181 : * after dependency sorting occurs. This routine should be called just after
10182 : * calling ArchiveEntry() for the specified object.
10183 : */
10184 : static void
10185 12540 : dumpCommentExtended(Archive *fout, const char *type,
10186 : const char *name, const char *namespace,
10187 : const char *owner, CatalogId catalogId,
10188 : int subid, DumpId dumpId,
10189 : const char *initdb_comment)
10190 : {
10191 12540 : DumpOptions *dopt = fout->dopt;
10192 : CommentItem *comments;
10193 : int ncomments;
10194 :
10195 : /* do nothing, if --no-comments is supplied */
10196 12540 : if (dopt->no_comments)
10197 0 : return;
10198 :
10199 : /* Comments are schema not data ... except LO comments are data */
10200 12540 : if (strcmp(type, "LARGE OBJECT") != 0)
10201 : {
10202 12442 : if (dopt->dataOnly)
10203 0 : return;
10204 : }
10205 : else
10206 : {
10207 : /* We do dump LO comments in binary-upgrade mode */
10208 98 : if (dopt->schemaOnly && !dopt->binary_upgrade)
10209 0 : return;
10210 : }
10211 :
10212 : /* Search for comments associated with catalogId, using table */
10213 12540 : ncomments = findComments(catalogId.tableoid, catalogId.oid,
10214 : &comments);
10215 :
10216 : /* Is there one matching the subid? */
10217 12540 : while (ncomments > 0)
10218 : {
10219 12456 : if (comments->objsubid == subid)
10220 12456 : break;
10221 0 : comments++;
10222 0 : ncomments--;
10223 : }
10224 :
10225 12540 : if (initdb_comment != NULL)
10226 : {
10227 : static CommentItem empty_comment = {.descr = ""};
10228 :
10229 : /*
10230 : * initdb creates this object with a comment. Skip dumping the
10231 : * initdb-provided comment, which would complicate matters for
10232 : * non-superuser use of pg_dump. When the DBA has removed initdb's
10233 : * comment, replicate that.
10234 : */
10235 220 : if (ncomments == 0)
10236 : {
10237 8 : comments = &empty_comment;
10238 8 : ncomments = 1;
10239 : }
10240 212 : else if (strcmp(comments->descr, initdb_comment) == 0)
10241 212 : ncomments = 0;
10242 : }
10243 :
10244 : /* If a comment exists, build COMMENT ON statement */
10245 12540 : if (ncomments > 0)
10246 : {
10247 12252 : PQExpBuffer query = createPQExpBuffer();
10248 12252 : PQExpBuffer tag = createPQExpBuffer();
10249 :
10250 12252 : appendPQExpBuffer(query, "COMMENT ON %s ", type);
10251 12252 : if (namespace && *namespace)
10252 11958 : appendPQExpBuffer(query, "%s.", fmtId(namespace));
10253 12252 : appendPQExpBuffer(query, "%s IS ", name);
10254 12252 : appendStringLiteralAH(query, comments->descr, fout);
10255 12252 : appendPQExpBufferStr(query, ";\n");
10256 :
10257 12252 : appendPQExpBuffer(tag, "%s %s", type, name);
10258 :
10259 : /*
10260 : * We mark comments as SECTION_NONE because they really belong in the
10261 : * same section as their parent, whether that is pre-data or
10262 : * post-data.
10263 : */
10264 12252 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
10265 12252 : ARCHIVE_OPTS(.tag = tag->data,
10266 : .namespace = namespace,
10267 : .owner = owner,
10268 : .description = "COMMENT",
10269 : .section = SECTION_NONE,
10270 : .createStmt = query->data,
10271 : .deps = &dumpId,
10272 : .nDeps = 1));
10273 :
10274 12252 : destroyPQExpBuffer(query);
10275 12252 : destroyPQExpBuffer(tag);
10276 : }
10277 : }
10278 :
10279 : /*
10280 : * dumpComment --
10281 : *
10282 : * Typical simplification of the above function.
10283 : */
10284 : static inline void
10285 12286 : dumpComment(Archive *fout, const char *type,
10286 : const char *name, const char *namespace,
10287 : const char *owner, CatalogId catalogId,
10288 : int subid, DumpId dumpId)
10289 : {
10290 12286 : dumpCommentExtended(fout, type, name, namespace, owner,
10291 : catalogId, subid, dumpId, NULL);
10292 12286 : }
10293 :
10294 : /*
10295 : * dumpTableComment --
10296 : *
10297 : * As above, but dump comments for both the specified table (or view)
10298 : * and its columns.
10299 : */
10300 : static void
10301 152 : dumpTableComment(Archive *fout, const TableInfo *tbinfo,
10302 : const char *reltypename)
10303 : {
10304 152 : DumpOptions *dopt = fout->dopt;
10305 : CommentItem *comments;
10306 : int ncomments;
10307 : PQExpBuffer query;
10308 : PQExpBuffer tag;
10309 :
10310 : /* do nothing, if --no-comments is supplied */
10311 152 : if (dopt->no_comments)
10312 0 : return;
10313 :
10314 : /* Comments are SCHEMA not data */
10315 152 : if (dopt->dataOnly)
10316 0 : return;
10317 :
10318 : /* Search for comments associated with relation, using table */
10319 152 : ncomments = findComments(tbinfo->dobj.catId.tableoid,
10320 : tbinfo->dobj.catId.oid,
10321 : &comments);
10322 :
10323 : /* If comments exist, build COMMENT ON statements */
10324 152 : if (ncomments <= 0)
10325 0 : return;
10326 :
10327 152 : query = createPQExpBuffer();
10328 152 : tag = createPQExpBuffer();
10329 :
10330 436 : while (ncomments > 0)
10331 : {
10332 284 : const char *descr = comments->descr;
10333 284 : int objsubid = comments->objsubid;
10334 :
10335 284 : if (objsubid == 0)
10336 : {
10337 66 : resetPQExpBuffer(tag);
10338 66 : appendPQExpBuffer(tag, "%s %s", reltypename,
10339 66 : fmtId(tbinfo->dobj.name));
10340 :
10341 66 : resetPQExpBuffer(query);
10342 66 : appendPQExpBuffer(query, "COMMENT ON %s %s IS ", reltypename,
10343 66 : fmtQualifiedDumpable(tbinfo));
10344 66 : appendStringLiteralAH(query, descr, fout);
10345 66 : appendPQExpBufferStr(query, ";\n");
10346 :
10347 66 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
10348 66 : ARCHIVE_OPTS(.tag = tag->data,
10349 : .namespace = tbinfo->dobj.namespace->dobj.name,
10350 : .owner = tbinfo->rolname,
10351 : .description = "COMMENT",
10352 : .section = SECTION_NONE,
10353 : .createStmt = query->data,
10354 : .deps = &(tbinfo->dobj.dumpId),
10355 : .nDeps = 1));
10356 : }
10357 218 : else if (objsubid > 0 && objsubid <= tbinfo->numatts)
10358 : {
10359 218 : resetPQExpBuffer(tag);
10360 218 : appendPQExpBuffer(tag, "COLUMN %s.",
10361 218 : fmtId(tbinfo->dobj.name));
10362 218 : appendPQExpBufferStr(tag, fmtId(tbinfo->attnames[objsubid - 1]));
10363 :
10364 218 : resetPQExpBuffer(query);
10365 218 : appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
10366 218 : fmtQualifiedDumpable(tbinfo));
10367 218 : appendPQExpBuffer(query, "%s IS ",
10368 218 : fmtId(tbinfo->attnames[objsubid - 1]));
10369 218 : appendStringLiteralAH(query, descr, fout);
10370 218 : appendPQExpBufferStr(query, ";\n");
10371 :
10372 218 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
10373 218 : ARCHIVE_OPTS(.tag = tag->data,
10374 : .namespace = tbinfo->dobj.namespace->dobj.name,
10375 : .owner = tbinfo->rolname,
10376 : .description = "COMMENT",
10377 : .section = SECTION_NONE,
10378 : .createStmt = query->data,
10379 : .deps = &(tbinfo->dobj.dumpId),
10380 : .nDeps = 1));
10381 : }
10382 :
10383 284 : comments++;
10384 284 : ncomments--;
10385 : }
10386 :
10387 152 : destroyPQExpBuffer(query);
10388 152 : destroyPQExpBuffer(tag);
10389 : }
10390 :
10391 : /*
10392 : * findComments --
10393 : *
10394 : * Find the comment(s), if any, associated with the given object. All the
10395 : * objsubid values associated with the given classoid/objoid are found with
10396 : * one search.
10397 : */
10398 : static int
10399 12758 : findComments(Oid classoid, Oid objoid, CommentItem **items)
10400 : {
10401 12758 : CommentItem *middle = NULL;
10402 : CommentItem *low;
10403 : CommentItem *high;
10404 : int nmatch;
10405 :
10406 : /*
10407 : * Do binary search to find some item matching the object.
10408 : */
10409 12758 : low = &comments[0];
10410 12758 : high = &comments[ncomments - 1];
10411 126922 : while (low <= high)
10412 : {
10413 126838 : middle = low + (high - low) / 2;
10414 :
10415 126838 : if (classoid < middle->classoid)
10416 13168 : high = middle - 1;
10417 113670 : else if (classoid > middle->classoid)
10418 13812 : low = middle + 1;
10419 99858 : else if (objoid < middle->objoid)
10420 41992 : high = middle - 1;
10421 57866 : else if (objoid > middle->objoid)
10422 45192 : low = middle + 1;
10423 : else
10424 12674 : break; /* found a match */
10425 : }
10426 :
10427 12758 : if (low > high) /* no matches */
10428 : {
10429 84 : *items = NULL;
10430 84 : return 0;
10431 : }
10432 :
10433 : /*
10434 : * Now determine how many items match the object. The search loop
10435 : * invariant still holds: only items between low and high inclusive could
10436 : * match.
10437 : */
10438 12674 : nmatch = 1;
10439 12674 : while (middle > low)
10440 : {
10441 5828 : if (classoid != middle[-1].classoid ||
10442 5628 : objoid != middle[-1].objoid)
10443 : break;
10444 0 : middle--;
10445 0 : nmatch++;
10446 : }
10447 :
10448 12674 : *items = middle;
10449 :
10450 12674 : middle += nmatch;
10451 12806 : while (middle <= high)
10452 : {
10453 6762 : if (classoid != middle->classoid ||
10454 6286 : objoid != middle->objoid)
10455 : break;
10456 132 : middle++;
10457 132 : nmatch++;
10458 : }
10459 :
10460 12674 : return nmatch;
10461 : }
10462 :
10463 : /*
10464 : * collectComments --
10465 : *
10466 : * Construct a table of all comments available for database objects;
10467 : * also set the has-comment component flag for each relevant object.
10468 : *
10469 : * We used to do per-object queries for the comments, but it's much faster
10470 : * to pull them all over at once, and on most databases the memory cost
10471 : * isn't high.
10472 : *
10473 : * The table is sorted by classoid/objid/objsubid for speed in lookup.
10474 : */
10475 : static void
10476 308 : collectComments(Archive *fout)
10477 : {
10478 : PGresult *res;
10479 : PQExpBuffer query;
10480 : int i_description;
10481 : int i_classoid;
10482 : int i_objoid;
10483 : int i_objsubid;
10484 : int ntups;
10485 : int i;
10486 : DumpableObject *dobj;
10487 :
10488 308 : query = createPQExpBuffer();
10489 :
10490 308 : appendPQExpBufferStr(query, "SELECT description, classoid, objoid, objsubid "
10491 : "FROM pg_catalog.pg_description "
10492 : "ORDER BY classoid, objoid, objsubid");
10493 :
10494 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
10495 :
10496 : /* Construct lookup table containing OIDs in numeric form */
10497 :
10498 308 : i_description = PQfnumber(res, "description");
10499 308 : i_classoid = PQfnumber(res, "classoid");
10500 308 : i_objoid = PQfnumber(res, "objoid");
10501 308 : i_objsubid = PQfnumber(res, "objsubid");
10502 :
10503 308 : ntups = PQntuples(res);
10504 :
10505 308 : comments = (CommentItem *) pg_malloc(ntups * sizeof(CommentItem));
10506 308 : ncomments = 0;
10507 308 : dobj = NULL;
10508 :
10509 1618638 : for (i = 0; i < ntups; i++)
10510 : {
10511 : CatalogId objId;
10512 : int subid;
10513 :
10514 1618330 : objId.tableoid = atooid(PQgetvalue(res, i, i_classoid));
10515 1618330 : objId.oid = atooid(PQgetvalue(res, i, i_objoid));
10516 1618330 : subid = atoi(PQgetvalue(res, i, i_objsubid));
10517 :
10518 : /* We needn't remember comments that don't match any dumpable object */
10519 1618330 : if (dobj == NULL ||
10520 583500 : dobj->catId.tableoid != objId.tableoid ||
10521 579662 : dobj->catId.oid != objId.oid)
10522 1618158 : dobj = findObjectByCatalogId(objId);
10523 1618330 : if (dobj == NULL)
10524 1034534 : continue;
10525 :
10526 : /*
10527 : * Comments on columns of composite types are linked to the type's
10528 : * pg_class entry, but we need to set the DUMP_COMPONENT_COMMENT flag
10529 : * in the type's own DumpableObject.
10530 : */
10531 583796 : if (subid != 0 && dobj->objType == DO_TABLE &&
10532 372 : ((TableInfo *) dobj)->relkind == RELKIND_COMPOSITE_TYPE)
10533 86 : {
10534 : TypeInfo *cTypeInfo;
10535 :
10536 86 : cTypeInfo = findTypeByOid(((TableInfo *) dobj)->reltype);
10537 86 : if (cTypeInfo)
10538 86 : cTypeInfo->dobj.components |= DUMP_COMPONENT_COMMENT;
10539 : }
10540 : else
10541 583710 : dobj->components |= DUMP_COMPONENT_COMMENT;
10542 :
10543 583796 : comments[ncomments].descr = pg_strdup(PQgetvalue(res, i, i_description));
10544 583796 : comments[ncomments].classoid = objId.tableoid;
10545 583796 : comments[ncomments].objoid = objId.oid;
10546 583796 : comments[ncomments].objsubid = subid;
10547 583796 : ncomments++;
10548 : }
10549 :
10550 308 : PQclear(res);
10551 308 : destroyPQExpBuffer(query);
10552 308 : }
10553 :
10554 : /*
10555 : * dumpDumpableObject
10556 : *
10557 : * This routine and its subsidiaries are responsible for creating
10558 : * ArchiveEntries (TOC objects) for each object to be dumped.
10559 : */
10560 : static void
10561 1125784 : dumpDumpableObject(Archive *fout, DumpableObject *dobj)
10562 : {
10563 : /*
10564 : * Clear any dump-request bits for components that don't exist for this
10565 : * object. (This makes it safe to initially use DUMP_COMPONENT_ALL as the
10566 : * request for every kind of object.)
10567 : */
10568 1125784 : dobj->dump &= dobj->components;
10569 :
10570 : /* Now, short-circuit if there's nothing to be done here. */
10571 1125784 : if (dobj->dump == 0)
10572 1000290 : return;
10573 :
10574 125494 : switch (dobj->objType)
10575 : {
10576 784 : case DO_NAMESPACE:
10577 784 : dumpNamespace(fout, (const NamespaceInfo *) dobj);
10578 784 : break;
10579 38 : case DO_EXTENSION:
10580 38 : dumpExtension(fout, (const ExtensionInfo *) dobj);
10581 38 : break;
10582 1672 : case DO_TYPE:
10583 1672 : dumpType(fout, (const TypeInfo *) dobj);
10584 1672 : break;
10585 142 : case DO_SHELL_TYPE:
10586 142 : dumpShellType(fout, (const ShellTypeInfo *) dobj);
10587 142 : break;
10588 3556 : case DO_FUNC:
10589 3556 : dumpFunc(fout, (const FuncInfo *) dobj);
10590 3556 : break;
10591 580 : case DO_AGG:
10592 580 : dumpAgg(fout, (const AggInfo *) dobj);
10593 580 : break;
10594 5004 : case DO_OPERATOR:
10595 5004 : dumpOpr(fout, (const OprInfo *) dobj);
10596 5004 : break;
10597 152 : case DO_ACCESS_METHOD:
10598 152 : dumpAccessMethod(fout, (const AccessMethodInfo *) dobj);
10599 152 : break;
10600 1308 : case DO_OPCLASS:
10601 1308 : dumpOpclass(fout, (const OpclassInfo *) dobj);
10602 1308 : break;
10603 1090 : case DO_OPFAMILY:
10604 1090 : dumpOpfamily(fout, (const OpfamilyInfo *) dobj);
10605 1090 : break;
10606 4912 : case DO_COLLATION:
10607 4912 : dumpCollation(fout, (const CollInfo *) dobj);
10608 4912 : break;
10609 840 : case DO_CONVERSION:
10610 840 : dumpConversion(fout, (const ConvInfo *) dobj);
10611 840 : break;
10612 49974 : case DO_TABLE:
10613 49974 : dumpTable(fout, (const TableInfo *) dobj);
10614 49974 : break;
10615 2496 : case DO_TABLE_ATTACH:
10616 2496 : dumpTableAttach(fout, (const TableAttachInfo *) dobj);
10617 2496 : break;
10618 1520 : case DO_ATTRDEF:
10619 1520 : dumpAttrDef(fout, (const AttrDefInfo *) dobj);
10620 1520 : break;
10621 4740 : case DO_INDEX:
10622 4740 : dumpIndex(fout, (const IndxInfo *) dobj);
10623 4740 : break;
10624 1096 : case DO_INDEX_ATTACH:
10625 1096 : dumpIndexAttach(fout, (const IndexAttachInfo *) dobj);
10626 1096 : break;
10627 254 : case DO_STATSEXT:
10628 254 : dumpStatisticsExt(fout, (const StatsExtInfo *) dobj);
10629 254 : break;
10630 676 : case DO_REFRESH_MATVIEW:
10631 676 : refreshMatViewData(fout, (const TableDataInfo *) dobj);
10632 676 : break;
10633 2150 : case DO_RULE:
10634 2150 : dumpRule(fout, (const RuleInfo *) dobj);
10635 2150 : break;
10636 986 : case DO_TRIGGER:
10637 986 : dumpTrigger(fout, (const TriggerInfo *) dobj);
10638 986 : break;
10639 80 : case DO_EVENT_TRIGGER:
10640 80 : dumpEventTrigger(fout, (const EventTriggerInfo *) dobj);
10641 80 : break;
10642 4002 : case DO_CONSTRAINT:
10643 4002 : dumpConstraint(fout, (const ConstraintInfo *) dobj);
10644 4002 : break;
10645 344 : case DO_FK_CONSTRAINT:
10646 344 : dumpConstraint(fout, (const ConstraintInfo *) dobj);
10647 344 : break;
10648 156 : case DO_PROCLANG:
10649 156 : dumpProcLang(fout, (const ProcLangInfo *) dobj);
10650 156 : break;
10651 130 : case DO_CAST:
10652 130 : dumpCast(fout, (const CastInfo *) dobj);
10653 130 : break;
10654 80 : case DO_TRANSFORM:
10655 80 : dumpTransform(fout, (const TransformInfo *) dobj);
10656 80 : break;
10657 728 : case DO_SEQUENCE_SET:
10658 728 : dumpSequenceData(fout, (const TableDataInfo *) dobj);
10659 728 : break;
10660 7292 : case DO_TABLE_DATA:
10661 7292 : dumpTableData(fout, (const TableDataInfo *) dobj);
10662 7292 : break;
10663 24694 : case DO_DUMMY_TYPE:
10664 : /* table rowtypes and array types are never dumped separately */
10665 24694 : break;
10666 78 : case DO_TSPARSER:
10667 78 : dumpTSParser(fout, (const TSParserInfo *) dobj);
10668 78 : break;
10669 336 : case DO_TSDICT:
10670 336 : dumpTSDictionary(fout, (const TSDictInfo *) dobj);
10671 336 : break;
10672 102 : case DO_TSTEMPLATE:
10673 102 : dumpTSTemplate(fout, (const TSTemplateInfo *) dobj);
10674 102 : break;
10675 286 : case DO_TSCONFIG:
10676 286 : dumpTSConfig(fout, (const TSConfigInfo *) dobj);
10677 286 : break;
10678 100 : case DO_FDW:
10679 100 : dumpForeignDataWrapper(fout, (const FdwInfo *) dobj);
10680 100 : break;
10681 108 : case DO_FOREIGN_SERVER:
10682 108 : dumpForeignServer(fout, (const ForeignServerInfo *) dobj);
10683 108 : break;
10684 284 : case DO_DEFAULT_ACL:
10685 284 : dumpDefaultACL(fout, (const DefaultACLInfo *) dobj);
10686 284 : break;
10687 146 : case DO_LARGE_OBJECT:
10688 146 : dumpLO(fout, (const LoInfo *) dobj);
10689 146 : break;
10690 146 : case DO_LARGE_OBJECT_DATA:
10691 146 : if (dobj->dump & DUMP_COMPONENT_DATA)
10692 : {
10693 : LoInfo *loinfo;
10694 : TocEntry *te;
10695 :
10696 146 : loinfo = (LoInfo *) findObjectByDumpId(dobj->dependencies[0]);
10697 146 : if (loinfo == NULL)
10698 0 : pg_fatal("missing metadata for large objects \"%s\"",
10699 : dobj->name);
10700 :
10701 146 : te = ArchiveEntry(fout, dobj->catId, dobj->dumpId,
10702 146 : ARCHIVE_OPTS(.tag = dobj->name,
10703 : .owner = loinfo->rolname,
10704 : .description = "BLOBS",
10705 : .section = SECTION_DATA,
10706 : .deps = dobj->dependencies,
10707 : .nDeps = dobj->nDeps,
10708 : .dumpFn = dumpLOs,
10709 : .dumpArg = loinfo));
10710 :
10711 : /*
10712 : * Set the TocEntry's dataLength in case we are doing a
10713 : * parallel dump and want to order dump jobs by table size.
10714 : * (We need some size estimate for every TocEntry with a
10715 : * DataDumper function.) We don't currently have any cheap
10716 : * way to estimate the size of LOs, but fortunately it doesn't
10717 : * matter too much as long as we get large batches of LOs
10718 : * processed reasonably early. Assume 8K per blob.
10719 : */
10720 146 : te->dataLength = loinfo->numlos * (pgoff_t) 8192;
10721 : }
10722 146 : break;
10723 638 : case DO_POLICY:
10724 638 : dumpPolicy(fout, (const PolicyInfo *) dobj);
10725 638 : break;
10726 352 : case DO_PUBLICATION:
10727 352 : dumpPublication(fout, (const PublicationInfo *) dobj);
10728 352 : break;
10729 470 : case DO_PUBLICATION_REL:
10730 470 : dumpPublicationTable(fout, (const PublicationRelInfo *) dobj);
10731 470 : break;
10732 138 : case DO_PUBLICATION_TABLE_IN_SCHEMA:
10733 138 : dumpPublicationNamespace(fout,
10734 : (const PublicationSchemaInfo *) dobj);
10735 138 : break;
10736 214 : case DO_SUBSCRIPTION:
10737 214 : dumpSubscription(fout, (const SubscriptionInfo *) dobj);
10738 214 : break;
10739 4 : case DO_SUBSCRIPTION_REL:
10740 4 : dumpSubscriptionTable(fout, (const SubRelInfo *) dobj);
10741 4 : break;
10742 616 : case DO_PRE_DATA_BOUNDARY:
10743 : case DO_POST_DATA_BOUNDARY:
10744 : /* never dumped, nothing to do */
10745 616 : break;
10746 : }
10747 : }
10748 :
10749 : /*
10750 : * dumpNamespace
10751 : * writes out to fout the queries to recreate a user-defined namespace
10752 : */
10753 : static void
10754 784 : dumpNamespace(Archive *fout, const NamespaceInfo *nspinfo)
10755 : {
10756 784 : DumpOptions *dopt = fout->dopt;
10757 : PQExpBuffer q;
10758 : PQExpBuffer delq;
10759 : char *qnspname;
10760 :
10761 : /* Do nothing in data-only dump */
10762 784 : if (dopt->dataOnly)
10763 32 : return;
10764 :
10765 752 : q = createPQExpBuffer();
10766 752 : delq = createPQExpBuffer();
10767 :
10768 752 : qnspname = pg_strdup(fmtId(nspinfo->dobj.name));
10769 :
10770 752 : if (nspinfo->create)
10771 : {
10772 508 : appendPQExpBuffer(delq, "DROP SCHEMA %s;\n", qnspname);
10773 508 : appendPQExpBuffer(q, "CREATE SCHEMA %s;\n", qnspname);
10774 : }
10775 : else
10776 : {
10777 : /* see selectDumpableNamespace() */
10778 244 : appendPQExpBufferStr(delq,
10779 : "-- *not* dropping schema, since initdb creates it\n");
10780 244 : appendPQExpBufferStr(q,
10781 : "-- *not* creating schema, since initdb creates it\n");
10782 : }
10783 :
10784 752 : if (dopt->binary_upgrade)
10785 82 : binary_upgrade_extension_member(q, &nspinfo->dobj,
10786 : "SCHEMA", qnspname, NULL);
10787 :
10788 752 : if (nspinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10789 326 : ArchiveEntry(fout, nspinfo->dobj.catId, nspinfo->dobj.dumpId,
10790 326 : ARCHIVE_OPTS(.tag = nspinfo->dobj.name,
10791 : .owner = nspinfo->rolname,
10792 : .description = "SCHEMA",
10793 : .section = SECTION_PRE_DATA,
10794 : .createStmt = q->data,
10795 : .dropStmt = delq->data));
10796 :
10797 : /* Dump Schema Comments and Security Labels */
10798 752 : if (nspinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10799 : {
10800 254 : const char *initdb_comment = NULL;
10801 :
10802 254 : if (!nspinfo->create && strcmp(qnspname, "public") == 0)
10803 220 : initdb_comment = "standard public schema";
10804 254 : dumpCommentExtended(fout, "SCHEMA", qnspname,
10805 : NULL, nspinfo->rolname,
10806 : nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId,
10807 : initdb_comment);
10808 : }
10809 :
10810 752 : if (nspinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10811 0 : dumpSecLabel(fout, "SCHEMA", qnspname,
10812 : NULL, nspinfo->rolname,
10813 : nspinfo->dobj.catId, 0, nspinfo->dobj.dumpId);
10814 :
10815 752 : if (nspinfo->dobj.dump & DUMP_COMPONENT_ACL)
10816 586 : dumpACL(fout, nspinfo->dobj.dumpId, InvalidDumpId, "SCHEMA",
10817 : qnspname, NULL, NULL,
10818 : NULL, nspinfo->rolname, &nspinfo->dacl);
10819 :
10820 752 : free(qnspname);
10821 :
10822 752 : destroyPQExpBuffer(q);
10823 752 : destroyPQExpBuffer(delq);
10824 : }
10825 :
10826 : /*
10827 : * dumpExtension
10828 : * writes out to fout the queries to recreate an extension
10829 : */
10830 : static void
10831 38 : dumpExtension(Archive *fout, const ExtensionInfo *extinfo)
10832 : {
10833 38 : DumpOptions *dopt = fout->dopt;
10834 : PQExpBuffer q;
10835 : PQExpBuffer delq;
10836 : char *qextname;
10837 :
10838 : /* Do nothing in data-only dump */
10839 38 : if (dopt->dataOnly)
10840 2 : return;
10841 :
10842 36 : q = createPQExpBuffer();
10843 36 : delq = createPQExpBuffer();
10844 :
10845 36 : qextname = pg_strdup(fmtId(extinfo->dobj.name));
10846 :
10847 36 : appendPQExpBuffer(delq, "DROP EXTENSION %s;\n", qextname);
10848 :
10849 36 : if (!dopt->binary_upgrade)
10850 : {
10851 : /*
10852 : * In a regular dump, we simply create the extension, intentionally
10853 : * not specifying a version, so that the destination installation's
10854 : * default version is used.
10855 : *
10856 : * Use of IF NOT EXISTS here is unlike our behavior for other object
10857 : * types; but there are various scenarios in which it's convenient to
10858 : * manually create the desired extension before restoring, so we
10859 : * prefer to allow it to exist already.
10860 : */
10861 34 : appendPQExpBuffer(q, "CREATE EXTENSION IF NOT EXISTS %s WITH SCHEMA %s;\n",
10862 34 : qextname, fmtId(extinfo->namespace));
10863 : }
10864 : else
10865 : {
10866 : /*
10867 : * In binary-upgrade mode, it's critical to reproduce the state of the
10868 : * database exactly, so our procedure is to create an empty extension,
10869 : * restore all the contained objects normally, and add them to the
10870 : * extension one by one. This function performs just the first of
10871 : * those steps. binary_upgrade_extension_member() takes care of
10872 : * adding member objects as they're created.
10873 : */
10874 : int i;
10875 : int n;
10876 :
10877 2 : appendPQExpBufferStr(q, "-- For binary upgrade, create an empty extension and insert objects into it\n");
10878 :
10879 : /*
10880 : * We unconditionally create the extension, so we must drop it if it
10881 : * exists. This could happen if the user deleted 'plpgsql' and then
10882 : * readded it, causing its oid to be greater than g_last_builtin_oid.
10883 : */
10884 2 : appendPQExpBuffer(q, "DROP EXTENSION IF EXISTS %s;\n", qextname);
10885 :
10886 2 : appendPQExpBufferStr(q,
10887 : "SELECT pg_catalog.binary_upgrade_create_empty_extension(");
10888 2 : appendStringLiteralAH(q, extinfo->dobj.name, fout);
10889 2 : appendPQExpBufferStr(q, ", ");
10890 2 : appendStringLiteralAH(q, extinfo->namespace, fout);
10891 2 : appendPQExpBufferStr(q, ", ");
10892 2 : appendPQExpBuffer(q, "%s, ", extinfo->relocatable ? "true" : "false");
10893 2 : appendStringLiteralAH(q, extinfo->extversion, fout);
10894 2 : appendPQExpBufferStr(q, ", ");
10895 :
10896 : /*
10897 : * Note that we're pushing extconfig (an OID array) back into
10898 : * pg_extension exactly as-is. This is OK because pg_class OIDs are
10899 : * preserved in binary upgrade.
10900 : */
10901 2 : if (strlen(extinfo->extconfig) > 2)
10902 2 : appendStringLiteralAH(q, extinfo->extconfig, fout);
10903 : else
10904 0 : appendPQExpBufferStr(q, "NULL");
10905 2 : appendPQExpBufferStr(q, ", ");
10906 2 : if (strlen(extinfo->extcondition) > 2)
10907 2 : appendStringLiteralAH(q, extinfo->extcondition, fout);
10908 : else
10909 0 : appendPQExpBufferStr(q, "NULL");
10910 2 : appendPQExpBufferStr(q, ", ");
10911 2 : appendPQExpBufferStr(q, "ARRAY[");
10912 2 : n = 0;
10913 4 : for (i = 0; i < extinfo->dobj.nDeps; i++)
10914 : {
10915 : DumpableObject *extobj;
10916 :
10917 2 : extobj = findObjectByDumpId(extinfo->dobj.dependencies[i]);
10918 2 : if (extobj && extobj->objType == DO_EXTENSION)
10919 : {
10920 0 : if (n++ > 0)
10921 0 : appendPQExpBufferChar(q, ',');
10922 0 : appendStringLiteralAH(q, extobj->name, fout);
10923 : }
10924 : }
10925 2 : appendPQExpBufferStr(q, "]::pg_catalog.text[]");
10926 2 : appendPQExpBufferStr(q, ");\n");
10927 : }
10928 :
10929 36 : if (extinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
10930 36 : ArchiveEntry(fout, extinfo->dobj.catId, extinfo->dobj.dumpId,
10931 36 : ARCHIVE_OPTS(.tag = extinfo->dobj.name,
10932 : .description = "EXTENSION",
10933 : .section = SECTION_PRE_DATA,
10934 : .createStmt = q->data,
10935 : .dropStmt = delq->data));
10936 :
10937 : /* Dump Extension Comments and Security Labels */
10938 36 : if (extinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
10939 36 : dumpComment(fout, "EXTENSION", qextname,
10940 : NULL, "",
10941 : extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10942 :
10943 36 : if (extinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
10944 0 : dumpSecLabel(fout, "EXTENSION", qextname,
10945 : NULL, "",
10946 : extinfo->dobj.catId, 0, extinfo->dobj.dumpId);
10947 :
10948 36 : free(qextname);
10949 :
10950 36 : destroyPQExpBuffer(q);
10951 36 : destroyPQExpBuffer(delq);
10952 : }
10953 :
10954 : /*
10955 : * dumpType
10956 : * writes out to fout the queries to recreate a user-defined type
10957 : */
10958 : static void
10959 1672 : dumpType(Archive *fout, const TypeInfo *tyinfo)
10960 : {
10961 1672 : DumpOptions *dopt = fout->dopt;
10962 :
10963 : /* Do nothing in data-only dump */
10964 1672 : if (dopt->dataOnly)
10965 44 : return;
10966 :
10967 : /* Dump out in proper style */
10968 1628 : if (tyinfo->typtype == TYPTYPE_BASE)
10969 556 : dumpBaseType(fout, tyinfo);
10970 1072 : else if (tyinfo->typtype == TYPTYPE_DOMAIN)
10971 266 : dumpDomain(fout, tyinfo);
10972 806 : else if (tyinfo->typtype == TYPTYPE_COMPOSITE)
10973 262 : dumpCompositeType(fout, tyinfo);
10974 544 : else if (tyinfo->typtype == TYPTYPE_ENUM)
10975 110 : dumpEnumType(fout, tyinfo);
10976 434 : else if (tyinfo->typtype == TYPTYPE_RANGE)
10977 208 : dumpRangeType(fout, tyinfo);
10978 226 : else if (tyinfo->typtype == TYPTYPE_PSEUDO && !tyinfo->isDefined)
10979 76 : dumpUndefinedType(fout, tyinfo);
10980 : else
10981 150 : pg_log_warning("typtype of data type \"%s\" appears to be invalid",
10982 : tyinfo->dobj.name);
10983 : }
10984 :
10985 : /*
10986 : * dumpEnumType
10987 : * writes out to fout the queries to recreate a user-defined enum type
10988 : */
10989 : static void
10990 110 : dumpEnumType(Archive *fout, const TypeInfo *tyinfo)
10991 : {
10992 110 : DumpOptions *dopt = fout->dopt;
10993 110 : PQExpBuffer q = createPQExpBuffer();
10994 110 : PQExpBuffer delq = createPQExpBuffer();
10995 110 : PQExpBuffer query = createPQExpBuffer();
10996 : PGresult *res;
10997 : int num,
10998 : i;
10999 : Oid enum_oid;
11000 : char *qtypname;
11001 : char *qualtypname;
11002 : char *label;
11003 : int i_enumlabel;
11004 : int i_oid;
11005 :
11006 110 : if (!fout->is_prepared[PREPQUERY_DUMPENUMTYPE])
11007 : {
11008 : /* Set up query for enum-specific details */
11009 80 : appendPQExpBufferStr(query,
11010 : "PREPARE dumpEnumType(pg_catalog.oid) AS\n"
11011 : "SELECT oid, enumlabel "
11012 : "FROM pg_catalog.pg_enum "
11013 : "WHERE enumtypid = $1 "
11014 : "ORDER BY enumsortorder");
11015 :
11016 80 : ExecuteSqlStatement(fout, query->data);
11017 :
11018 80 : fout->is_prepared[PREPQUERY_DUMPENUMTYPE] = true;
11019 : }
11020 :
11021 110 : printfPQExpBuffer(query,
11022 : "EXECUTE dumpEnumType('%u')",
11023 : tyinfo->dobj.catId.oid);
11024 :
11025 110 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11026 :
11027 110 : num = PQntuples(res);
11028 :
11029 110 : qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11030 110 : qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11031 :
11032 : /*
11033 : * CASCADE shouldn't be required here as for normal types since the I/O
11034 : * functions are generic and do not get dropped.
11035 : */
11036 110 : appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11037 :
11038 110 : if (dopt->binary_upgrade)
11039 10 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
11040 : tyinfo->dobj.catId.oid,
11041 : false, false);
11042 :
11043 110 : appendPQExpBuffer(q, "CREATE TYPE %s AS ENUM (",
11044 : qualtypname);
11045 :
11046 110 : if (!dopt->binary_upgrade)
11047 : {
11048 100 : i_enumlabel = PQfnumber(res, "enumlabel");
11049 :
11050 : /* Labels with server-assigned oids */
11051 732 : for (i = 0; i < num; i++)
11052 : {
11053 632 : label = PQgetvalue(res, i, i_enumlabel);
11054 632 : if (i > 0)
11055 532 : appendPQExpBufferChar(q, ',');
11056 632 : appendPQExpBufferStr(q, "\n ");
11057 632 : appendStringLiteralAH(q, label, fout);
11058 : }
11059 : }
11060 :
11061 110 : appendPQExpBufferStr(q, "\n);\n");
11062 :
11063 110 : if (dopt->binary_upgrade)
11064 : {
11065 10 : i_oid = PQfnumber(res, "oid");
11066 10 : i_enumlabel = PQfnumber(res, "enumlabel");
11067 :
11068 : /* Labels with dump-assigned (preserved) oids */
11069 116 : for (i = 0; i < num; i++)
11070 : {
11071 106 : enum_oid = atooid(PQgetvalue(res, i, i_oid));
11072 106 : label = PQgetvalue(res, i, i_enumlabel);
11073 :
11074 106 : if (i == 0)
11075 10 : appendPQExpBufferStr(q, "\n-- For binary upgrade, must preserve pg_enum oids\n");
11076 106 : appendPQExpBuffer(q,
11077 : "SELECT pg_catalog.binary_upgrade_set_next_pg_enum_oid('%u'::pg_catalog.oid);\n",
11078 : enum_oid);
11079 106 : appendPQExpBuffer(q, "ALTER TYPE %s ADD VALUE ", qualtypname);
11080 106 : appendStringLiteralAH(q, label, fout);
11081 106 : appendPQExpBufferStr(q, ";\n\n");
11082 : }
11083 : }
11084 :
11085 110 : if (dopt->binary_upgrade)
11086 10 : binary_upgrade_extension_member(q, &tyinfo->dobj,
11087 : "TYPE", qtypname,
11088 10 : tyinfo->dobj.namespace->dobj.name);
11089 :
11090 110 : if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11091 110 : ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11092 110 : ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11093 : .namespace = tyinfo->dobj.namespace->dobj.name,
11094 : .owner = tyinfo->rolname,
11095 : .description = "TYPE",
11096 : .section = SECTION_PRE_DATA,
11097 : .createStmt = q->data,
11098 : .dropStmt = delq->data));
11099 :
11100 : /* Dump Type Comments and Security Labels */
11101 110 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11102 66 : dumpComment(fout, "TYPE", qtypname,
11103 66 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11104 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11105 :
11106 110 : if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11107 0 : dumpSecLabel(fout, "TYPE", qtypname,
11108 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11109 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11110 :
11111 110 : if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11112 66 : dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11113 : qtypname, NULL,
11114 66 : tyinfo->dobj.namespace->dobj.name,
11115 : NULL, tyinfo->rolname, &tyinfo->dacl);
11116 :
11117 110 : PQclear(res);
11118 110 : destroyPQExpBuffer(q);
11119 110 : destroyPQExpBuffer(delq);
11120 110 : destroyPQExpBuffer(query);
11121 110 : free(qtypname);
11122 110 : free(qualtypname);
11123 110 : }
11124 :
11125 : /*
11126 : * dumpRangeType
11127 : * writes out to fout the queries to recreate a user-defined range type
11128 : */
11129 : static void
11130 208 : dumpRangeType(Archive *fout, const TypeInfo *tyinfo)
11131 : {
11132 208 : DumpOptions *dopt = fout->dopt;
11133 208 : PQExpBuffer q = createPQExpBuffer();
11134 208 : PQExpBuffer delq = createPQExpBuffer();
11135 208 : PQExpBuffer query = createPQExpBuffer();
11136 : PGresult *res;
11137 : Oid collationOid;
11138 : char *qtypname;
11139 : char *qualtypname;
11140 : char *procname;
11141 :
11142 208 : if (!fout->is_prepared[PREPQUERY_DUMPRANGETYPE])
11143 : {
11144 : /* Set up query for range-specific details */
11145 82 : appendPQExpBufferStr(query,
11146 : "PREPARE dumpRangeType(pg_catalog.oid) AS\n");
11147 :
11148 82 : appendPQExpBufferStr(query,
11149 : "SELECT ");
11150 :
11151 82 : if (fout->remoteVersion >= 140000)
11152 82 : appendPQExpBufferStr(query,
11153 : "pg_catalog.format_type(rngmultitypid, NULL) AS rngmultitype, ");
11154 : else
11155 0 : appendPQExpBufferStr(query,
11156 : "NULL AS rngmultitype, ");
11157 :
11158 82 : appendPQExpBufferStr(query,
11159 : "pg_catalog.format_type(rngsubtype, NULL) AS rngsubtype, "
11160 : "opc.opcname AS opcname, "
11161 : "(SELECT nspname FROM pg_catalog.pg_namespace nsp "
11162 : " WHERE nsp.oid = opc.opcnamespace) AS opcnsp, "
11163 : "opc.opcdefault, "
11164 : "CASE WHEN rngcollation = st.typcollation THEN 0 "
11165 : " ELSE rngcollation END AS collation, "
11166 : "rngcanonical, rngsubdiff "
11167 : "FROM pg_catalog.pg_range r, pg_catalog.pg_type st, "
11168 : " pg_catalog.pg_opclass opc "
11169 : "WHERE st.oid = rngsubtype AND opc.oid = rngsubopc AND "
11170 : "rngtypid = $1");
11171 :
11172 82 : ExecuteSqlStatement(fout, query->data);
11173 :
11174 82 : fout->is_prepared[PREPQUERY_DUMPRANGETYPE] = true;
11175 : }
11176 :
11177 208 : printfPQExpBuffer(query,
11178 : "EXECUTE dumpRangeType('%u')",
11179 : tyinfo->dobj.catId.oid);
11180 :
11181 208 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
11182 :
11183 208 : qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11184 208 : qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11185 :
11186 : /*
11187 : * CASCADE shouldn't be required here as for normal types since the I/O
11188 : * functions are generic and do not get dropped.
11189 : */
11190 208 : appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11191 :
11192 208 : if (dopt->binary_upgrade)
11193 12 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
11194 : tyinfo->dobj.catId.oid,
11195 : false, true);
11196 :
11197 208 : appendPQExpBuffer(q, "CREATE TYPE %s AS RANGE (",
11198 : qualtypname);
11199 :
11200 208 : appendPQExpBuffer(q, "\n subtype = %s",
11201 : PQgetvalue(res, 0, PQfnumber(res, "rngsubtype")));
11202 :
11203 208 : if (!PQgetisnull(res, 0, PQfnumber(res, "rngmultitype")))
11204 208 : appendPQExpBuffer(q, ",\n multirange_type_name = %s",
11205 : PQgetvalue(res, 0, PQfnumber(res, "rngmultitype")));
11206 :
11207 : /* print subtype_opclass only if not default for subtype */
11208 208 : if (PQgetvalue(res, 0, PQfnumber(res, "opcdefault"))[0] != 't')
11209 : {
11210 66 : char *opcname = PQgetvalue(res, 0, PQfnumber(res, "opcname"));
11211 66 : char *nspname = PQgetvalue(res, 0, PQfnumber(res, "opcnsp"));
11212 :
11213 66 : appendPQExpBuffer(q, ",\n subtype_opclass = %s.",
11214 : fmtId(nspname));
11215 66 : appendPQExpBufferStr(q, fmtId(opcname));
11216 : }
11217 :
11218 208 : collationOid = atooid(PQgetvalue(res, 0, PQfnumber(res, "collation")));
11219 208 : if (OidIsValid(collationOid))
11220 : {
11221 76 : CollInfo *coll = findCollationByOid(collationOid);
11222 :
11223 76 : if (coll)
11224 76 : appendPQExpBuffer(q, ",\n collation = %s",
11225 76 : fmtQualifiedDumpable(coll));
11226 : }
11227 :
11228 208 : procname = PQgetvalue(res, 0, PQfnumber(res, "rngcanonical"));
11229 208 : if (strcmp(procname, "-") != 0)
11230 18 : appendPQExpBuffer(q, ",\n canonical = %s", procname);
11231 :
11232 208 : procname = PQgetvalue(res, 0, PQfnumber(res, "rngsubdiff"));
11233 208 : if (strcmp(procname, "-") != 0)
11234 46 : appendPQExpBuffer(q, ",\n subtype_diff = %s", procname);
11235 :
11236 208 : appendPQExpBufferStr(q, "\n);\n");
11237 :
11238 208 : if (dopt->binary_upgrade)
11239 12 : binary_upgrade_extension_member(q, &tyinfo->dobj,
11240 : "TYPE", qtypname,
11241 12 : tyinfo->dobj.namespace->dobj.name);
11242 :
11243 208 : if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11244 208 : ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11245 208 : ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11246 : .namespace = tyinfo->dobj.namespace->dobj.name,
11247 : .owner = tyinfo->rolname,
11248 : .description = "TYPE",
11249 : .section = SECTION_PRE_DATA,
11250 : .createStmt = q->data,
11251 : .dropStmt = delq->data));
11252 :
11253 : /* Dump Type Comments and Security Labels */
11254 208 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11255 102 : dumpComment(fout, "TYPE", qtypname,
11256 102 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11257 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11258 :
11259 208 : if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11260 0 : dumpSecLabel(fout, "TYPE", qtypname,
11261 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11262 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11263 :
11264 208 : if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11265 66 : dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11266 : qtypname, NULL,
11267 66 : tyinfo->dobj.namespace->dobj.name,
11268 : NULL, tyinfo->rolname, &tyinfo->dacl);
11269 :
11270 208 : PQclear(res);
11271 208 : destroyPQExpBuffer(q);
11272 208 : destroyPQExpBuffer(delq);
11273 208 : destroyPQExpBuffer(query);
11274 208 : free(qtypname);
11275 208 : free(qualtypname);
11276 208 : }
11277 :
11278 : /*
11279 : * dumpUndefinedType
11280 : * writes out to fout the queries to recreate a !typisdefined type
11281 : *
11282 : * This is a shell type, but we use different terminology to distinguish
11283 : * this case from where we have to emit a shell type definition to break
11284 : * circular dependencies. An undefined type shouldn't ever have anything
11285 : * depending on it.
11286 : */
11287 : static void
11288 76 : dumpUndefinedType(Archive *fout, const TypeInfo *tyinfo)
11289 : {
11290 76 : DumpOptions *dopt = fout->dopt;
11291 76 : PQExpBuffer q = createPQExpBuffer();
11292 76 : PQExpBuffer delq = createPQExpBuffer();
11293 : char *qtypname;
11294 : char *qualtypname;
11295 :
11296 76 : qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11297 76 : qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11298 :
11299 76 : appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11300 :
11301 76 : if (dopt->binary_upgrade)
11302 4 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
11303 : tyinfo->dobj.catId.oid,
11304 : false, false);
11305 :
11306 76 : appendPQExpBuffer(q, "CREATE TYPE %s;\n",
11307 : qualtypname);
11308 :
11309 76 : if (dopt->binary_upgrade)
11310 4 : binary_upgrade_extension_member(q, &tyinfo->dobj,
11311 : "TYPE", qtypname,
11312 4 : tyinfo->dobj.namespace->dobj.name);
11313 :
11314 76 : if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11315 76 : ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11316 76 : ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11317 : .namespace = tyinfo->dobj.namespace->dobj.name,
11318 : .owner = tyinfo->rolname,
11319 : .description = "TYPE",
11320 : .section = SECTION_PRE_DATA,
11321 : .createStmt = q->data,
11322 : .dropStmt = delq->data));
11323 :
11324 : /* Dump Type Comments and Security Labels */
11325 76 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11326 66 : dumpComment(fout, "TYPE", qtypname,
11327 66 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11328 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11329 :
11330 76 : if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11331 0 : dumpSecLabel(fout, "TYPE", qtypname,
11332 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11333 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11334 :
11335 76 : if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11336 0 : dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11337 : qtypname, NULL,
11338 0 : tyinfo->dobj.namespace->dobj.name,
11339 : NULL, tyinfo->rolname, &tyinfo->dacl);
11340 :
11341 76 : destroyPQExpBuffer(q);
11342 76 : destroyPQExpBuffer(delq);
11343 76 : free(qtypname);
11344 76 : free(qualtypname);
11345 76 : }
11346 :
11347 : /*
11348 : * dumpBaseType
11349 : * writes out to fout the queries to recreate a user-defined base type
11350 : */
11351 : static void
11352 556 : dumpBaseType(Archive *fout, const TypeInfo *tyinfo)
11353 : {
11354 556 : DumpOptions *dopt = fout->dopt;
11355 556 : PQExpBuffer q = createPQExpBuffer();
11356 556 : PQExpBuffer delq = createPQExpBuffer();
11357 556 : PQExpBuffer query = createPQExpBuffer();
11358 : PGresult *res;
11359 : char *qtypname;
11360 : char *qualtypname;
11361 : char *typlen;
11362 : char *typinput;
11363 : char *typoutput;
11364 : char *typreceive;
11365 : char *typsend;
11366 : char *typmodin;
11367 : char *typmodout;
11368 : char *typanalyze;
11369 : char *typsubscript;
11370 : Oid typreceiveoid;
11371 : Oid typsendoid;
11372 : Oid typmodinoid;
11373 : Oid typmodoutoid;
11374 : Oid typanalyzeoid;
11375 : Oid typsubscriptoid;
11376 : char *typcategory;
11377 : char *typispreferred;
11378 : char *typdelim;
11379 : char *typbyval;
11380 : char *typalign;
11381 : char *typstorage;
11382 : char *typcollatable;
11383 : char *typdefault;
11384 556 : bool typdefault_is_literal = false;
11385 :
11386 556 : if (!fout->is_prepared[PREPQUERY_DUMPBASETYPE])
11387 : {
11388 : /* Set up query for type-specific details */
11389 82 : appendPQExpBufferStr(query,
11390 : "PREPARE dumpBaseType(pg_catalog.oid) AS\n"
11391 : "SELECT typlen, "
11392 : "typinput, typoutput, typreceive, typsend, "
11393 : "typreceive::pg_catalog.oid AS typreceiveoid, "
11394 : "typsend::pg_catalog.oid AS typsendoid, "
11395 : "typanalyze, "
11396 : "typanalyze::pg_catalog.oid AS typanalyzeoid, "
11397 : "typdelim, typbyval, typalign, typstorage, "
11398 : "typmodin, typmodout, "
11399 : "typmodin::pg_catalog.oid AS typmodinoid, "
11400 : "typmodout::pg_catalog.oid AS typmodoutoid, "
11401 : "typcategory, typispreferred, "
11402 : "(typcollation <> 0) AS typcollatable, "
11403 : "pg_catalog.pg_get_expr(typdefaultbin, 0) AS typdefaultbin, typdefault, ");
11404 :
11405 82 : if (fout->remoteVersion >= 140000)
11406 82 : appendPQExpBufferStr(query,
11407 : "typsubscript, "
11408 : "typsubscript::pg_catalog.oid AS typsubscriptoid ");
11409 : else
11410 0 : appendPQExpBufferStr(query,
11411 : "'-' AS typsubscript, 0 AS typsubscriptoid ");
11412 :
11413 82 : appendPQExpBufferStr(query, "FROM pg_catalog.pg_type "
11414 : "WHERE oid = $1");
11415 :
11416 82 : ExecuteSqlStatement(fout, query->data);
11417 :
11418 82 : fout->is_prepared[PREPQUERY_DUMPBASETYPE] = true;
11419 : }
11420 :
11421 556 : printfPQExpBuffer(query,
11422 : "EXECUTE dumpBaseType('%u')",
11423 : tyinfo->dobj.catId.oid);
11424 :
11425 556 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
11426 :
11427 556 : typlen = PQgetvalue(res, 0, PQfnumber(res, "typlen"));
11428 556 : typinput = PQgetvalue(res, 0, PQfnumber(res, "typinput"));
11429 556 : typoutput = PQgetvalue(res, 0, PQfnumber(res, "typoutput"));
11430 556 : typreceive = PQgetvalue(res, 0, PQfnumber(res, "typreceive"));
11431 556 : typsend = PQgetvalue(res, 0, PQfnumber(res, "typsend"));
11432 556 : typmodin = PQgetvalue(res, 0, PQfnumber(res, "typmodin"));
11433 556 : typmodout = PQgetvalue(res, 0, PQfnumber(res, "typmodout"));
11434 556 : typanalyze = PQgetvalue(res, 0, PQfnumber(res, "typanalyze"));
11435 556 : typsubscript = PQgetvalue(res, 0, PQfnumber(res, "typsubscript"));
11436 556 : typreceiveoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typreceiveoid")));
11437 556 : typsendoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsendoid")));
11438 556 : typmodinoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodinoid")));
11439 556 : typmodoutoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typmodoutoid")));
11440 556 : typanalyzeoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typanalyzeoid")));
11441 556 : typsubscriptoid = atooid(PQgetvalue(res, 0, PQfnumber(res, "typsubscriptoid")));
11442 556 : typcategory = PQgetvalue(res, 0, PQfnumber(res, "typcategory"));
11443 556 : typispreferred = PQgetvalue(res, 0, PQfnumber(res, "typispreferred"));
11444 556 : typdelim = PQgetvalue(res, 0, PQfnumber(res, "typdelim"));
11445 556 : typbyval = PQgetvalue(res, 0, PQfnumber(res, "typbyval"));
11446 556 : typalign = PQgetvalue(res, 0, PQfnumber(res, "typalign"));
11447 556 : typstorage = PQgetvalue(res, 0, PQfnumber(res, "typstorage"));
11448 556 : typcollatable = PQgetvalue(res, 0, PQfnumber(res, "typcollatable"));
11449 556 : if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
11450 0 : typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
11451 556 : else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
11452 : {
11453 86 : typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
11454 86 : typdefault_is_literal = true; /* it needs quotes */
11455 : }
11456 : else
11457 470 : typdefault = NULL;
11458 :
11459 556 : qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11460 556 : qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11461 :
11462 : /*
11463 : * The reason we include CASCADE is that the circular dependency between
11464 : * the type and its I/O functions makes it impossible to drop the type any
11465 : * other way.
11466 : */
11467 556 : appendPQExpBuffer(delq, "DROP TYPE %s CASCADE;\n", qualtypname);
11468 :
11469 : /*
11470 : * We might already have a shell type, but setting pg_type_oid is
11471 : * harmless, and in any case we'd better set the array type OID.
11472 : */
11473 556 : if (dopt->binary_upgrade)
11474 16 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
11475 : tyinfo->dobj.catId.oid,
11476 : false, false);
11477 :
11478 556 : appendPQExpBuffer(q,
11479 : "CREATE TYPE %s (\n"
11480 : " INTERNALLENGTH = %s",
11481 : qualtypname,
11482 556 : (strcmp(typlen, "-1") == 0) ? "variable" : typlen);
11483 :
11484 : /* regproc result is sufficiently quoted already */
11485 556 : appendPQExpBuffer(q, ",\n INPUT = %s", typinput);
11486 556 : appendPQExpBuffer(q, ",\n OUTPUT = %s", typoutput);
11487 556 : if (OidIsValid(typreceiveoid))
11488 408 : appendPQExpBuffer(q, ",\n RECEIVE = %s", typreceive);
11489 556 : if (OidIsValid(typsendoid))
11490 408 : appendPQExpBuffer(q, ",\n SEND = %s", typsend);
11491 556 : if (OidIsValid(typmodinoid))
11492 70 : appendPQExpBuffer(q, ",\n TYPMOD_IN = %s", typmodin);
11493 556 : if (OidIsValid(typmodoutoid))
11494 70 : appendPQExpBuffer(q, ",\n TYPMOD_OUT = %s", typmodout);
11495 556 : if (OidIsValid(typanalyzeoid))
11496 6 : appendPQExpBuffer(q, ",\n ANALYZE = %s", typanalyze);
11497 :
11498 556 : if (strcmp(typcollatable, "t") == 0)
11499 60 : appendPQExpBufferStr(q, ",\n COLLATABLE = true");
11500 :
11501 556 : if (typdefault != NULL)
11502 : {
11503 86 : appendPQExpBufferStr(q, ",\n DEFAULT = ");
11504 86 : if (typdefault_is_literal)
11505 86 : appendStringLiteralAH(q, typdefault, fout);
11506 : else
11507 0 : appendPQExpBufferStr(q, typdefault);
11508 : }
11509 :
11510 556 : if (OidIsValid(typsubscriptoid))
11511 58 : appendPQExpBuffer(q, ",\n SUBSCRIPT = %s", typsubscript);
11512 :
11513 556 : if (OidIsValid(tyinfo->typelem))
11514 52 : appendPQExpBuffer(q, ",\n ELEMENT = %s",
11515 : getFormattedTypeName(fout, tyinfo->typelem,
11516 : zeroIsError));
11517 :
11518 556 : if (strcmp(typcategory, "U") != 0)
11519 : {
11520 310 : appendPQExpBufferStr(q, ",\n CATEGORY = ");
11521 310 : appendStringLiteralAH(q, typcategory, fout);
11522 : }
11523 :
11524 556 : if (strcmp(typispreferred, "t") == 0)
11525 58 : appendPQExpBufferStr(q, ",\n PREFERRED = true");
11526 :
11527 556 : if (typdelim && strcmp(typdelim, ",") != 0)
11528 : {
11529 6 : appendPQExpBufferStr(q, ",\n DELIMITER = ");
11530 6 : appendStringLiteralAH(q, typdelim, fout);
11531 : }
11532 :
11533 556 : if (*typalign == TYPALIGN_CHAR)
11534 24 : appendPQExpBufferStr(q, ",\n ALIGNMENT = char");
11535 532 : else if (*typalign == TYPALIGN_SHORT)
11536 12 : appendPQExpBufferStr(q, ",\n ALIGNMENT = int2");
11537 520 : else if (*typalign == TYPALIGN_INT)
11538 370 : appendPQExpBufferStr(q, ",\n ALIGNMENT = int4");
11539 150 : else if (*typalign == TYPALIGN_DOUBLE)
11540 150 : appendPQExpBufferStr(q, ",\n ALIGNMENT = double");
11541 :
11542 556 : if (*typstorage == TYPSTORAGE_PLAIN)
11543 406 : appendPQExpBufferStr(q, ",\n STORAGE = plain");
11544 150 : else if (*typstorage == TYPSTORAGE_EXTERNAL)
11545 0 : appendPQExpBufferStr(q, ",\n STORAGE = external");
11546 150 : else if (*typstorage == TYPSTORAGE_EXTENDED)
11547 132 : appendPQExpBufferStr(q, ",\n STORAGE = extended");
11548 18 : else if (*typstorage == TYPSTORAGE_MAIN)
11549 18 : appendPQExpBufferStr(q, ",\n STORAGE = main");
11550 :
11551 556 : if (strcmp(typbyval, "t") == 0)
11552 264 : appendPQExpBufferStr(q, ",\n PASSEDBYVALUE");
11553 :
11554 556 : appendPQExpBufferStr(q, "\n);\n");
11555 :
11556 556 : if (dopt->binary_upgrade)
11557 16 : binary_upgrade_extension_member(q, &tyinfo->dobj,
11558 : "TYPE", qtypname,
11559 16 : tyinfo->dobj.namespace->dobj.name);
11560 :
11561 556 : if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11562 556 : ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11563 556 : ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11564 : .namespace = tyinfo->dobj.namespace->dobj.name,
11565 : .owner = tyinfo->rolname,
11566 : .description = "TYPE",
11567 : .section = SECTION_PRE_DATA,
11568 : .createStmt = q->data,
11569 : .dropStmt = delq->data));
11570 :
11571 : /* Dump Type Comments and Security Labels */
11572 556 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11573 486 : dumpComment(fout, "TYPE", qtypname,
11574 486 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11575 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11576 :
11577 556 : if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11578 0 : dumpSecLabel(fout, "TYPE", qtypname,
11579 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11580 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11581 :
11582 556 : if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11583 66 : dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11584 : qtypname, NULL,
11585 66 : tyinfo->dobj.namespace->dobj.name,
11586 : NULL, tyinfo->rolname, &tyinfo->dacl);
11587 :
11588 556 : PQclear(res);
11589 556 : destroyPQExpBuffer(q);
11590 556 : destroyPQExpBuffer(delq);
11591 556 : destroyPQExpBuffer(query);
11592 556 : free(qtypname);
11593 556 : free(qualtypname);
11594 556 : }
11595 :
11596 : /*
11597 : * dumpDomain
11598 : * writes out to fout the queries to recreate a user-defined domain
11599 : */
11600 : static void
11601 266 : dumpDomain(Archive *fout, const TypeInfo *tyinfo)
11602 : {
11603 266 : DumpOptions *dopt = fout->dopt;
11604 266 : PQExpBuffer q = createPQExpBuffer();
11605 266 : PQExpBuffer delq = createPQExpBuffer();
11606 266 : PQExpBuffer query = createPQExpBuffer();
11607 : PGresult *res;
11608 : int i;
11609 : char *qtypname;
11610 : char *qualtypname;
11611 : char *typnotnull;
11612 : char *typdefn;
11613 : char *typdefault;
11614 : Oid typcollation;
11615 266 : bool typdefault_is_literal = false;
11616 :
11617 266 : if (!fout->is_prepared[PREPQUERY_DUMPDOMAIN])
11618 : {
11619 : /* Set up query for domain-specific details */
11620 76 : appendPQExpBufferStr(query,
11621 : "PREPARE dumpDomain(pg_catalog.oid) AS\n");
11622 :
11623 76 : appendPQExpBufferStr(query, "SELECT t.typnotnull, "
11624 : "pg_catalog.format_type(t.typbasetype, t.typtypmod) AS typdefn, "
11625 : "pg_catalog.pg_get_expr(t.typdefaultbin, 'pg_catalog.pg_type'::pg_catalog.regclass) AS typdefaultbin, "
11626 : "t.typdefault, "
11627 : "CASE WHEN t.typcollation <> u.typcollation "
11628 : "THEN t.typcollation ELSE 0 END AS typcollation "
11629 : "FROM pg_catalog.pg_type t "
11630 : "LEFT JOIN pg_catalog.pg_type u ON (t.typbasetype = u.oid) "
11631 : "WHERE t.oid = $1");
11632 :
11633 76 : ExecuteSqlStatement(fout, query->data);
11634 :
11635 76 : fout->is_prepared[PREPQUERY_DUMPDOMAIN] = true;
11636 : }
11637 :
11638 266 : printfPQExpBuffer(query,
11639 : "EXECUTE dumpDomain('%u')",
11640 : tyinfo->dobj.catId.oid);
11641 :
11642 266 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
11643 :
11644 266 : typnotnull = PQgetvalue(res, 0, PQfnumber(res, "typnotnull"));
11645 266 : typdefn = PQgetvalue(res, 0, PQfnumber(res, "typdefn"));
11646 266 : if (!PQgetisnull(res, 0, PQfnumber(res, "typdefaultbin")))
11647 76 : typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefaultbin"));
11648 190 : else if (!PQgetisnull(res, 0, PQfnumber(res, "typdefault")))
11649 : {
11650 0 : typdefault = PQgetvalue(res, 0, PQfnumber(res, "typdefault"));
11651 0 : typdefault_is_literal = true; /* it needs quotes */
11652 : }
11653 : else
11654 190 : typdefault = NULL;
11655 266 : typcollation = atooid(PQgetvalue(res, 0, PQfnumber(res, "typcollation")));
11656 :
11657 266 : if (dopt->binary_upgrade)
11658 42 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
11659 : tyinfo->dobj.catId.oid,
11660 : true, /* force array type */
11661 : false); /* force multirange type */
11662 :
11663 266 : qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11664 266 : qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11665 :
11666 266 : appendPQExpBuffer(q,
11667 : "CREATE DOMAIN %s AS %s",
11668 : qualtypname,
11669 : typdefn);
11670 :
11671 : /* Print collation only if different from base type's collation */
11672 266 : if (OidIsValid(typcollation))
11673 : {
11674 : CollInfo *coll;
11675 :
11676 66 : coll = findCollationByOid(typcollation);
11677 66 : if (coll)
11678 66 : appendPQExpBuffer(q, " COLLATE %s", fmtQualifiedDumpable(coll));
11679 : }
11680 :
11681 266 : if (typnotnull[0] == 't')
11682 30 : appendPQExpBufferStr(q, " NOT NULL");
11683 :
11684 266 : if (typdefault != NULL)
11685 : {
11686 76 : appendPQExpBufferStr(q, " DEFAULT ");
11687 76 : if (typdefault_is_literal)
11688 0 : appendStringLiteralAH(q, typdefault, fout);
11689 : else
11690 76 : appendPQExpBufferStr(q, typdefault);
11691 : }
11692 :
11693 266 : PQclear(res);
11694 :
11695 : /*
11696 : * Add any CHECK constraints for the domain
11697 : */
11698 442 : for (i = 0; i < tyinfo->nDomChecks; i++)
11699 : {
11700 176 : ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
11701 :
11702 176 : if (!domcheck->separate)
11703 176 : appendPQExpBuffer(q, "\n\tCONSTRAINT %s %s",
11704 176 : fmtId(domcheck->dobj.name), domcheck->condef);
11705 : }
11706 :
11707 266 : appendPQExpBufferStr(q, ";\n");
11708 :
11709 266 : appendPQExpBuffer(delq, "DROP DOMAIN %s;\n", qualtypname);
11710 :
11711 266 : if (dopt->binary_upgrade)
11712 42 : binary_upgrade_extension_member(q, &tyinfo->dobj,
11713 : "DOMAIN", qtypname,
11714 42 : tyinfo->dobj.namespace->dobj.name);
11715 :
11716 266 : if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11717 266 : ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11718 266 : ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11719 : .namespace = tyinfo->dobj.namespace->dobj.name,
11720 : .owner = tyinfo->rolname,
11721 : .description = "DOMAIN",
11722 : .section = SECTION_PRE_DATA,
11723 : .createStmt = q->data,
11724 : .dropStmt = delq->data));
11725 :
11726 : /* Dump Domain Comments and Security Labels */
11727 266 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11728 0 : dumpComment(fout, "DOMAIN", qtypname,
11729 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11730 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11731 :
11732 266 : if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11733 0 : dumpSecLabel(fout, "DOMAIN", qtypname,
11734 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11735 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11736 :
11737 266 : if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11738 66 : dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11739 : qtypname, NULL,
11740 66 : tyinfo->dobj.namespace->dobj.name,
11741 : NULL, tyinfo->rolname, &tyinfo->dacl);
11742 :
11743 : /* Dump any per-constraint comments */
11744 442 : for (i = 0; i < tyinfo->nDomChecks; i++)
11745 : {
11746 176 : ConstraintInfo *domcheck = &(tyinfo->domChecks[i]);
11747 176 : PQExpBuffer conprefix = createPQExpBuffer();
11748 :
11749 176 : appendPQExpBuffer(conprefix, "CONSTRAINT %s ON DOMAIN",
11750 176 : fmtId(domcheck->dobj.name));
11751 :
11752 176 : if (domcheck->dobj.dump & DUMP_COMPONENT_COMMENT)
11753 66 : dumpComment(fout, conprefix->data, qtypname,
11754 66 : tyinfo->dobj.namespace->dobj.name,
11755 : tyinfo->rolname,
11756 : domcheck->dobj.catId, 0, tyinfo->dobj.dumpId);
11757 :
11758 176 : destroyPQExpBuffer(conprefix);
11759 : }
11760 :
11761 266 : destroyPQExpBuffer(q);
11762 266 : destroyPQExpBuffer(delq);
11763 266 : destroyPQExpBuffer(query);
11764 266 : free(qtypname);
11765 266 : free(qualtypname);
11766 266 : }
11767 :
11768 : /*
11769 : * dumpCompositeType
11770 : * writes out to fout the queries to recreate a user-defined stand-alone
11771 : * composite type
11772 : */
11773 : static void
11774 262 : dumpCompositeType(Archive *fout, const TypeInfo *tyinfo)
11775 : {
11776 262 : DumpOptions *dopt = fout->dopt;
11777 262 : PQExpBuffer q = createPQExpBuffer();
11778 262 : PQExpBuffer dropped = createPQExpBuffer();
11779 262 : PQExpBuffer delq = createPQExpBuffer();
11780 262 : PQExpBuffer query = createPQExpBuffer();
11781 : PGresult *res;
11782 : char *qtypname;
11783 : char *qualtypname;
11784 : int ntups;
11785 : int i_attname;
11786 : int i_atttypdefn;
11787 : int i_attlen;
11788 : int i_attalign;
11789 : int i_attisdropped;
11790 : int i_attcollation;
11791 : int i;
11792 : int actual_atts;
11793 :
11794 262 : if (!fout->is_prepared[PREPQUERY_DUMPCOMPOSITETYPE])
11795 : {
11796 : /*
11797 : * Set up query for type-specific details.
11798 : *
11799 : * Since we only want to dump COLLATE clauses for attributes whose
11800 : * collation is different from their type's default, we use a CASE
11801 : * here to suppress uninteresting attcollations cheaply. atttypid
11802 : * will be 0 for dropped columns; collation does not matter for those.
11803 : */
11804 112 : appendPQExpBufferStr(query,
11805 : "PREPARE dumpCompositeType(pg_catalog.oid) AS\n"
11806 : "SELECT a.attname, a.attnum, "
11807 : "pg_catalog.format_type(a.atttypid, a.atttypmod) AS atttypdefn, "
11808 : "a.attlen, a.attalign, a.attisdropped, "
11809 : "CASE WHEN a.attcollation <> at.typcollation "
11810 : "THEN a.attcollation ELSE 0 END AS attcollation "
11811 : "FROM pg_catalog.pg_type ct "
11812 : "JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.typrelid "
11813 : "LEFT JOIN pg_catalog.pg_type at ON at.oid = a.atttypid "
11814 : "WHERE ct.oid = $1 "
11815 : "ORDER BY a.attnum");
11816 :
11817 112 : ExecuteSqlStatement(fout, query->data);
11818 :
11819 112 : fout->is_prepared[PREPQUERY_DUMPCOMPOSITETYPE] = true;
11820 : }
11821 :
11822 262 : printfPQExpBuffer(query,
11823 : "EXECUTE dumpCompositeType('%u')",
11824 : tyinfo->dobj.catId.oid);
11825 :
11826 262 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
11827 :
11828 262 : ntups = PQntuples(res);
11829 :
11830 262 : i_attname = PQfnumber(res, "attname");
11831 262 : i_atttypdefn = PQfnumber(res, "atttypdefn");
11832 262 : i_attlen = PQfnumber(res, "attlen");
11833 262 : i_attalign = PQfnumber(res, "attalign");
11834 262 : i_attisdropped = PQfnumber(res, "attisdropped");
11835 262 : i_attcollation = PQfnumber(res, "attcollation");
11836 :
11837 262 : if (dopt->binary_upgrade)
11838 : {
11839 36 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
11840 : tyinfo->dobj.catId.oid,
11841 : false, false);
11842 36 : binary_upgrade_set_pg_class_oids(fout, q, tyinfo->typrelid);
11843 : }
11844 :
11845 262 : qtypname = pg_strdup(fmtId(tyinfo->dobj.name));
11846 262 : qualtypname = pg_strdup(fmtQualifiedDumpable(tyinfo));
11847 :
11848 262 : appendPQExpBuffer(q, "CREATE TYPE %s AS (",
11849 : qualtypname);
11850 :
11851 262 : actual_atts = 0;
11852 830 : for (i = 0; i < ntups; i++)
11853 : {
11854 : char *attname;
11855 : char *atttypdefn;
11856 : char *attlen;
11857 : char *attalign;
11858 : bool attisdropped;
11859 : Oid attcollation;
11860 :
11861 568 : attname = PQgetvalue(res, i, i_attname);
11862 568 : atttypdefn = PQgetvalue(res, i, i_atttypdefn);
11863 568 : attlen = PQgetvalue(res, i, i_attlen);
11864 568 : attalign = PQgetvalue(res, i, i_attalign);
11865 568 : attisdropped = (PQgetvalue(res, i, i_attisdropped)[0] == 't');
11866 568 : attcollation = atooid(PQgetvalue(res, i, i_attcollation));
11867 :
11868 568 : if (attisdropped && !dopt->binary_upgrade)
11869 16 : continue;
11870 :
11871 : /* Format properly if not first attr */
11872 552 : if (actual_atts++ > 0)
11873 290 : appendPQExpBufferChar(q, ',');
11874 552 : appendPQExpBufferStr(q, "\n\t");
11875 :
11876 552 : if (!attisdropped)
11877 : {
11878 548 : appendPQExpBuffer(q, "%s %s", fmtId(attname), atttypdefn);
11879 :
11880 : /* Add collation if not default for the column type */
11881 548 : if (OidIsValid(attcollation))
11882 : {
11883 : CollInfo *coll;
11884 :
11885 0 : coll = findCollationByOid(attcollation);
11886 0 : if (coll)
11887 0 : appendPQExpBuffer(q, " COLLATE %s",
11888 0 : fmtQualifiedDumpable(coll));
11889 : }
11890 : }
11891 : else
11892 : {
11893 : /*
11894 : * This is a dropped attribute and we're in binary_upgrade mode.
11895 : * Insert a placeholder for it in the CREATE TYPE command, and set
11896 : * length and alignment with direct UPDATE to the catalogs
11897 : * afterwards. See similar code in dumpTableSchema().
11898 : */
11899 4 : appendPQExpBuffer(q, "%s INTEGER /* dummy */", fmtId(attname));
11900 :
11901 : /* stash separately for insertion after the CREATE TYPE */
11902 4 : appendPQExpBufferStr(dropped,
11903 : "\n-- For binary upgrade, recreate dropped column.\n");
11904 4 : appendPQExpBuffer(dropped, "UPDATE pg_catalog.pg_attribute\n"
11905 : "SET attlen = %s, "
11906 : "attalign = '%s', attbyval = false\n"
11907 : "WHERE attname = ", attlen, attalign);
11908 4 : appendStringLiteralAH(dropped, attname, fout);
11909 4 : appendPQExpBufferStr(dropped, "\n AND attrelid = ");
11910 4 : appendStringLiteralAH(dropped, qualtypname, fout);
11911 4 : appendPQExpBufferStr(dropped, "::pg_catalog.regclass;\n");
11912 :
11913 4 : appendPQExpBuffer(dropped, "ALTER TYPE %s ",
11914 : qualtypname);
11915 4 : appendPQExpBuffer(dropped, "DROP ATTRIBUTE %s;\n",
11916 : fmtId(attname));
11917 : }
11918 : }
11919 262 : appendPQExpBufferStr(q, "\n);\n");
11920 262 : appendPQExpBufferStr(q, dropped->data);
11921 :
11922 262 : appendPQExpBuffer(delq, "DROP TYPE %s;\n", qualtypname);
11923 :
11924 262 : if (dopt->binary_upgrade)
11925 36 : binary_upgrade_extension_member(q, &tyinfo->dobj,
11926 : "TYPE", qtypname,
11927 36 : tyinfo->dobj.namespace->dobj.name);
11928 :
11929 262 : if (tyinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
11930 228 : ArchiveEntry(fout, tyinfo->dobj.catId, tyinfo->dobj.dumpId,
11931 228 : ARCHIVE_OPTS(.tag = tyinfo->dobj.name,
11932 : .namespace = tyinfo->dobj.namespace->dobj.name,
11933 : .owner = tyinfo->rolname,
11934 : .description = "TYPE",
11935 : .section = SECTION_PRE_DATA,
11936 : .createStmt = q->data,
11937 : .dropStmt = delq->data));
11938 :
11939 :
11940 : /* Dump Type Comments and Security Labels */
11941 262 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11942 66 : dumpComment(fout, "TYPE", qtypname,
11943 66 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11944 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11945 :
11946 262 : if (tyinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
11947 0 : dumpSecLabel(fout, "TYPE", qtypname,
11948 0 : tyinfo->dobj.namespace->dobj.name, tyinfo->rolname,
11949 : tyinfo->dobj.catId, 0, tyinfo->dobj.dumpId);
11950 :
11951 262 : if (tyinfo->dobj.dump & DUMP_COMPONENT_ACL)
11952 36 : dumpACL(fout, tyinfo->dobj.dumpId, InvalidDumpId, "TYPE",
11953 : qtypname, NULL,
11954 36 : tyinfo->dobj.namespace->dobj.name,
11955 : NULL, tyinfo->rolname, &tyinfo->dacl);
11956 :
11957 : /* Dump any per-column comments */
11958 262 : if (tyinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
11959 66 : dumpCompositeTypeColComments(fout, tyinfo, res);
11960 :
11961 262 : PQclear(res);
11962 262 : destroyPQExpBuffer(q);
11963 262 : destroyPQExpBuffer(dropped);
11964 262 : destroyPQExpBuffer(delq);
11965 262 : destroyPQExpBuffer(query);
11966 262 : free(qtypname);
11967 262 : free(qualtypname);
11968 262 : }
11969 :
11970 : /*
11971 : * dumpCompositeTypeColComments
11972 : * writes out to fout the queries to recreate comments on the columns of
11973 : * a user-defined stand-alone composite type.
11974 : *
11975 : * The caller has already made a query to collect the names and attnums
11976 : * of the type's columns, so we just pass that result into here rather
11977 : * than reading them again.
11978 : */
11979 : static void
11980 66 : dumpCompositeTypeColComments(Archive *fout, const TypeInfo *tyinfo,
11981 : PGresult *res)
11982 : {
11983 : CommentItem *comments;
11984 : int ncomments;
11985 : PQExpBuffer query;
11986 : PQExpBuffer target;
11987 : int i;
11988 : int ntups;
11989 : int i_attname;
11990 : int i_attnum;
11991 : int i_attisdropped;
11992 :
11993 : /* do nothing, if --no-comments is supplied */
11994 66 : if (fout->dopt->no_comments)
11995 0 : return;
11996 :
11997 : /* Search for comments associated with type's pg_class OID */
11998 66 : ncomments = findComments(RelationRelationId, tyinfo->typrelid,
11999 : &comments);
12000 :
12001 : /* If no comments exist, we're done */
12002 66 : if (ncomments <= 0)
12003 0 : return;
12004 :
12005 : /* Build COMMENT ON statements */
12006 66 : query = createPQExpBuffer();
12007 66 : target = createPQExpBuffer();
12008 :
12009 66 : ntups = PQntuples(res);
12010 66 : i_attnum = PQfnumber(res, "attnum");
12011 66 : i_attname = PQfnumber(res, "attname");
12012 66 : i_attisdropped = PQfnumber(res, "attisdropped");
12013 132 : while (ncomments > 0)
12014 : {
12015 : const char *attname;
12016 :
12017 66 : attname = NULL;
12018 66 : for (i = 0; i < ntups; i++)
12019 : {
12020 66 : if (atoi(PQgetvalue(res, i, i_attnum)) == comments->objsubid &&
12021 66 : PQgetvalue(res, i, i_attisdropped)[0] != 't')
12022 : {
12023 66 : attname = PQgetvalue(res, i, i_attname);
12024 66 : break;
12025 : }
12026 : }
12027 66 : if (attname) /* just in case we don't find it */
12028 : {
12029 66 : const char *descr = comments->descr;
12030 :
12031 66 : resetPQExpBuffer(target);
12032 66 : appendPQExpBuffer(target, "COLUMN %s.",
12033 66 : fmtId(tyinfo->dobj.name));
12034 66 : appendPQExpBufferStr(target, fmtId(attname));
12035 :
12036 66 : resetPQExpBuffer(query);
12037 66 : appendPQExpBuffer(query, "COMMENT ON COLUMN %s.",
12038 66 : fmtQualifiedDumpable(tyinfo));
12039 66 : appendPQExpBuffer(query, "%s IS ", fmtId(attname));
12040 66 : appendStringLiteralAH(query, descr, fout);
12041 66 : appendPQExpBufferStr(query, ";\n");
12042 :
12043 66 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
12044 66 : ARCHIVE_OPTS(.tag = target->data,
12045 : .namespace = tyinfo->dobj.namespace->dobj.name,
12046 : .owner = tyinfo->rolname,
12047 : .description = "COMMENT",
12048 : .section = SECTION_NONE,
12049 : .createStmt = query->data,
12050 : .deps = &(tyinfo->dobj.dumpId),
12051 : .nDeps = 1));
12052 : }
12053 :
12054 66 : comments++;
12055 66 : ncomments--;
12056 : }
12057 :
12058 66 : destroyPQExpBuffer(query);
12059 66 : destroyPQExpBuffer(target);
12060 : }
12061 :
12062 : /*
12063 : * dumpShellType
12064 : * writes out to fout the queries to create a shell type
12065 : *
12066 : * We dump a shell definition in advance of the I/O functions for the type.
12067 : */
12068 : static void
12069 142 : dumpShellType(Archive *fout, const ShellTypeInfo *stinfo)
12070 : {
12071 142 : DumpOptions *dopt = fout->dopt;
12072 : PQExpBuffer q;
12073 :
12074 : /* Do nothing in data-only dump */
12075 142 : if (dopt->dataOnly)
12076 6 : return;
12077 :
12078 136 : q = createPQExpBuffer();
12079 :
12080 : /*
12081 : * Note the lack of a DROP command for the shell type; any required DROP
12082 : * is driven off the base type entry, instead. This interacts with
12083 : * _printTocEntry()'s use of the presence of a DROP command to decide
12084 : * whether an entry needs an ALTER OWNER command. We don't want to alter
12085 : * the shell type's owner immediately on creation; that should happen only
12086 : * after it's filled in, otherwise the backend complains.
12087 : */
12088 :
12089 136 : if (dopt->binary_upgrade)
12090 16 : binary_upgrade_set_type_oids_by_type_oid(fout, q,
12091 16 : stinfo->baseType->dobj.catId.oid,
12092 : false, false);
12093 :
12094 136 : appendPQExpBuffer(q, "CREATE TYPE %s;\n",
12095 136 : fmtQualifiedDumpable(stinfo));
12096 :
12097 136 : if (stinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12098 136 : ArchiveEntry(fout, stinfo->dobj.catId, stinfo->dobj.dumpId,
12099 136 : ARCHIVE_OPTS(.tag = stinfo->dobj.name,
12100 : .namespace = stinfo->dobj.namespace->dobj.name,
12101 : .owner = stinfo->baseType->rolname,
12102 : .description = "SHELL TYPE",
12103 : .section = SECTION_PRE_DATA,
12104 : .createStmt = q->data));
12105 :
12106 136 : destroyPQExpBuffer(q);
12107 : }
12108 :
12109 : /*
12110 : * dumpProcLang
12111 : * writes out to fout the queries to recreate a user-defined
12112 : * procedural language
12113 : */
12114 : static void
12115 156 : dumpProcLang(Archive *fout, const ProcLangInfo *plang)
12116 : {
12117 156 : DumpOptions *dopt = fout->dopt;
12118 : PQExpBuffer defqry;
12119 : PQExpBuffer delqry;
12120 : bool useParams;
12121 : char *qlanname;
12122 : FuncInfo *funcInfo;
12123 156 : FuncInfo *inlineInfo = NULL;
12124 156 : FuncInfo *validatorInfo = NULL;
12125 :
12126 : /* Do nothing in data-only dump */
12127 156 : if (dopt->dataOnly)
12128 14 : return;
12129 :
12130 : /*
12131 : * Try to find the support function(s). It is not an error if we don't
12132 : * find them --- if the functions are in the pg_catalog schema, as is
12133 : * standard in 8.1 and up, then we won't have loaded them. (In this case
12134 : * we will emit a parameterless CREATE LANGUAGE command, which will
12135 : * require PL template knowledge in the backend to reload.)
12136 : */
12137 :
12138 142 : funcInfo = findFuncByOid(plang->lanplcallfoid);
12139 142 : if (funcInfo != NULL && !funcInfo->dobj.dump)
12140 4 : funcInfo = NULL; /* treat not-dumped same as not-found */
12141 :
12142 142 : if (OidIsValid(plang->laninline))
12143 : {
12144 78 : inlineInfo = findFuncByOid(plang->laninline);
12145 78 : if (inlineInfo != NULL && !inlineInfo->dobj.dump)
12146 2 : inlineInfo = NULL;
12147 : }
12148 :
12149 142 : if (OidIsValid(plang->lanvalidator))
12150 : {
12151 78 : validatorInfo = findFuncByOid(plang->lanvalidator);
12152 78 : if (validatorInfo != NULL && !validatorInfo->dobj.dump)
12153 2 : validatorInfo = NULL;
12154 : }
12155 :
12156 : /*
12157 : * If the functions are dumpable then emit a complete CREATE LANGUAGE with
12158 : * parameters. Otherwise, we'll write a parameterless command, which will
12159 : * be interpreted as CREATE EXTENSION.
12160 : */
12161 62 : useParams = (funcInfo != NULL &&
12162 266 : (inlineInfo != NULL || !OidIsValid(plang->laninline)) &&
12163 62 : (validatorInfo != NULL || !OidIsValid(plang->lanvalidator)));
12164 :
12165 142 : defqry = createPQExpBuffer();
12166 142 : delqry = createPQExpBuffer();
12167 :
12168 142 : qlanname = pg_strdup(fmtId(plang->dobj.name));
12169 :
12170 142 : appendPQExpBuffer(delqry, "DROP PROCEDURAL LANGUAGE %s;\n",
12171 : qlanname);
12172 :
12173 142 : if (useParams)
12174 : {
12175 62 : appendPQExpBuffer(defqry, "CREATE %sPROCEDURAL LANGUAGE %s",
12176 62 : plang->lanpltrusted ? "TRUSTED " : "",
12177 : qlanname);
12178 62 : appendPQExpBuffer(defqry, " HANDLER %s",
12179 62 : fmtQualifiedDumpable(funcInfo));
12180 62 : if (OidIsValid(plang->laninline))
12181 0 : appendPQExpBuffer(defqry, " INLINE %s",
12182 0 : fmtQualifiedDumpable(inlineInfo));
12183 62 : if (OidIsValid(plang->lanvalidator))
12184 0 : appendPQExpBuffer(defqry, " VALIDATOR %s",
12185 0 : fmtQualifiedDumpable(validatorInfo));
12186 : }
12187 : else
12188 : {
12189 : /*
12190 : * If not dumping parameters, then use CREATE OR REPLACE so that the
12191 : * command will not fail if the language is preinstalled in the target
12192 : * database.
12193 : *
12194 : * Modern servers will interpret this as CREATE EXTENSION IF NOT
12195 : * EXISTS; perhaps we should emit that instead? But it might just add
12196 : * confusion.
12197 : */
12198 80 : appendPQExpBuffer(defqry, "CREATE OR REPLACE PROCEDURAL LANGUAGE %s",
12199 : qlanname);
12200 : }
12201 142 : appendPQExpBufferStr(defqry, ";\n");
12202 :
12203 142 : if (dopt->binary_upgrade)
12204 4 : binary_upgrade_extension_member(defqry, &plang->dobj,
12205 : "LANGUAGE", qlanname, NULL);
12206 :
12207 142 : if (plang->dobj.dump & DUMP_COMPONENT_DEFINITION)
12208 64 : ArchiveEntry(fout, plang->dobj.catId, plang->dobj.dumpId,
12209 64 : ARCHIVE_OPTS(.tag = plang->dobj.name,
12210 : .owner = plang->lanowner,
12211 : .description = "PROCEDURAL LANGUAGE",
12212 : .section = SECTION_PRE_DATA,
12213 : .createStmt = defqry->data,
12214 : .dropStmt = delqry->data,
12215 : ));
12216 :
12217 : /* Dump Proc Lang Comments and Security Labels */
12218 142 : if (plang->dobj.dump & DUMP_COMPONENT_COMMENT)
12219 0 : dumpComment(fout, "LANGUAGE", qlanname,
12220 : NULL, plang->lanowner,
12221 : plang->dobj.catId, 0, plang->dobj.dumpId);
12222 :
12223 142 : if (plang->dobj.dump & DUMP_COMPONENT_SECLABEL)
12224 0 : dumpSecLabel(fout, "LANGUAGE", qlanname,
12225 : NULL, plang->lanowner,
12226 : plang->dobj.catId, 0, plang->dobj.dumpId);
12227 :
12228 142 : if (plang->lanpltrusted && plang->dobj.dump & DUMP_COMPONENT_ACL)
12229 78 : dumpACL(fout, plang->dobj.dumpId, InvalidDumpId, "LANGUAGE",
12230 : qlanname, NULL, NULL,
12231 : NULL, plang->lanowner, &plang->dacl);
12232 :
12233 142 : free(qlanname);
12234 :
12235 142 : destroyPQExpBuffer(defqry);
12236 142 : destroyPQExpBuffer(delqry);
12237 : }
12238 :
12239 : /*
12240 : * format_function_arguments: generate function name and argument list
12241 : *
12242 : * This is used when we can rely on pg_get_function_arguments to format
12243 : * the argument list. Note, however, that pg_get_function_arguments
12244 : * does not special-case zero-argument aggregates.
12245 : */
12246 : static char *
12247 8128 : format_function_arguments(const FuncInfo *finfo, const char *funcargs, bool is_agg)
12248 : {
12249 : PQExpBufferData fn;
12250 :
12251 8128 : initPQExpBuffer(&fn);
12252 8128 : appendPQExpBufferStr(&fn, fmtId(finfo->dobj.name));
12253 8128 : if (is_agg && finfo->nargs == 0)
12254 160 : appendPQExpBufferStr(&fn, "(*)");
12255 : else
12256 7968 : appendPQExpBuffer(&fn, "(%s)", funcargs);
12257 8128 : return fn.data;
12258 : }
12259 :
12260 : /*
12261 : * format_function_signature: generate function name and argument list
12262 : *
12263 : * Only a minimal list of input argument types is generated; this is
12264 : * sufficient to reference the function, but not to define it.
12265 : *
12266 : * If honor_quotes is false then the function name is never quoted.
12267 : * This is appropriate for use in TOC tags, but not in SQL commands.
12268 : */
12269 : static char *
12270 4286 : format_function_signature(Archive *fout, const FuncInfo *finfo, bool honor_quotes)
12271 : {
12272 : PQExpBufferData fn;
12273 : int j;
12274 :
12275 4286 : initPQExpBuffer(&fn);
12276 4286 : if (honor_quotes)
12277 794 : appendPQExpBuffer(&fn, "%s(", fmtId(finfo->dobj.name));
12278 : else
12279 3492 : appendPQExpBuffer(&fn, "%s(", finfo->dobj.name);
12280 7894 : for (j = 0; j < finfo->nargs; j++)
12281 : {
12282 3608 : if (j > 0)
12283 844 : appendPQExpBufferStr(&fn, ", ");
12284 :
12285 3608 : appendPQExpBufferStr(&fn,
12286 3608 : getFormattedTypeName(fout, finfo->argtypes[j],
12287 : zeroIsError));
12288 : }
12289 4286 : appendPQExpBufferChar(&fn, ')');
12290 4286 : return fn.data;
12291 : }
12292 :
12293 :
12294 : /*
12295 : * dumpFunc:
12296 : * dump out one function
12297 : */
12298 : static void
12299 3556 : dumpFunc(Archive *fout, const FuncInfo *finfo)
12300 : {
12301 3556 : DumpOptions *dopt = fout->dopt;
12302 : PQExpBuffer query;
12303 : PQExpBuffer q;
12304 : PQExpBuffer delqry;
12305 : PQExpBuffer asPart;
12306 : PGresult *res;
12307 : char *funcsig; /* identity signature */
12308 3556 : char *funcfullsig = NULL; /* full signature */
12309 : char *funcsig_tag;
12310 : char *qual_funcsig;
12311 : char *proretset;
12312 : char *prosrc;
12313 : char *probin;
12314 : char *prosqlbody;
12315 : char *funcargs;
12316 : char *funciargs;
12317 : char *funcresult;
12318 : char *protrftypes;
12319 : char *prokind;
12320 : char *provolatile;
12321 : char *proisstrict;
12322 : char *prosecdef;
12323 : char *proleakproof;
12324 : char *proconfig;
12325 : char *procost;
12326 : char *prorows;
12327 : char *prosupport;
12328 : char *proparallel;
12329 : char *lanname;
12330 3556 : char **configitems = NULL;
12331 3556 : int nconfigitems = 0;
12332 : const char *keyword;
12333 :
12334 : /* Do nothing in data-only dump */
12335 3556 : if (dopt->dataOnly)
12336 64 : return;
12337 :
12338 3492 : query = createPQExpBuffer();
12339 3492 : q = createPQExpBuffer();
12340 3492 : delqry = createPQExpBuffer();
12341 3492 : asPart = createPQExpBuffer();
12342 :
12343 3492 : if (!fout->is_prepared[PREPQUERY_DUMPFUNC])
12344 : {
12345 : /* Set up query for function-specific details */
12346 124 : appendPQExpBufferStr(query,
12347 : "PREPARE dumpFunc(pg_catalog.oid) AS\n");
12348 :
12349 124 : appendPQExpBufferStr(query,
12350 : "SELECT\n"
12351 : "proretset,\n"
12352 : "prosrc,\n"
12353 : "probin,\n"
12354 : "provolatile,\n"
12355 : "proisstrict,\n"
12356 : "prosecdef,\n"
12357 : "lanname,\n"
12358 : "proconfig,\n"
12359 : "procost,\n"
12360 : "prorows,\n"
12361 : "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs,\n"
12362 : "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs,\n"
12363 : "pg_catalog.pg_get_function_result(p.oid) AS funcresult,\n"
12364 : "proleakproof,\n");
12365 :
12366 124 : if (fout->remoteVersion >= 90500)
12367 124 : appendPQExpBufferStr(query,
12368 : "array_to_string(protrftypes, ' ') AS protrftypes,\n");
12369 : else
12370 0 : appendPQExpBufferStr(query,
12371 : "NULL AS protrftypes,\n");
12372 :
12373 124 : if (fout->remoteVersion >= 90600)
12374 124 : appendPQExpBufferStr(query,
12375 : "proparallel,\n");
12376 : else
12377 0 : appendPQExpBufferStr(query,
12378 : "'u' AS proparallel,\n");
12379 :
12380 124 : if (fout->remoteVersion >= 110000)
12381 124 : appendPQExpBufferStr(query,
12382 : "prokind,\n");
12383 : else
12384 0 : appendPQExpBufferStr(query,
12385 : "CASE WHEN proiswindow THEN 'w' ELSE 'f' END AS prokind,\n");
12386 :
12387 124 : if (fout->remoteVersion >= 120000)
12388 124 : appendPQExpBufferStr(query,
12389 : "prosupport,\n");
12390 : else
12391 0 : appendPQExpBufferStr(query,
12392 : "'-' AS prosupport,\n");
12393 :
12394 124 : if (fout->remoteVersion >= 140000)
12395 124 : appendPQExpBufferStr(query,
12396 : "pg_get_function_sqlbody(p.oid) AS prosqlbody\n");
12397 : else
12398 0 : appendPQExpBufferStr(query,
12399 : "NULL AS prosqlbody\n");
12400 :
12401 124 : appendPQExpBufferStr(query,
12402 : "FROM pg_catalog.pg_proc p, pg_catalog.pg_language l\n"
12403 : "WHERE p.oid = $1 "
12404 : "AND l.oid = p.prolang");
12405 :
12406 124 : ExecuteSqlStatement(fout, query->data);
12407 :
12408 124 : fout->is_prepared[PREPQUERY_DUMPFUNC] = true;
12409 : }
12410 :
12411 3492 : printfPQExpBuffer(query,
12412 : "EXECUTE dumpFunc('%u')",
12413 : finfo->dobj.catId.oid);
12414 :
12415 3492 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
12416 :
12417 3492 : proretset = PQgetvalue(res, 0, PQfnumber(res, "proretset"));
12418 3492 : if (PQgetisnull(res, 0, PQfnumber(res, "prosqlbody")))
12419 : {
12420 3394 : prosrc = PQgetvalue(res, 0, PQfnumber(res, "prosrc"));
12421 3394 : probin = PQgetvalue(res, 0, PQfnumber(res, "probin"));
12422 3394 : prosqlbody = NULL;
12423 : }
12424 : else
12425 : {
12426 98 : prosrc = NULL;
12427 98 : probin = NULL;
12428 98 : prosqlbody = PQgetvalue(res, 0, PQfnumber(res, "prosqlbody"));
12429 : }
12430 3492 : funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
12431 3492 : funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
12432 3492 : funcresult = PQgetvalue(res, 0, PQfnumber(res, "funcresult"));
12433 3492 : protrftypes = PQgetvalue(res, 0, PQfnumber(res, "protrftypes"));
12434 3492 : prokind = PQgetvalue(res, 0, PQfnumber(res, "prokind"));
12435 3492 : provolatile = PQgetvalue(res, 0, PQfnumber(res, "provolatile"));
12436 3492 : proisstrict = PQgetvalue(res, 0, PQfnumber(res, "proisstrict"));
12437 3492 : prosecdef = PQgetvalue(res, 0, PQfnumber(res, "prosecdef"));
12438 3492 : proleakproof = PQgetvalue(res, 0, PQfnumber(res, "proleakproof"));
12439 3492 : proconfig = PQgetvalue(res, 0, PQfnumber(res, "proconfig"));
12440 3492 : procost = PQgetvalue(res, 0, PQfnumber(res, "procost"));
12441 3492 : prorows = PQgetvalue(res, 0, PQfnumber(res, "prorows"));
12442 3492 : prosupport = PQgetvalue(res, 0, PQfnumber(res, "prosupport"));
12443 3492 : proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
12444 3492 : lanname = PQgetvalue(res, 0, PQfnumber(res, "lanname"));
12445 :
12446 : /*
12447 : * See backend/commands/functioncmds.c for details of how the 'AS' clause
12448 : * is used.
12449 : */
12450 3492 : if (prosqlbody)
12451 : {
12452 98 : appendPQExpBufferStr(asPart, prosqlbody);
12453 : }
12454 3394 : else if (probin[0] != '\0')
12455 : {
12456 286 : appendPQExpBufferStr(asPart, "AS ");
12457 286 : appendStringLiteralAH(asPart, probin, fout);
12458 286 : if (prosrc[0] != '\0')
12459 : {
12460 286 : appendPQExpBufferStr(asPart, ", ");
12461 :
12462 : /*
12463 : * where we have bin, use dollar quoting if allowed and src
12464 : * contains quote or backslash; else use regular quoting.
12465 : */
12466 286 : if (dopt->disable_dollar_quoting ||
12467 286 : (strchr(prosrc, '\'') == NULL && strchr(prosrc, '\\') == NULL))
12468 286 : appendStringLiteralAH(asPart, prosrc, fout);
12469 : else
12470 0 : appendStringLiteralDQ(asPart, prosrc, NULL);
12471 : }
12472 : }
12473 : else
12474 : {
12475 3108 : appendPQExpBufferStr(asPart, "AS ");
12476 : /* with no bin, dollar quote src unconditionally if allowed */
12477 3108 : if (dopt->disable_dollar_quoting)
12478 0 : appendStringLiteralAH(asPart, prosrc, fout);
12479 : else
12480 3108 : appendStringLiteralDQ(asPart, prosrc, NULL);
12481 : }
12482 :
12483 3492 : if (*proconfig)
12484 : {
12485 30 : if (!parsePGArray(proconfig, &configitems, &nconfigitems))
12486 0 : pg_fatal("could not parse %s array", "proconfig");
12487 : }
12488 : else
12489 : {
12490 3462 : configitems = NULL;
12491 3462 : nconfigitems = 0;
12492 : }
12493 :
12494 3492 : funcfullsig = format_function_arguments(finfo, funcargs, false);
12495 3492 : funcsig = format_function_arguments(finfo, funciargs, false);
12496 :
12497 3492 : funcsig_tag = format_function_signature(fout, finfo, false);
12498 :
12499 3492 : qual_funcsig = psprintf("%s.%s",
12500 3492 : fmtId(finfo->dobj.namespace->dobj.name),
12501 : funcsig);
12502 :
12503 3492 : if (prokind[0] == PROKIND_PROCEDURE)
12504 186 : keyword = "PROCEDURE";
12505 : else
12506 3306 : keyword = "FUNCTION"; /* works for window functions too */
12507 :
12508 3492 : appendPQExpBuffer(delqry, "DROP %s %s;\n",
12509 : keyword, qual_funcsig);
12510 :
12511 6984 : appendPQExpBuffer(q, "CREATE %s %s.%s",
12512 : keyword,
12513 3492 : fmtId(finfo->dobj.namespace->dobj.name),
12514 : funcfullsig ? funcfullsig :
12515 : funcsig);
12516 :
12517 3492 : if (prokind[0] == PROKIND_PROCEDURE)
12518 : /* no result type to output */ ;
12519 3306 : else if (funcresult)
12520 3306 : appendPQExpBuffer(q, " RETURNS %s", funcresult);
12521 : else
12522 0 : appendPQExpBuffer(q, " RETURNS %s%s",
12523 0 : (proretset[0] == 't') ? "SETOF " : "",
12524 : getFormattedTypeName(fout, finfo->prorettype,
12525 : zeroIsError));
12526 :
12527 3492 : appendPQExpBuffer(q, "\n LANGUAGE %s", fmtId(lanname));
12528 :
12529 3492 : if (*protrftypes)
12530 : {
12531 0 : Oid *typeids = palloc(FUNC_MAX_ARGS * sizeof(Oid));
12532 : int i;
12533 :
12534 0 : appendPQExpBufferStr(q, " TRANSFORM ");
12535 0 : parseOidArray(protrftypes, typeids, FUNC_MAX_ARGS);
12536 0 : for (i = 0; typeids[i]; i++)
12537 : {
12538 0 : if (i != 0)
12539 0 : appendPQExpBufferStr(q, ", ");
12540 0 : appendPQExpBuffer(q, "FOR TYPE %s",
12541 0 : getFormattedTypeName(fout, typeids[i], zeroAsNone));
12542 : }
12543 : }
12544 :
12545 3492 : if (prokind[0] == PROKIND_WINDOW)
12546 10 : appendPQExpBufferStr(q, " WINDOW");
12547 :
12548 3492 : if (provolatile[0] != PROVOLATILE_VOLATILE)
12549 : {
12550 696 : if (provolatile[0] == PROVOLATILE_IMMUTABLE)
12551 664 : appendPQExpBufferStr(q, " IMMUTABLE");
12552 32 : else if (provolatile[0] == PROVOLATILE_STABLE)
12553 32 : appendPQExpBufferStr(q, " STABLE");
12554 0 : else if (provolatile[0] != PROVOLATILE_VOLATILE)
12555 0 : pg_fatal("unrecognized provolatile value for function \"%s\"",
12556 : finfo->dobj.name);
12557 : }
12558 :
12559 3492 : if (proisstrict[0] == 't')
12560 702 : appendPQExpBufferStr(q, " STRICT");
12561 :
12562 3492 : if (prosecdef[0] == 't')
12563 0 : appendPQExpBufferStr(q, " SECURITY DEFINER");
12564 :
12565 3492 : if (proleakproof[0] == 't')
12566 20 : appendPQExpBufferStr(q, " LEAKPROOF");
12567 :
12568 : /*
12569 : * COST and ROWS are emitted only if present and not default, so as not to
12570 : * break backwards-compatibility of the dump without need. Keep this code
12571 : * in sync with the defaults in functioncmds.c.
12572 : */
12573 3492 : if (strcmp(procost, "0") != 0)
12574 : {
12575 3492 : if (strcmp(lanname, "internal") == 0 || strcmp(lanname, "c") == 0)
12576 : {
12577 : /* default cost is 1 */
12578 752 : if (strcmp(procost, "1") != 0)
12579 0 : appendPQExpBuffer(q, " COST %s", procost);
12580 : }
12581 : else
12582 : {
12583 : /* default cost is 100 */
12584 2740 : if (strcmp(procost, "100") != 0)
12585 12 : appendPQExpBuffer(q, " COST %s", procost);
12586 : }
12587 : }
12588 3492 : if (proretset[0] == 't' &&
12589 376 : strcmp(prorows, "0") != 0 && strcmp(prorows, "1000") != 0)
12590 0 : appendPQExpBuffer(q, " ROWS %s", prorows);
12591 :
12592 3492 : if (strcmp(prosupport, "-") != 0)
12593 : {
12594 : /* We rely on regprocout to provide quoting and qualification */
12595 86 : appendPQExpBuffer(q, " SUPPORT %s", prosupport);
12596 : }
12597 :
12598 3492 : if (proparallel[0] != PROPARALLEL_UNSAFE)
12599 : {
12600 236 : if (proparallel[0] == PROPARALLEL_SAFE)
12601 226 : appendPQExpBufferStr(q, " PARALLEL SAFE");
12602 10 : else if (proparallel[0] == PROPARALLEL_RESTRICTED)
12603 10 : appendPQExpBufferStr(q, " PARALLEL RESTRICTED");
12604 0 : else if (proparallel[0] != PROPARALLEL_UNSAFE)
12605 0 : pg_fatal("unrecognized proparallel value for function \"%s\"",
12606 : finfo->dobj.name);
12607 : }
12608 :
12609 3562 : for (int i = 0; i < nconfigitems; i++)
12610 : {
12611 : /* we feel free to scribble on configitems[] here */
12612 70 : char *configitem = configitems[i];
12613 : char *pos;
12614 :
12615 70 : pos = strchr(configitem, '=');
12616 70 : if (pos == NULL)
12617 0 : continue;
12618 70 : *pos++ = '\0';
12619 70 : appendPQExpBuffer(q, "\n SET %s TO ", fmtId(configitem));
12620 :
12621 : /*
12622 : * Variables that are marked GUC_LIST_QUOTE were already fully quoted
12623 : * by flatten_set_variable_args() before they were put into the
12624 : * proconfig array. However, because the quoting rules used there
12625 : * aren't exactly like SQL's, we have to break the list value apart
12626 : * and then quote the elements as string literals. (The elements may
12627 : * be double-quoted as-is, but we can't just feed them to the SQL
12628 : * parser; it would do the wrong thing with elements that are
12629 : * zero-length or longer than NAMEDATALEN.)
12630 : *
12631 : * Variables that are not so marked should just be emitted as simple
12632 : * string literals. If the variable is not known to
12633 : * variable_is_guc_list_quote(), we'll do that; this makes it unsafe
12634 : * to use GUC_LIST_QUOTE for extension variables.
12635 : */
12636 70 : if (variable_is_guc_list_quote(configitem))
12637 : {
12638 : char **namelist;
12639 : char **nameptr;
12640 :
12641 : /* Parse string into list of identifiers */
12642 : /* this shouldn't fail really */
12643 20 : if (SplitGUCList(pos, ',', &namelist))
12644 : {
12645 70 : for (nameptr = namelist; *nameptr; nameptr++)
12646 : {
12647 50 : if (nameptr != namelist)
12648 30 : appendPQExpBufferStr(q, ", ");
12649 50 : appendStringLiteralAH(q, *nameptr, fout);
12650 : }
12651 : }
12652 20 : pg_free(namelist);
12653 : }
12654 : else
12655 50 : appendStringLiteralAH(q, pos, fout);
12656 : }
12657 :
12658 3492 : appendPQExpBuffer(q, "\n %s;\n", asPart->data);
12659 :
12660 3492 : append_depends_on_extension(fout, q, &finfo->dobj,
12661 : "pg_catalog.pg_proc", keyword,
12662 : qual_funcsig);
12663 :
12664 3492 : if (dopt->binary_upgrade)
12665 570 : binary_upgrade_extension_member(q, &finfo->dobj,
12666 : keyword, funcsig,
12667 570 : finfo->dobj.namespace->dobj.name);
12668 :
12669 3492 : if (finfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
12670 3296 : ArchiveEntry(fout, finfo->dobj.catId, finfo->dobj.dumpId,
12671 3296 : ARCHIVE_OPTS(.tag = funcsig_tag,
12672 : .namespace = finfo->dobj.namespace->dobj.name,
12673 : .owner = finfo->rolname,
12674 : .description = keyword,
12675 : .section = finfo->postponed_def ?
12676 : SECTION_POST_DATA : SECTION_PRE_DATA,
12677 : .createStmt = q->data,
12678 : .dropStmt = delqry->data));
12679 :
12680 : /* Dump Function Comments and Security Labels */
12681 3492 : if (finfo->dobj.dump & DUMP_COMPONENT_COMMENT)
12682 18 : dumpComment(fout, keyword, funcsig,
12683 18 : finfo->dobj.namespace->dobj.name, finfo->rolname,
12684 : finfo->dobj.catId, 0, finfo->dobj.dumpId);
12685 :
12686 3492 : if (finfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
12687 0 : dumpSecLabel(fout, keyword, funcsig,
12688 0 : finfo->dobj.namespace->dobj.name, finfo->rolname,
12689 : finfo->dobj.catId, 0, finfo->dobj.dumpId);
12690 :
12691 3492 : if (finfo->dobj.dump & DUMP_COMPONENT_ACL)
12692 204 : dumpACL(fout, finfo->dobj.dumpId, InvalidDumpId, keyword,
12693 : funcsig, NULL,
12694 204 : finfo->dobj.namespace->dobj.name,
12695 : NULL, finfo->rolname, &finfo->dacl);
12696 :
12697 3492 : PQclear(res);
12698 :
12699 3492 : destroyPQExpBuffer(query);
12700 3492 : destroyPQExpBuffer(q);
12701 3492 : destroyPQExpBuffer(delqry);
12702 3492 : destroyPQExpBuffer(asPart);
12703 3492 : free(funcsig);
12704 3492 : free(funcfullsig);
12705 3492 : free(funcsig_tag);
12706 3492 : free(qual_funcsig);
12707 3492 : free(configitems);
12708 : }
12709 :
12710 :
12711 : /*
12712 : * Dump a user-defined cast
12713 : */
12714 : static void
12715 130 : dumpCast(Archive *fout, const CastInfo *cast)
12716 : {
12717 130 : DumpOptions *dopt = fout->dopt;
12718 : PQExpBuffer defqry;
12719 : PQExpBuffer delqry;
12720 : PQExpBuffer labelq;
12721 : PQExpBuffer castargs;
12722 130 : FuncInfo *funcInfo = NULL;
12723 : const char *sourceType;
12724 : const char *targetType;
12725 :
12726 : /* Do nothing in data-only dump */
12727 130 : if (dopt->dataOnly)
12728 6 : return;
12729 :
12730 : /* Cannot dump if we don't have the cast function's info */
12731 124 : if (OidIsValid(cast->castfunc))
12732 : {
12733 74 : funcInfo = findFuncByOid(cast->castfunc);
12734 74 : if (funcInfo == NULL)
12735 0 : pg_fatal("could not find function definition for function with OID %u",
12736 : cast->castfunc);
12737 : }
12738 :
12739 124 : defqry = createPQExpBuffer();
12740 124 : delqry = createPQExpBuffer();
12741 124 : labelq = createPQExpBuffer();
12742 124 : castargs = createPQExpBuffer();
12743 :
12744 124 : sourceType = getFormattedTypeName(fout, cast->castsource, zeroAsNone);
12745 124 : targetType = getFormattedTypeName(fout, cast->casttarget, zeroAsNone);
12746 124 : appendPQExpBuffer(delqry, "DROP CAST (%s AS %s);\n",
12747 : sourceType, targetType);
12748 :
12749 124 : appendPQExpBuffer(defqry, "CREATE CAST (%s AS %s) ",
12750 : sourceType, targetType);
12751 :
12752 124 : switch (cast->castmethod)
12753 : {
12754 50 : case COERCION_METHOD_BINARY:
12755 50 : appendPQExpBufferStr(defqry, "WITHOUT FUNCTION");
12756 50 : break;
12757 0 : case COERCION_METHOD_INOUT:
12758 0 : appendPQExpBufferStr(defqry, "WITH INOUT");
12759 0 : break;
12760 74 : case COERCION_METHOD_FUNCTION:
12761 74 : if (funcInfo)
12762 : {
12763 74 : char *fsig = format_function_signature(fout, funcInfo, true);
12764 :
12765 : /*
12766 : * Always qualify the function name (format_function_signature
12767 : * won't qualify it).
12768 : */
12769 74 : appendPQExpBuffer(defqry, "WITH FUNCTION %s.%s",
12770 74 : fmtId(funcInfo->dobj.namespace->dobj.name), fsig);
12771 74 : free(fsig);
12772 : }
12773 : else
12774 0 : pg_log_warning("bogus value in pg_cast.castfunc or pg_cast.castmethod field");
12775 74 : break;
12776 0 : default:
12777 0 : pg_log_warning("bogus value in pg_cast.castmethod field");
12778 : }
12779 :
12780 124 : if (cast->castcontext == 'a')
12781 64 : appendPQExpBufferStr(defqry, " AS ASSIGNMENT");
12782 60 : else if (cast->castcontext == 'i')
12783 20 : appendPQExpBufferStr(defqry, " AS IMPLICIT");
12784 124 : appendPQExpBufferStr(defqry, ";\n");
12785 :
12786 124 : appendPQExpBuffer(labelq, "CAST (%s AS %s)",
12787 : sourceType, targetType);
12788 :
12789 124 : appendPQExpBuffer(castargs, "(%s AS %s)",
12790 : sourceType, targetType);
12791 :
12792 124 : if (dopt->binary_upgrade)
12793 14 : binary_upgrade_extension_member(defqry, &cast->dobj,
12794 14 : "CAST", castargs->data, NULL);
12795 :
12796 124 : if (cast->dobj.dump & DUMP_COMPONENT_DEFINITION)
12797 124 : ArchiveEntry(fout, cast->dobj.catId, cast->dobj.dumpId,
12798 124 : ARCHIVE_OPTS(.tag = labelq->data,
12799 : .description = "CAST",
12800 : .section = SECTION_PRE_DATA,
12801 : .createStmt = defqry->data,
12802 : .dropStmt = delqry->data));
12803 :
12804 : /* Dump Cast Comments */
12805 124 : if (cast->dobj.dump & DUMP_COMPONENT_COMMENT)
12806 0 : dumpComment(fout, "CAST", castargs->data,
12807 : NULL, "",
12808 : cast->dobj.catId, 0, cast->dobj.dumpId);
12809 :
12810 124 : destroyPQExpBuffer(defqry);
12811 124 : destroyPQExpBuffer(delqry);
12812 124 : destroyPQExpBuffer(labelq);
12813 124 : destroyPQExpBuffer(castargs);
12814 : }
12815 :
12816 : /*
12817 : * Dump a transform
12818 : */
12819 : static void
12820 80 : dumpTransform(Archive *fout, const TransformInfo *transform)
12821 : {
12822 80 : DumpOptions *dopt = fout->dopt;
12823 : PQExpBuffer defqry;
12824 : PQExpBuffer delqry;
12825 : PQExpBuffer labelq;
12826 : PQExpBuffer transformargs;
12827 80 : FuncInfo *fromsqlFuncInfo = NULL;
12828 80 : FuncInfo *tosqlFuncInfo = NULL;
12829 : char *lanname;
12830 : const char *transformType;
12831 :
12832 : /* Do nothing in data-only dump */
12833 80 : if (dopt->dataOnly)
12834 6 : return;
12835 :
12836 : /* Cannot dump if we don't have the transform functions' info */
12837 74 : if (OidIsValid(transform->trffromsql))
12838 : {
12839 74 : fromsqlFuncInfo = findFuncByOid(transform->trffromsql);
12840 74 : if (fromsqlFuncInfo == NULL)
12841 0 : pg_fatal("could not find function definition for function with OID %u",
12842 : transform->trffromsql);
12843 : }
12844 74 : if (OidIsValid(transform->trftosql))
12845 : {
12846 74 : tosqlFuncInfo = findFuncByOid(transform->trftosql);
12847 74 : if (tosqlFuncInfo == NULL)
12848 0 : pg_fatal("could not find function definition for function with OID %u",
12849 : transform->trftosql);
12850 : }
12851 :
12852 74 : defqry = createPQExpBuffer();
12853 74 : delqry = createPQExpBuffer();
12854 74 : labelq = createPQExpBuffer();
12855 74 : transformargs = createPQExpBuffer();
12856 :
12857 74 : lanname = get_language_name(fout, transform->trflang);
12858 74 : transformType = getFormattedTypeName(fout, transform->trftype, zeroAsNone);
12859 :
12860 74 : appendPQExpBuffer(delqry, "DROP TRANSFORM FOR %s LANGUAGE %s;\n",
12861 : transformType, lanname);
12862 :
12863 74 : appendPQExpBuffer(defqry, "CREATE TRANSFORM FOR %s LANGUAGE %s (",
12864 : transformType, lanname);
12865 :
12866 74 : if (!transform->trffromsql && !transform->trftosql)
12867 0 : pg_log_warning("bogus transform definition, at least one of trffromsql and trftosql should be nonzero");
12868 :
12869 74 : if (transform->trffromsql)
12870 : {
12871 74 : if (fromsqlFuncInfo)
12872 : {
12873 74 : char *fsig = format_function_signature(fout, fromsqlFuncInfo, true);
12874 :
12875 : /*
12876 : * Always qualify the function name (format_function_signature
12877 : * won't qualify it).
12878 : */
12879 74 : appendPQExpBuffer(defqry, "FROM SQL WITH FUNCTION %s.%s",
12880 74 : fmtId(fromsqlFuncInfo->dobj.namespace->dobj.name), fsig);
12881 74 : free(fsig);
12882 : }
12883 : else
12884 0 : pg_log_warning("bogus value in pg_transform.trffromsql field");
12885 : }
12886 :
12887 74 : if (transform->trftosql)
12888 : {
12889 74 : if (transform->trffromsql)
12890 74 : appendPQExpBufferStr(defqry, ", ");
12891 :
12892 74 : if (tosqlFuncInfo)
12893 : {
12894 74 : char *fsig = format_function_signature(fout, tosqlFuncInfo, true);
12895 :
12896 : /*
12897 : * Always qualify the function name (format_function_signature
12898 : * won't qualify it).
12899 : */
12900 74 : appendPQExpBuffer(defqry, "TO SQL WITH FUNCTION %s.%s",
12901 74 : fmtId(tosqlFuncInfo->dobj.namespace->dobj.name), fsig);
12902 74 : free(fsig);
12903 : }
12904 : else
12905 0 : pg_log_warning("bogus value in pg_transform.trftosql field");
12906 : }
12907 :
12908 74 : appendPQExpBufferStr(defqry, ");\n");
12909 :
12910 74 : appendPQExpBuffer(labelq, "TRANSFORM FOR %s LANGUAGE %s",
12911 : transformType, lanname);
12912 :
12913 74 : appendPQExpBuffer(transformargs, "FOR %s LANGUAGE %s",
12914 : transformType, lanname);
12915 :
12916 74 : if (dopt->binary_upgrade)
12917 4 : binary_upgrade_extension_member(defqry, &transform->dobj,
12918 4 : "TRANSFORM", transformargs->data, NULL);
12919 :
12920 74 : if (transform->dobj.dump & DUMP_COMPONENT_DEFINITION)
12921 74 : ArchiveEntry(fout, transform->dobj.catId, transform->dobj.dumpId,
12922 74 : ARCHIVE_OPTS(.tag = labelq->data,
12923 : .description = "TRANSFORM",
12924 : .section = SECTION_PRE_DATA,
12925 : .createStmt = defqry->data,
12926 : .dropStmt = delqry->data,
12927 : .deps = transform->dobj.dependencies,
12928 : .nDeps = transform->dobj.nDeps));
12929 :
12930 : /* Dump Transform Comments */
12931 74 : if (transform->dobj.dump & DUMP_COMPONENT_COMMENT)
12932 0 : dumpComment(fout, "TRANSFORM", transformargs->data,
12933 : NULL, "",
12934 : transform->dobj.catId, 0, transform->dobj.dumpId);
12935 :
12936 74 : free(lanname);
12937 74 : destroyPQExpBuffer(defqry);
12938 74 : destroyPQExpBuffer(delqry);
12939 74 : destroyPQExpBuffer(labelq);
12940 74 : destroyPQExpBuffer(transformargs);
12941 : }
12942 :
12943 :
12944 : /*
12945 : * dumpOpr
12946 : * write out a single operator definition
12947 : */
12948 : static void
12949 5004 : dumpOpr(Archive *fout, const OprInfo *oprinfo)
12950 : {
12951 5004 : DumpOptions *dopt = fout->dopt;
12952 : PQExpBuffer query;
12953 : PQExpBuffer q;
12954 : PQExpBuffer delq;
12955 : PQExpBuffer oprid;
12956 : PQExpBuffer details;
12957 : PGresult *res;
12958 : int i_oprkind;
12959 : int i_oprcode;
12960 : int i_oprleft;
12961 : int i_oprright;
12962 : int i_oprcom;
12963 : int i_oprnegate;
12964 : int i_oprrest;
12965 : int i_oprjoin;
12966 : int i_oprcanmerge;
12967 : int i_oprcanhash;
12968 : char *oprkind;
12969 : char *oprcode;
12970 : char *oprleft;
12971 : char *oprright;
12972 : char *oprcom;
12973 : char *oprnegate;
12974 : char *oprrest;
12975 : char *oprjoin;
12976 : char *oprcanmerge;
12977 : char *oprcanhash;
12978 : char *oprregproc;
12979 : char *oprref;
12980 :
12981 : /* Do nothing in data-only dump */
12982 5004 : if (dopt->dataOnly)
12983 6 : return;
12984 :
12985 : /*
12986 : * some operators are invalid because they were the result of user
12987 : * defining operators before commutators exist
12988 : */
12989 4998 : if (!OidIsValid(oprinfo->oprcode))
12990 28 : return;
12991 :
12992 4970 : query = createPQExpBuffer();
12993 4970 : q = createPQExpBuffer();
12994 4970 : delq = createPQExpBuffer();
12995 4970 : oprid = createPQExpBuffer();
12996 4970 : details = createPQExpBuffer();
12997 :
12998 4970 : if (!fout->is_prepared[PREPQUERY_DUMPOPR])
12999 : {
13000 : /* Set up query for operator-specific details */
13001 82 : appendPQExpBufferStr(query,
13002 : "PREPARE dumpOpr(pg_catalog.oid) AS\n"
13003 : "SELECT oprkind, "
13004 : "oprcode::pg_catalog.regprocedure, "
13005 : "oprleft::pg_catalog.regtype, "
13006 : "oprright::pg_catalog.regtype, "
13007 : "oprcom, "
13008 : "oprnegate, "
13009 : "oprrest::pg_catalog.regprocedure, "
13010 : "oprjoin::pg_catalog.regprocedure, "
13011 : "oprcanmerge, oprcanhash "
13012 : "FROM pg_catalog.pg_operator "
13013 : "WHERE oid = $1");
13014 :
13015 82 : ExecuteSqlStatement(fout, query->data);
13016 :
13017 82 : fout->is_prepared[PREPQUERY_DUMPOPR] = true;
13018 : }
13019 :
13020 4970 : printfPQExpBuffer(query,
13021 : "EXECUTE dumpOpr('%u')",
13022 : oprinfo->dobj.catId.oid);
13023 :
13024 4970 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
13025 :
13026 4970 : i_oprkind = PQfnumber(res, "oprkind");
13027 4970 : i_oprcode = PQfnumber(res, "oprcode");
13028 4970 : i_oprleft = PQfnumber(res, "oprleft");
13029 4970 : i_oprright = PQfnumber(res, "oprright");
13030 4970 : i_oprcom = PQfnumber(res, "oprcom");
13031 4970 : i_oprnegate = PQfnumber(res, "oprnegate");
13032 4970 : i_oprrest = PQfnumber(res, "oprrest");
13033 4970 : i_oprjoin = PQfnumber(res, "oprjoin");
13034 4970 : i_oprcanmerge = PQfnumber(res, "oprcanmerge");
13035 4970 : i_oprcanhash = PQfnumber(res, "oprcanhash");
13036 :
13037 4970 : oprkind = PQgetvalue(res, 0, i_oprkind);
13038 4970 : oprcode = PQgetvalue(res, 0, i_oprcode);
13039 4970 : oprleft = PQgetvalue(res, 0, i_oprleft);
13040 4970 : oprright = PQgetvalue(res, 0, i_oprright);
13041 4970 : oprcom = PQgetvalue(res, 0, i_oprcom);
13042 4970 : oprnegate = PQgetvalue(res, 0, i_oprnegate);
13043 4970 : oprrest = PQgetvalue(res, 0, i_oprrest);
13044 4970 : oprjoin = PQgetvalue(res, 0, i_oprjoin);
13045 4970 : oprcanmerge = PQgetvalue(res, 0, i_oprcanmerge);
13046 4970 : oprcanhash = PQgetvalue(res, 0, i_oprcanhash);
13047 :
13048 : /* In PG14 upwards postfix operator support does not exist anymore. */
13049 4970 : if (strcmp(oprkind, "r") == 0)
13050 0 : pg_log_warning("postfix operators are not supported anymore (operator \"%s\")",
13051 : oprcode);
13052 :
13053 4970 : oprregproc = convertRegProcReference(oprcode);
13054 4970 : if (oprregproc)
13055 : {
13056 4970 : appendPQExpBuffer(details, " FUNCTION = %s", oprregproc);
13057 4970 : free(oprregproc);
13058 : }
13059 :
13060 4970 : appendPQExpBuffer(oprid, "%s (",
13061 : oprinfo->dobj.name);
13062 :
13063 : /*
13064 : * right unary means there's a left arg and left unary means there's a
13065 : * right arg. (Although the "r" case is dead code for PG14 and later,
13066 : * continue to support it in case we're dumping from an old server.)
13067 : */
13068 4970 : if (strcmp(oprkind, "r") == 0 ||
13069 4970 : strcmp(oprkind, "b") == 0)
13070 : {
13071 4684 : appendPQExpBuffer(details, ",\n LEFTARG = %s", oprleft);
13072 4684 : appendPQExpBufferStr(oprid, oprleft);
13073 : }
13074 : else
13075 286 : appendPQExpBufferStr(oprid, "NONE");
13076 :
13077 4970 : if (strcmp(oprkind, "l") == 0 ||
13078 4684 : strcmp(oprkind, "b") == 0)
13079 : {
13080 4970 : appendPQExpBuffer(details, ",\n RIGHTARG = %s", oprright);
13081 4970 : appendPQExpBuffer(oprid, ", %s)", oprright);
13082 : }
13083 : else
13084 0 : appendPQExpBufferStr(oprid, ", NONE)");
13085 :
13086 4970 : oprref = getFormattedOperatorName(oprcom);
13087 4970 : if (oprref)
13088 : {
13089 3322 : appendPQExpBuffer(details, ",\n COMMUTATOR = %s", oprref);
13090 3322 : free(oprref);
13091 : }
13092 :
13093 4970 : oprref = getFormattedOperatorName(oprnegate);
13094 4970 : if (oprref)
13095 : {
13096 2326 : appendPQExpBuffer(details, ",\n NEGATOR = %s", oprref);
13097 2326 : free(oprref);
13098 : }
13099 :
13100 4970 : if (strcmp(oprcanmerge, "t") == 0)
13101 370 : appendPQExpBufferStr(details, ",\n MERGES");
13102 :
13103 4970 : if (strcmp(oprcanhash, "t") == 0)
13104 276 : appendPQExpBufferStr(details, ",\n HASHES");
13105 :
13106 4970 : oprregproc = convertRegProcReference(oprrest);
13107 4970 : if (oprregproc)
13108 : {
13109 3028 : appendPQExpBuffer(details, ",\n RESTRICT = %s", oprregproc);
13110 3028 : free(oprregproc);
13111 : }
13112 :
13113 4970 : oprregproc = convertRegProcReference(oprjoin);
13114 4970 : if (oprregproc)
13115 : {
13116 3028 : appendPQExpBuffer(details, ",\n JOIN = %s", oprregproc);
13117 3028 : free(oprregproc);
13118 : }
13119 :
13120 4970 : appendPQExpBuffer(delq, "DROP OPERATOR %s.%s;\n",
13121 4970 : fmtId(oprinfo->dobj.namespace->dobj.name),
13122 : oprid->data);
13123 :
13124 4970 : appendPQExpBuffer(q, "CREATE OPERATOR %s.%s (\n%s\n);\n",
13125 4970 : fmtId(oprinfo->dobj.namespace->dobj.name),
13126 : oprinfo->dobj.name, details->data);
13127 :
13128 4970 : if (dopt->binary_upgrade)
13129 24 : binary_upgrade_extension_member(q, &oprinfo->dobj,
13130 24 : "OPERATOR", oprid->data,
13131 24 : oprinfo->dobj.namespace->dobj.name);
13132 :
13133 4970 : if (oprinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13134 4970 : ArchiveEntry(fout, oprinfo->dobj.catId, oprinfo->dobj.dumpId,
13135 4970 : ARCHIVE_OPTS(.tag = oprinfo->dobj.name,
13136 : .namespace = oprinfo->dobj.namespace->dobj.name,
13137 : .owner = oprinfo->rolname,
13138 : .description = "OPERATOR",
13139 : .section = SECTION_PRE_DATA,
13140 : .createStmt = q->data,
13141 : .dropStmt = delq->data));
13142 :
13143 : /* Dump Operator Comments */
13144 4970 : if (oprinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13145 4794 : dumpComment(fout, "OPERATOR", oprid->data,
13146 4794 : oprinfo->dobj.namespace->dobj.name, oprinfo->rolname,
13147 : oprinfo->dobj.catId, 0, oprinfo->dobj.dumpId);
13148 :
13149 4970 : PQclear(res);
13150 :
13151 4970 : destroyPQExpBuffer(query);
13152 4970 : destroyPQExpBuffer(q);
13153 4970 : destroyPQExpBuffer(delq);
13154 4970 : destroyPQExpBuffer(oprid);
13155 4970 : destroyPQExpBuffer(details);
13156 : }
13157 :
13158 : /*
13159 : * Convert a function reference obtained from pg_operator
13160 : *
13161 : * Returns allocated string of what to print, or NULL if function references
13162 : * is InvalidOid. Returned string is expected to be free'd by the caller.
13163 : *
13164 : * The input is a REGPROCEDURE display; we have to strip the argument-types
13165 : * part.
13166 : */
13167 : static char *
13168 14910 : convertRegProcReference(const char *proc)
13169 : {
13170 : char *name;
13171 : char *paren;
13172 : bool inquote;
13173 :
13174 : /* In all cases "-" means a null reference */
13175 14910 : if (strcmp(proc, "-") == 0)
13176 3884 : return NULL;
13177 :
13178 11026 : name = pg_strdup(proc);
13179 : /* find non-double-quoted left paren */
13180 11026 : inquote = false;
13181 132878 : for (paren = name; *paren; paren++)
13182 : {
13183 132878 : if (*paren == '(' && !inquote)
13184 : {
13185 11026 : *paren = '\0';
13186 11026 : break;
13187 : }
13188 121852 : if (*paren == '"')
13189 100 : inquote = !inquote;
13190 : }
13191 11026 : return name;
13192 : }
13193 :
13194 : /*
13195 : * getFormattedOperatorName - retrieve the operator name for the
13196 : * given operator OID (presented in string form).
13197 : *
13198 : * Returns an allocated string, or NULL if the given OID is invalid.
13199 : * Caller is responsible for free'ing result string.
13200 : *
13201 : * What we produce has the format "OPERATOR(schema.oprname)". This is only
13202 : * useful in commands where the operator's argument types can be inferred from
13203 : * context. We always schema-qualify the name, though. The predecessor to
13204 : * this code tried to skip the schema qualification if possible, but that led
13205 : * to wrong results in corner cases, such as if an operator and its negator
13206 : * are in different schemas.
13207 : */
13208 : static char *
13209 10512 : getFormattedOperatorName(const char *oproid)
13210 : {
13211 : OprInfo *oprInfo;
13212 :
13213 : /* In all cases "0" means a null reference */
13214 10512 : if (strcmp(oproid, "0") == 0)
13215 4864 : return NULL;
13216 :
13217 5648 : oprInfo = findOprByOid(atooid(oproid));
13218 5648 : if (oprInfo == NULL)
13219 : {
13220 0 : pg_log_warning("could not find operator with OID %s",
13221 : oproid);
13222 0 : return NULL;
13223 : }
13224 :
13225 5648 : return psprintf("OPERATOR(%s.%s)",
13226 5648 : fmtId(oprInfo->dobj.namespace->dobj.name),
13227 : oprInfo->dobj.name);
13228 : }
13229 :
13230 : /*
13231 : * Convert a function OID obtained from pg_ts_parser or pg_ts_template
13232 : *
13233 : * It is sufficient to use REGPROC rather than REGPROCEDURE, since the
13234 : * argument lists of these functions are predetermined. Note that the
13235 : * caller should ensure we are in the proper schema, because the results
13236 : * are search path dependent!
13237 : */
13238 : static char *
13239 420 : convertTSFunction(Archive *fout, Oid funcOid)
13240 : {
13241 : char *result;
13242 : char query[128];
13243 : PGresult *res;
13244 :
13245 420 : snprintf(query, sizeof(query),
13246 : "SELECT '%u'::pg_catalog.regproc", funcOid);
13247 420 : res = ExecuteSqlQueryForSingleRow(fout, query);
13248 :
13249 420 : result = pg_strdup(PQgetvalue(res, 0, 0));
13250 :
13251 420 : PQclear(res);
13252 :
13253 420 : return result;
13254 : }
13255 :
13256 : /*
13257 : * dumpAccessMethod
13258 : * write out a single access method definition
13259 : */
13260 : static void
13261 152 : dumpAccessMethod(Archive *fout, const AccessMethodInfo *aminfo)
13262 : {
13263 152 : DumpOptions *dopt = fout->dopt;
13264 : PQExpBuffer q;
13265 : PQExpBuffer delq;
13266 : char *qamname;
13267 :
13268 : /* Do nothing in data-only dump */
13269 152 : if (dopt->dataOnly)
13270 12 : return;
13271 :
13272 140 : q = createPQExpBuffer();
13273 140 : delq = createPQExpBuffer();
13274 :
13275 140 : qamname = pg_strdup(fmtId(aminfo->dobj.name));
13276 :
13277 140 : appendPQExpBuffer(q, "CREATE ACCESS METHOD %s ", qamname);
13278 :
13279 140 : switch (aminfo->amtype)
13280 : {
13281 66 : case AMTYPE_INDEX:
13282 66 : appendPQExpBufferStr(q, "TYPE INDEX ");
13283 66 : break;
13284 74 : case AMTYPE_TABLE:
13285 74 : appendPQExpBufferStr(q, "TYPE TABLE ");
13286 74 : break;
13287 0 : default:
13288 0 : pg_log_warning("invalid type \"%c\" of access method \"%s\"",
13289 : aminfo->amtype, qamname);
13290 0 : destroyPQExpBuffer(q);
13291 0 : destroyPQExpBuffer(delq);
13292 0 : free(qamname);
13293 0 : return;
13294 : }
13295 :
13296 140 : appendPQExpBuffer(q, "HANDLER %s;\n", aminfo->amhandler);
13297 :
13298 140 : appendPQExpBuffer(delq, "DROP ACCESS METHOD %s;\n",
13299 : qamname);
13300 :
13301 140 : if (dopt->binary_upgrade)
13302 8 : binary_upgrade_extension_member(q, &aminfo->dobj,
13303 : "ACCESS METHOD", qamname, NULL);
13304 :
13305 140 : if (aminfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13306 140 : ArchiveEntry(fout, aminfo->dobj.catId, aminfo->dobj.dumpId,
13307 140 : ARCHIVE_OPTS(.tag = aminfo->dobj.name,
13308 : .description = "ACCESS METHOD",
13309 : .section = SECTION_PRE_DATA,
13310 : .createStmt = q->data,
13311 : .dropStmt = delq->data));
13312 :
13313 : /* Dump Access Method Comments */
13314 140 : if (aminfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13315 0 : dumpComment(fout, "ACCESS METHOD", qamname,
13316 : NULL, "",
13317 : aminfo->dobj.catId, 0, aminfo->dobj.dumpId);
13318 :
13319 140 : destroyPQExpBuffer(q);
13320 140 : destroyPQExpBuffer(delq);
13321 140 : free(qamname);
13322 : }
13323 :
13324 : /*
13325 : * dumpOpclass
13326 : * write out a single operator class definition
13327 : */
13328 : static void
13329 1308 : dumpOpclass(Archive *fout, const OpclassInfo *opcinfo)
13330 : {
13331 1308 : DumpOptions *dopt = fout->dopt;
13332 : PQExpBuffer query;
13333 : PQExpBuffer q;
13334 : PQExpBuffer delq;
13335 : PQExpBuffer nameusing;
13336 : PGresult *res;
13337 : int ntups;
13338 : int i_opcintype;
13339 : int i_opckeytype;
13340 : int i_opcdefault;
13341 : int i_opcfamily;
13342 : int i_opcfamilyname;
13343 : int i_opcfamilynsp;
13344 : int i_amname;
13345 : int i_amopstrategy;
13346 : int i_amopopr;
13347 : int i_sortfamily;
13348 : int i_sortfamilynsp;
13349 : int i_amprocnum;
13350 : int i_amproc;
13351 : int i_amproclefttype;
13352 : int i_amprocrighttype;
13353 : char *opcintype;
13354 : char *opckeytype;
13355 : char *opcdefault;
13356 : char *opcfamily;
13357 : char *opcfamilyname;
13358 : char *opcfamilynsp;
13359 : char *amname;
13360 : char *amopstrategy;
13361 : char *amopopr;
13362 : char *sortfamily;
13363 : char *sortfamilynsp;
13364 : char *amprocnum;
13365 : char *amproc;
13366 : char *amproclefttype;
13367 : char *amprocrighttype;
13368 : bool needComma;
13369 : int i;
13370 :
13371 : /* Do nothing in data-only dump */
13372 1308 : if (dopt->dataOnly)
13373 18 : return;
13374 :
13375 1290 : query = createPQExpBuffer();
13376 1290 : q = createPQExpBuffer();
13377 1290 : delq = createPQExpBuffer();
13378 1290 : nameusing = createPQExpBuffer();
13379 :
13380 : /* Get additional fields from the pg_opclass row */
13381 1290 : appendPQExpBuffer(query, "SELECT opcintype::pg_catalog.regtype, "
13382 : "opckeytype::pg_catalog.regtype, "
13383 : "opcdefault, opcfamily, "
13384 : "opfname AS opcfamilyname, "
13385 : "nspname AS opcfamilynsp, "
13386 : "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opcmethod) AS amname "
13387 : "FROM pg_catalog.pg_opclass c "
13388 : "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = opcfamily "
13389 : "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13390 : "WHERE c.oid = '%u'::pg_catalog.oid",
13391 : opcinfo->dobj.catId.oid);
13392 :
13393 1290 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
13394 :
13395 1290 : i_opcintype = PQfnumber(res, "opcintype");
13396 1290 : i_opckeytype = PQfnumber(res, "opckeytype");
13397 1290 : i_opcdefault = PQfnumber(res, "opcdefault");
13398 1290 : i_opcfamily = PQfnumber(res, "opcfamily");
13399 1290 : i_opcfamilyname = PQfnumber(res, "opcfamilyname");
13400 1290 : i_opcfamilynsp = PQfnumber(res, "opcfamilynsp");
13401 1290 : i_amname = PQfnumber(res, "amname");
13402 :
13403 : /* opcintype may still be needed after we PQclear res */
13404 1290 : opcintype = pg_strdup(PQgetvalue(res, 0, i_opcintype));
13405 1290 : opckeytype = PQgetvalue(res, 0, i_opckeytype);
13406 1290 : opcdefault = PQgetvalue(res, 0, i_opcdefault);
13407 : /* opcfamily will still be needed after we PQclear res */
13408 1290 : opcfamily = pg_strdup(PQgetvalue(res, 0, i_opcfamily));
13409 1290 : opcfamilyname = PQgetvalue(res, 0, i_opcfamilyname);
13410 1290 : opcfamilynsp = PQgetvalue(res, 0, i_opcfamilynsp);
13411 : /* amname will still be needed after we PQclear res */
13412 1290 : amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13413 :
13414 1290 : appendPQExpBuffer(delq, "DROP OPERATOR CLASS %s",
13415 1290 : fmtQualifiedDumpable(opcinfo));
13416 1290 : appendPQExpBuffer(delq, " USING %s;\n",
13417 : fmtId(amname));
13418 :
13419 : /* Build the fixed portion of the CREATE command */
13420 1290 : appendPQExpBuffer(q, "CREATE OPERATOR CLASS %s\n ",
13421 1290 : fmtQualifiedDumpable(opcinfo));
13422 1290 : if (strcmp(opcdefault, "t") == 0)
13423 714 : appendPQExpBufferStr(q, "DEFAULT ");
13424 1290 : appendPQExpBuffer(q, "FOR TYPE %s USING %s",
13425 : opcintype,
13426 : fmtId(amname));
13427 1290 : if (strlen(opcfamilyname) > 0)
13428 : {
13429 1290 : appendPQExpBufferStr(q, " FAMILY ");
13430 1290 : appendPQExpBuffer(q, "%s.", fmtId(opcfamilynsp));
13431 1290 : appendPQExpBufferStr(q, fmtId(opcfamilyname));
13432 : }
13433 1290 : appendPQExpBufferStr(q, " AS\n ");
13434 :
13435 1290 : needComma = false;
13436 :
13437 1290 : if (strcmp(opckeytype, "-") != 0)
13438 : {
13439 504 : appendPQExpBuffer(q, "STORAGE %s",
13440 : opckeytype);
13441 504 : needComma = true;
13442 : }
13443 :
13444 1290 : PQclear(res);
13445 :
13446 : /*
13447 : * Now fetch and print the OPERATOR entries (pg_amop rows).
13448 : *
13449 : * Print only those opfamily members that are tied to the opclass by
13450 : * pg_depend entries.
13451 : */
13452 1290 : resetPQExpBuffer(query);
13453 1290 : appendPQExpBuffer(query, "SELECT amopstrategy, "
13454 : "amopopr::pg_catalog.regoperator, "
13455 : "opfname AS sortfamily, "
13456 : "nspname AS sortfamilynsp "
13457 : "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13458 : "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13459 : "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13460 : "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13461 : "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13462 : "AND refobjid = '%u'::pg_catalog.oid "
13463 : "AND amopfamily = '%s'::pg_catalog.oid "
13464 : "ORDER BY amopstrategy",
13465 : opcinfo->dobj.catId.oid,
13466 : opcfamily);
13467 :
13468 1290 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13469 :
13470 1290 : ntups = PQntuples(res);
13471 :
13472 1290 : i_amopstrategy = PQfnumber(res, "amopstrategy");
13473 1290 : i_amopopr = PQfnumber(res, "amopopr");
13474 1290 : i_sortfamily = PQfnumber(res, "sortfamily");
13475 1290 : i_sortfamilynsp = PQfnumber(res, "sortfamilynsp");
13476 :
13477 1706 : for (i = 0; i < ntups; i++)
13478 : {
13479 416 : amopstrategy = PQgetvalue(res, i, i_amopstrategy);
13480 416 : amopopr = PQgetvalue(res, i, i_amopopr);
13481 416 : sortfamily = PQgetvalue(res, i, i_sortfamily);
13482 416 : sortfamilynsp = PQgetvalue(res, i, i_sortfamilynsp);
13483 :
13484 416 : if (needComma)
13485 264 : appendPQExpBufferStr(q, " ,\n ");
13486 :
13487 416 : appendPQExpBuffer(q, "OPERATOR %s %s",
13488 : amopstrategy, amopopr);
13489 :
13490 416 : if (strlen(sortfamily) > 0)
13491 : {
13492 0 : appendPQExpBufferStr(q, " FOR ORDER BY ");
13493 0 : appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13494 0 : appendPQExpBufferStr(q, fmtId(sortfamily));
13495 : }
13496 :
13497 416 : needComma = true;
13498 : }
13499 :
13500 1290 : PQclear(res);
13501 :
13502 : /*
13503 : * Now fetch and print the FUNCTION entries (pg_amproc rows).
13504 : *
13505 : * Print only those opfamily members that are tied to the opclass by
13506 : * pg_depend entries.
13507 : *
13508 : * We print the amproclefttype/amprocrighttype even though in most cases
13509 : * the backend could deduce the right values, because of the corner case
13510 : * of a btree sort support function for a cross-type comparison.
13511 : */
13512 1290 : resetPQExpBuffer(query);
13513 :
13514 1290 : appendPQExpBuffer(query, "SELECT amprocnum, "
13515 : "amproc::pg_catalog.regprocedure, "
13516 : "amproclefttype::pg_catalog.regtype, "
13517 : "amprocrighttype::pg_catalog.regtype "
13518 : "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13519 : "WHERE refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass "
13520 : "AND refobjid = '%u'::pg_catalog.oid "
13521 : "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13522 : "AND objid = ap.oid "
13523 : "ORDER BY amprocnum",
13524 : opcinfo->dobj.catId.oid);
13525 :
13526 1290 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13527 :
13528 1290 : ntups = PQntuples(res);
13529 :
13530 1290 : i_amprocnum = PQfnumber(res, "amprocnum");
13531 1290 : i_amproc = PQfnumber(res, "amproc");
13532 1290 : i_amproclefttype = PQfnumber(res, "amproclefttype");
13533 1290 : i_amprocrighttype = PQfnumber(res, "amprocrighttype");
13534 :
13535 1356 : for (i = 0; i < ntups; i++)
13536 : {
13537 66 : amprocnum = PQgetvalue(res, i, i_amprocnum);
13538 66 : amproc = PQgetvalue(res, i, i_amproc);
13539 66 : amproclefttype = PQgetvalue(res, i, i_amproclefttype);
13540 66 : amprocrighttype = PQgetvalue(res, i, i_amprocrighttype);
13541 :
13542 66 : if (needComma)
13543 66 : appendPQExpBufferStr(q, " ,\n ");
13544 :
13545 66 : appendPQExpBuffer(q, "FUNCTION %s", amprocnum);
13546 :
13547 66 : if (*amproclefttype && *amprocrighttype)
13548 66 : appendPQExpBuffer(q, " (%s, %s)", amproclefttype, amprocrighttype);
13549 :
13550 66 : appendPQExpBuffer(q, " %s", amproc);
13551 :
13552 66 : needComma = true;
13553 : }
13554 :
13555 1290 : PQclear(res);
13556 :
13557 : /*
13558 : * If needComma is still false it means we haven't added anything after
13559 : * the AS keyword. To avoid printing broken SQL, append a dummy STORAGE
13560 : * clause with the same datatype. This isn't sanctioned by the
13561 : * documentation, but actually DefineOpClass will treat it as a no-op.
13562 : */
13563 1290 : if (!needComma)
13564 634 : appendPQExpBuffer(q, "STORAGE %s", opcintype);
13565 :
13566 1290 : appendPQExpBufferStr(q, ";\n");
13567 :
13568 1290 : appendPQExpBufferStr(nameusing, fmtId(opcinfo->dobj.name));
13569 1290 : appendPQExpBuffer(nameusing, " USING %s",
13570 : fmtId(amname));
13571 :
13572 1290 : if (dopt->binary_upgrade)
13573 12 : binary_upgrade_extension_member(q, &opcinfo->dobj,
13574 12 : "OPERATOR CLASS", nameusing->data,
13575 12 : opcinfo->dobj.namespace->dobj.name);
13576 :
13577 1290 : if (opcinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13578 1290 : ArchiveEntry(fout, opcinfo->dobj.catId, opcinfo->dobj.dumpId,
13579 1290 : ARCHIVE_OPTS(.tag = opcinfo->dobj.name,
13580 : .namespace = opcinfo->dobj.namespace->dobj.name,
13581 : .owner = opcinfo->rolname,
13582 : .description = "OPERATOR CLASS",
13583 : .section = SECTION_PRE_DATA,
13584 : .createStmt = q->data,
13585 : .dropStmt = delq->data));
13586 :
13587 : /* Dump Operator Class Comments */
13588 1290 : if (opcinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13589 0 : dumpComment(fout, "OPERATOR CLASS", nameusing->data,
13590 0 : opcinfo->dobj.namespace->dobj.name, opcinfo->rolname,
13591 : opcinfo->dobj.catId, 0, opcinfo->dobj.dumpId);
13592 :
13593 1290 : free(opcintype);
13594 1290 : free(opcfamily);
13595 1290 : free(amname);
13596 1290 : destroyPQExpBuffer(query);
13597 1290 : destroyPQExpBuffer(q);
13598 1290 : destroyPQExpBuffer(delq);
13599 1290 : destroyPQExpBuffer(nameusing);
13600 : }
13601 :
13602 : /*
13603 : * dumpOpfamily
13604 : * write out a single operator family definition
13605 : *
13606 : * Note: this also dumps any "loose" operator members that aren't bound to a
13607 : * specific opclass within the opfamily.
13608 : */
13609 : static void
13610 1090 : dumpOpfamily(Archive *fout, const OpfamilyInfo *opfinfo)
13611 : {
13612 1090 : DumpOptions *dopt = fout->dopt;
13613 : PQExpBuffer query;
13614 : PQExpBuffer q;
13615 : PQExpBuffer delq;
13616 : PQExpBuffer nameusing;
13617 : PGresult *res;
13618 : PGresult *res_ops;
13619 : PGresult *res_procs;
13620 : int ntups;
13621 : int i_amname;
13622 : int i_amopstrategy;
13623 : int i_amopopr;
13624 : int i_sortfamily;
13625 : int i_sortfamilynsp;
13626 : int i_amprocnum;
13627 : int i_amproc;
13628 : int i_amproclefttype;
13629 : int i_amprocrighttype;
13630 : char *amname;
13631 : char *amopstrategy;
13632 : char *amopopr;
13633 : char *sortfamily;
13634 : char *sortfamilynsp;
13635 : char *amprocnum;
13636 : char *amproc;
13637 : char *amproclefttype;
13638 : char *amprocrighttype;
13639 : bool needComma;
13640 : int i;
13641 :
13642 : /* Do nothing in data-only dump */
13643 1090 : if (dopt->dataOnly)
13644 12 : return;
13645 :
13646 1078 : query = createPQExpBuffer();
13647 1078 : q = createPQExpBuffer();
13648 1078 : delq = createPQExpBuffer();
13649 1078 : nameusing = createPQExpBuffer();
13650 :
13651 : /*
13652 : * Fetch only those opfamily members that are tied directly to the
13653 : * opfamily by pg_depend entries.
13654 : */
13655 1078 : appendPQExpBuffer(query, "SELECT amopstrategy, "
13656 : "amopopr::pg_catalog.regoperator, "
13657 : "opfname AS sortfamily, "
13658 : "nspname AS sortfamilynsp "
13659 : "FROM pg_catalog.pg_amop ao JOIN pg_catalog.pg_depend ON "
13660 : "(classid = 'pg_catalog.pg_amop'::pg_catalog.regclass AND objid = ao.oid) "
13661 : "LEFT JOIN pg_catalog.pg_opfamily f ON f.oid = amopsortfamily "
13662 : "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = opfnamespace "
13663 : "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13664 : "AND refobjid = '%u'::pg_catalog.oid "
13665 : "AND amopfamily = '%u'::pg_catalog.oid "
13666 : "ORDER BY amopstrategy",
13667 : opfinfo->dobj.catId.oid,
13668 : opfinfo->dobj.catId.oid);
13669 :
13670 1078 : res_ops = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13671 :
13672 1078 : resetPQExpBuffer(query);
13673 :
13674 1078 : appendPQExpBuffer(query, "SELECT amprocnum, "
13675 : "amproc::pg_catalog.regprocedure, "
13676 : "amproclefttype::pg_catalog.regtype, "
13677 : "amprocrighttype::pg_catalog.regtype "
13678 : "FROM pg_catalog.pg_amproc ap, pg_catalog.pg_depend "
13679 : "WHERE refclassid = 'pg_catalog.pg_opfamily'::pg_catalog.regclass "
13680 : "AND refobjid = '%u'::pg_catalog.oid "
13681 : "AND classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass "
13682 : "AND objid = ap.oid "
13683 : "ORDER BY amprocnum",
13684 : opfinfo->dobj.catId.oid);
13685 :
13686 1078 : res_procs = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
13687 :
13688 : /* Get additional fields from the pg_opfamily row */
13689 1078 : resetPQExpBuffer(query);
13690 :
13691 1078 : appendPQExpBuffer(query, "SELECT "
13692 : "(SELECT amname FROM pg_catalog.pg_am WHERE oid = opfmethod) AS amname "
13693 : "FROM pg_catalog.pg_opfamily "
13694 : "WHERE oid = '%u'::pg_catalog.oid",
13695 : opfinfo->dobj.catId.oid);
13696 :
13697 1078 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
13698 :
13699 1078 : i_amname = PQfnumber(res, "amname");
13700 :
13701 : /* amname will still be needed after we PQclear res */
13702 1078 : amname = pg_strdup(PQgetvalue(res, 0, i_amname));
13703 :
13704 1078 : appendPQExpBuffer(delq, "DROP OPERATOR FAMILY %s",
13705 1078 : fmtQualifiedDumpable(opfinfo));
13706 1078 : appendPQExpBuffer(delq, " USING %s;\n",
13707 : fmtId(amname));
13708 :
13709 : /* Build the fixed portion of the CREATE command */
13710 1078 : appendPQExpBuffer(q, "CREATE OPERATOR FAMILY %s",
13711 1078 : fmtQualifiedDumpable(opfinfo));
13712 1078 : appendPQExpBuffer(q, " USING %s;\n",
13713 : fmtId(amname));
13714 :
13715 1078 : PQclear(res);
13716 :
13717 : /* Do we need an ALTER to add loose members? */
13718 1078 : if (PQntuples(res_ops) > 0 || PQntuples(res_procs) > 0)
13719 : {
13720 96 : appendPQExpBuffer(q, "ALTER OPERATOR FAMILY %s",
13721 96 : fmtQualifiedDumpable(opfinfo));
13722 96 : appendPQExpBuffer(q, " USING %s ADD\n ",
13723 : fmtId(amname));
13724 :
13725 96 : needComma = false;
13726 :
13727 : /*
13728 : * Now fetch and print the OPERATOR entries (pg_amop rows).
13729 : */
13730 96 : ntups = PQntuples(res_ops);
13731 :
13732 96 : i_amopstrategy = PQfnumber(res_ops, "amopstrategy");
13733 96 : i_amopopr = PQfnumber(res_ops, "amopopr");
13734 96 : i_sortfamily = PQfnumber(res_ops, "sortfamily");
13735 96 : i_sortfamilynsp = PQfnumber(res_ops, "sortfamilynsp");
13736 :
13737 426 : for (i = 0; i < ntups; i++)
13738 : {
13739 330 : amopstrategy = PQgetvalue(res_ops, i, i_amopstrategy);
13740 330 : amopopr = PQgetvalue(res_ops, i, i_amopopr);
13741 330 : sortfamily = PQgetvalue(res_ops, i, i_sortfamily);
13742 330 : sortfamilynsp = PQgetvalue(res_ops, i, i_sortfamilynsp);
13743 :
13744 330 : if (needComma)
13745 264 : appendPQExpBufferStr(q, " ,\n ");
13746 :
13747 330 : appendPQExpBuffer(q, "OPERATOR %s %s",
13748 : amopstrategy, amopopr);
13749 :
13750 330 : if (strlen(sortfamily) > 0)
13751 : {
13752 0 : appendPQExpBufferStr(q, " FOR ORDER BY ");
13753 0 : appendPQExpBuffer(q, "%s.", fmtId(sortfamilynsp));
13754 0 : appendPQExpBufferStr(q, fmtId(sortfamily));
13755 : }
13756 :
13757 330 : needComma = true;
13758 : }
13759 :
13760 : /*
13761 : * Now fetch and print the FUNCTION entries (pg_amproc rows).
13762 : */
13763 96 : ntups = PQntuples(res_procs);
13764 :
13765 96 : i_amprocnum = PQfnumber(res_procs, "amprocnum");
13766 96 : i_amproc = PQfnumber(res_procs, "amproc");
13767 96 : i_amproclefttype = PQfnumber(res_procs, "amproclefttype");
13768 96 : i_amprocrighttype = PQfnumber(res_procs, "amprocrighttype");
13769 :
13770 456 : for (i = 0; i < ntups; i++)
13771 : {
13772 360 : amprocnum = PQgetvalue(res_procs, i, i_amprocnum);
13773 360 : amproc = PQgetvalue(res_procs, i, i_amproc);
13774 360 : amproclefttype = PQgetvalue(res_procs, i, i_amproclefttype);
13775 360 : amprocrighttype = PQgetvalue(res_procs, i, i_amprocrighttype);
13776 :
13777 360 : if (needComma)
13778 330 : appendPQExpBufferStr(q, " ,\n ");
13779 :
13780 360 : appendPQExpBuffer(q, "FUNCTION %s (%s, %s) %s",
13781 : amprocnum, amproclefttype, amprocrighttype,
13782 : amproc);
13783 :
13784 360 : needComma = true;
13785 : }
13786 :
13787 96 : appendPQExpBufferStr(q, ";\n");
13788 : }
13789 :
13790 1078 : appendPQExpBufferStr(nameusing, fmtId(opfinfo->dobj.name));
13791 1078 : appendPQExpBuffer(nameusing, " USING %s",
13792 : fmtId(amname));
13793 :
13794 1078 : if (dopt->binary_upgrade)
13795 18 : binary_upgrade_extension_member(q, &opfinfo->dobj,
13796 18 : "OPERATOR FAMILY", nameusing->data,
13797 18 : opfinfo->dobj.namespace->dobj.name);
13798 :
13799 1078 : if (opfinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
13800 1078 : ArchiveEntry(fout, opfinfo->dobj.catId, opfinfo->dobj.dumpId,
13801 1078 : ARCHIVE_OPTS(.tag = opfinfo->dobj.name,
13802 : .namespace = opfinfo->dobj.namespace->dobj.name,
13803 : .owner = opfinfo->rolname,
13804 : .description = "OPERATOR FAMILY",
13805 : .section = SECTION_PRE_DATA,
13806 : .createStmt = q->data,
13807 : .dropStmt = delq->data));
13808 :
13809 : /* Dump Operator Family Comments */
13810 1078 : if (opfinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
13811 0 : dumpComment(fout, "OPERATOR FAMILY", nameusing->data,
13812 0 : opfinfo->dobj.namespace->dobj.name, opfinfo->rolname,
13813 : opfinfo->dobj.catId, 0, opfinfo->dobj.dumpId);
13814 :
13815 1078 : free(amname);
13816 1078 : PQclear(res_ops);
13817 1078 : PQclear(res_procs);
13818 1078 : destroyPQExpBuffer(query);
13819 1078 : destroyPQExpBuffer(q);
13820 1078 : destroyPQExpBuffer(delq);
13821 1078 : destroyPQExpBuffer(nameusing);
13822 : }
13823 :
13824 : /*
13825 : * dumpCollation
13826 : * write out a single collation definition
13827 : */
13828 : static void
13829 4912 : dumpCollation(Archive *fout, const CollInfo *collinfo)
13830 : {
13831 4912 : DumpOptions *dopt = fout->dopt;
13832 : PQExpBuffer query;
13833 : PQExpBuffer q;
13834 : PQExpBuffer delq;
13835 : char *qcollname;
13836 : PGresult *res;
13837 : int i_collprovider;
13838 : int i_collisdeterministic;
13839 : int i_collcollate;
13840 : int i_collctype;
13841 : int i_colllocale;
13842 : int i_collicurules;
13843 : const char *collprovider;
13844 : const char *collcollate;
13845 : const char *collctype;
13846 : const char *colllocale;
13847 : const char *collicurules;
13848 :
13849 : /* Do nothing in data-only dump */
13850 4912 : if (dopt->dataOnly)
13851 12 : return;
13852 :
13853 4900 : query = createPQExpBuffer();
13854 4900 : q = createPQExpBuffer();
13855 4900 : delq = createPQExpBuffer();
13856 :
13857 4900 : qcollname = pg_strdup(fmtId(collinfo->dobj.name));
13858 :
13859 : /* Get collation-specific details */
13860 4900 : appendPQExpBufferStr(query, "SELECT ");
13861 :
13862 4900 : if (fout->remoteVersion >= 100000)
13863 4900 : appendPQExpBufferStr(query,
13864 : "collprovider, "
13865 : "collversion, ");
13866 : else
13867 0 : appendPQExpBufferStr(query,
13868 : "'c' AS collprovider, "
13869 : "NULL AS collversion, ");
13870 :
13871 4900 : if (fout->remoteVersion >= 120000)
13872 4900 : appendPQExpBufferStr(query,
13873 : "collisdeterministic, ");
13874 : else
13875 0 : appendPQExpBufferStr(query,
13876 : "true AS collisdeterministic, ");
13877 :
13878 4900 : if (fout->remoteVersion >= 170000)
13879 4900 : appendPQExpBufferStr(query,
13880 : "colllocale, ");
13881 0 : else if (fout->remoteVersion >= 150000)
13882 0 : appendPQExpBufferStr(query,
13883 : "colliculocale AS colllocale, ");
13884 : else
13885 0 : appendPQExpBufferStr(query,
13886 : "NULL AS colllocale, ");
13887 :
13888 4900 : if (fout->remoteVersion >= 160000)
13889 4900 : appendPQExpBufferStr(query,
13890 : "collicurules, ");
13891 : else
13892 0 : appendPQExpBufferStr(query,
13893 : "NULL AS collicurules, ");
13894 :
13895 4900 : appendPQExpBuffer(query,
13896 : "collcollate, "
13897 : "collctype "
13898 : "FROM pg_catalog.pg_collation c "
13899 : "WHERE c.oid = '%u'::pg_catalog.oid",
13900 : collinfo->dobj.catId.oid);
13901 :
13902 4900 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
13903 :
13904 4900 : i_collprovider = PQfnumber(res, "collprovider");
13905 4900 : i_collisdeterministic = PQfnumber(res, "collisdeterministic");
13906 4900 : i_collcollate = PQfnumber(res, "collcollate");
13907 4900 : i_collctype = PQfnumber(res, "collctype");
13908 4900 : i_colllocale = PQfnumber(res, "colllocale");
13909 4900 : i_collicurules = PQfnumber(res, "collicurules");
13910 :
13911 4900 : collprovider = PQgetvalue(res, 0, i_collprovider);
13912 :
13913 4900 : if (!PQgetisnull(res, 0, i_collcollate))
13914 94 : collcollate = PQgetvalue(res, 0, i_collcollate);
13915 : else
13916 4806 : collcollate = NULL;
13917 :
13918 4900 : if (!PQgetisnull(res, 0, i_collctype))
13919 94 : collctype = PQgetvalue(res, 0, i_collctype);
13920 : else
13921 4806 : collctype = NULL;
13922 :
13923 : /*
13924 : * Before version 15, collcollate and collctype were of type NAME and
13925 : * non-nullable. Treat empty strings as NULL for consistency.
13926 : */
13927 4900 : if (fout->remoteVersion < 150000)
13928 : {
13929 0 : if (collcollate[0] == '\0')
13930 0 : collcollate = NULL;
13931 0 : if (collctype[0] == '\0')
13932 0 : collctype = NULL;
13933 : }
13934 :
13935 4900 : if (!PQgetisnull(res, 0, i_colllocale))
13936 4800 : colllocale = PQgetvalue(res, 0, i_colllocale);
13937 : else
13938 100 : colllocale = NULL;
13939 :
13940 4900 : if (!PQgetisnull(res, 0, i_collicurules))
13941 0 : collicurules = PQgetvalue(res, 0, i_collicurules);
13942 : else
13943 4900 : collicurules = NULL;
13944 :
13945 4900 : appendPQExpBuffer(delq, "DROP COLLATION %s;\n",
13946 4900 : fmtQualifiedDumpable(collinfo));
13947 :
13948 4900 : appendPQExpBuffer(q, "CREATE COLLATION %s (",
13949 4900 : fmtQualifiedDumpable(collinfo));
13950 :
13951 4900 : appendPQExpBufferStr(q, "provider = ");
13952 4900 : if (collprovider[0] == 'b')
13953 22 : appendPQExpBufferStr(q, "builtin");
13954 4878 : else if (collprovider[0] == 'c')
13955 94 : appendPQExpBufferStr(q, "libc");
13956 4784 : else if (collprovider[0] == 'i')
13957 4778 : appendPQExpBufferStr(q, "icu");
13958 6 : else if (collprovider[0] == 'd')
13959 : /* to allow dumping pg_catalog; not accepted on input */
13960 6 : appendPQExpBufferStr(q, "default");
13961 : else
13962 0 : pg_fatal("unrecognized collation provider: %s",
13963 : collprovider);
13964 :
13965 4900 : if (strcmp(PQgetvalue(res, 0, i_collisdeterministic), "f") == 0)
13966 0 : appendPQExpBufferStr(q, ", deterministic = false");
13967 :
13968 4900 : if (collprovider[0] == 'd')
13969 : {
13970 6 : if (collcollate || collctype || colllocale || collicurules)
13971 0 : pg_log_warning("invalid collation \"%s\"", qcollname);
13972 :
13973 : /* no locale -- the default collation cannot be reloaded anyway */
13974 : }
13975 4894 : else if (collprovider[0] == 'b')
13976 : {
13977 22 : if (collcollate || collctype || !colllocale || collicurules)
13978 0 : pg_log_warning("invalid collation \"%s\"", qcollname);
13979 :
13980 22 : appendPQExpBufferStr(q, ", locale = ");
13981 22 : appendStringLiteralAH(q, colllocale ? colllocale : "",
13982 : fout);
13983 : }
13984 4872 : else if (collprovider[0] == 'i')
13985 : {
13986 4778 : if (fout->remoteVersion >= 150000)
13987 : {
13988 4778 : if (collcollate || collctype || !colllocale)
13989 0 : pg_log_warning("invalid collation \"%s\"", qcollname);
13990 :
13991 4778 : appendPQExpBufferStr(q, ", locale = ");
13992 4778 : appendStringLiteralAH(q, colllocale ? colllocale : "",
13993 : fout);
13994 : }
13995 : else
13996 : {
13997 0 : if (!collcollate || !collctype || colllocale ||
13998 0 : strcmp(collcollate, collctype) != 0)
13999 0 : pg_log_warning("invalid collation \"%s\"", qcollname);
14000 :
14001 0 : appendPQExpBufferStr(q, ", locale = ");
14002 0 : appendStringLiteralAH(q, collcollate ? collcollate : "", fout);
14003 : }
14004 :
14005 4778 : if (collicurules)
14006 : {
14007 0 : appendPQExpBufferStr(q, ", rules = ");
14008 0 : appendStringLiteralAH(q, collicurules ? collicurules : "", fout);
14009 : }
14010 : }
14011 94 : else if (collprovider[0] == 'c')
14012 : {
14013 94 : if (colllocale || collicurules || !collcollate || !collctype)
14014 0 : pg_log_warning("invalid collation \"%s\"", qcollname);
14015 :
14016 94 : if (collcollate && collctype && strcmp(collcollate, collctype) == 0)
14017 : {
14018 94 : appendPQExpBufferStr(q, ", locale = ");
14019 94 : appendStringLiteralAH(q, collcollate ? collcollate : "", fout);
14020 : }
14021 : else
14022 : {
14023 0 : appendPQExpBufferStr(q, ", lc_collate = ");
14024 0 : appendStringLiteralAH(q, collcollate ? collcollate : "", fout);
14025 0 : appendPQExpBufferStr(q, ", lc_ctype = ");
14026 0 : appendStringLiteralAH(q, collctype ? collctype : "", fout);
14027 : }
14028 : }
14029 : else
14030 0 : pg_fatal("unrecognized collation provider: %s", collprovider);
14031 :
14032 : /*
14033 : * For binary upgrade, carry over the collation version. For normal
14034 : * dump/restore, omit the version, so that it is computed upon restore.
14035 : */
14036 4900 : if (dopt->binary_upgrade)
14037 : {
14038 : int i_collversion;
14039 :
14040 8 : i_collversion = PQfnumber(res, "collversion");
14041 8 : if (!PQgetisnull(res, 0, i_collversion))
14042 : {
14043 6 : appendPQExpBufferStr(q, ", version = ");
14044 6 : appendStringLiteralAH(q,
14045 : PQgetvalue(res, 0, i_collversion),
14046 : fout);
14047 : }
14048 : }
14049 :
14050 4900 : appendPQExpBufferStr(q, ");\n");
14051 :
14052 4900 : if (dopt->binary_upgrade)
14053 8 : binary_upgrade_extension_member(q, &collinfo->dobj,
14054 : "COLLATION", qcollname,
14055 8 : collinfo->dobj.namespace->dobj.name);
14056 :
14057 4900 : if (collinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14058 4900 : ArchiveEntry(fout, collinfo->dobj.catId, collinfo->dobj.dumpId,
14059 4900 : ARCHIVE_OPTS(.tag = collinfo->dobj.name,
14060 : .namespace = collinfo->dobj.namespace->dobj.name,
14061 : .owner = collinfo->rolname,
14062 : .description = "COLLATION",
14063 : .section = SECTION_PRE_DATA,
14064 : .createStmt = q->data,
14065 : .dropStmt = delq->data));
14066 :
14067 : /* Dump Collation Comments */
14068 4900 : if (collinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14069 4732 : dumpComment(fout, "COLLATION", qcollname,
14070 4732 : collinfo->dobj.namespace->dobj.name, collinfo->rolname,
14071 : collinfo->dobj.catId, 0, collinfo->dobj.dumpId);
14072 :
14073 4900 : PQclear(res);
14074 :
14075 4900 : destroyPQExpBuffer(query);
14076 4900 : destroyPQExpBuffer(q);
14077 4900 : destroyPQExpBuffer(delq);
14078 4900 : free(qcollname);
14079 : }
14080 :
14081 : /*
14082 : * dumpConversion
14083 : * write out a single conversion definition
14084 : */
14085 : static void
14086 840 : dumpConversion(Archive *fout, const ConvInfo *convinfo)
14087 : {
14088 840 : DumpOptions *dopt = fout->dopt;
14089 : PQExpBuffer query;
14090 : PQExpBuffer q;
14091 : PQExpBuffer delq;
14092 : char *qconvname;
14093 : PGresult *res;
14094 : int i_conforencoding;
14095 : int i_contoencoding;
14096 : int i_conproc;
14097 : int i_condefault;
14098 : const char *conforencoding;
14099 : const char *contoencoding;
14100 : const char *conproc;
14101 : bool condefault;
14102 :
14103 : /* Do nothing in data-only dump */
14104 840 : if (dopt->dataOnly)
14105 6 : return;
14106 :
14107 834 : query = createPQExpBuffer();
14108 834 : q = createPQExpBuffer();
14109 834 : delq = createPQExpBuffer();
14110 :
14111 834 : qconvname = pg_strdup(fmtId(convinfo->dobj.name));
14112 :
14113 : /* Get conversion-specific details */
14114 834 : appendPQExpBuffer(query, "SELECT "
14115 : "pg_catalog.pg_encoding_to_char(conforencoding) AS conforencoding, "
14116 : "pg_catalog.pg_encoding_to_char(contoencoding) AS contoencoding, "
14117 : "conproc, condefault "
14118 : "FROM pg_catalog.pg_conversion c "
14119 : "WHERE c.oid = '%u'::pg_catalog.oid",
14120 : convinfo->dobj.catId.oid);
14121 :
14122 834 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
14123 :
14124 834 : i_conforencoding = PQfnumber(res, "conforencoding");
14125 834 : i_contoencoding = PQfnumber(res, "contoencoding");
14126 834 : i_conproc = PQfnumber(res, "conproc");
14127 834 : i_condefault = PQfnumber(res, "condefault");
14128 :
14129 834 : conforencoding = PQgetvalue(res, 0, i_conforencoding);
14130 834 : contoencoding = PQgetvalue(res, 0, i_contoencoding);
14131 834 : conproc = PQgetvalue(res, 0, i_conproc);
14132 834 : condefault = (PQgetvalue(res, 0, i_condefault)[0] == 't');
14133 :
14134 834 : appendPQExpBuffer(delq, "DROP CONVERSION %s;\n",
14135 834 : fmtQualifiedDumpable(convinfo));
14136 :
14137 834 : appendPQExpBuffer(q, "CREATE %sCONVERSION %s FOR ",
14138 : (condefault) ? "DEFAULT " : "",
14139 834 : fmtQualifiedDumpable(convinfo));
14140 834 : appendStringLiteralAH(q, conforencoding, fout);
14141 834 : appendPQExpBufferStr(q, " TO ");
14142 834 : appendStringLiteralAH(q, contoencoding, fout);
14143 : /* regproc output is already sufficiently quoted */
14144 834 : appendPQExpBuffer(q, " FROM %s;\n", conproc);
14145 :
14146 834 : if (dopt->binary_upgrade)
14147 2 : binary_upgrade_extension_member(q, &convinfo->dobj,
14148 : "CONVERSION", qconvname,
14149 2 : convinfo->dobj.namespace->dobj.name);
14150 :
14151 834 : if (convinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14152 834 : ArchiveEntry(fout, convinfo->dobj.catId, convinfo->dobj.dumpId,
14153 834 : ARCHIVE_OPTS(.tag = convinfo->dobj.name,
14154 : .namespace = convinfo->dobj.namespace->dobj.name,
14155 : .owner = convinfo->rolname,
14156 : .description = "CONVERSION",
14157 : .section = SECTION_PRE_DATA,
14158 : .createStmt = q->data,
14159 : .dropStmt = delq->data));
14160 :
14161 : /* Dump Conversion Comments */
14162 834 : if (convinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14163 834 : dumpComment(fout, "CONVERSION", qconvname,
14164 834 : convinfo->dobj.namespace->dobj.name, convinfo->rolname,
14165 : convinfo->dobj.catId, 0, convinfo->dobj.dumpId);
14166 :
14167 834 : PQclear(res);
14168 :
14169 834 : destroyPQExpBuffer(query);
14170 834 : destroyPQExpBuffer(q);
14171 834 : destroyPQExpBuffer(delq);
14172 834 : free(qconvname);
14173 : }
14174 :
14175 : /*
14176 : * format_aggregate_signature: generate aggregate name and argument list
14177 : *
14178 : * The argument type names are qualified if needed. The aggregate name
14179 : * is never qualified.
14180 : */
14181 : static char *
14182 572 : format_aggregate_signature(const AggInfo *agginfo, Archive *fout, bool honor_quotes)
14183 : {
14184 : PQExpBufferData buf;
14185 : int j;
14186 :
14187 572 : initPQExpBuffer(&buf);
14188 572 : if (honor_quotes)
14189 0 : appendPQExpBufferStr(&buf, fmtId(agginfo->aggfn.dobj.name));
14190 : else
14191 572 : appendPQExpBufferStr(&buf, agginfo->aggfn.dobj.name);
14192 :
14193 572 : if (agginfo->aggfn.nargs == 0)
14194 80 : appendPQExpBufferStr(&buf, "(*)");
14195 : else
14196 : {
14197 492 : appendPQExpBufferChar(&buf, '(');
14198 1074 : for (j = 0; j < agginfo->aggfn.nargs; j++)
14199 582 : appendPQExpBuffer(&buf, "%s%s",
14200 : (j > 0) ? ", " : "",
14201 : getFormattedTypeName(fout,
14202 582 : agginfo->aggfn.argtypes[j],
14203 : zeroIsError));
14204 492 : appendPQExpBufferChar(&buf, ')');
14205 : }
14206 572 : return buf.data;
14207 : }
14208 :
14209 : /*
14210 : * dumpAgg
14211 : * write out a single aggregate definition
14212 : */
14213 : static void
14214 580 : dumpAgg(Archive *fout, const AggInfo *agginfo)
14215 : {
14216 580 : DumpOptions *dopt = fout->dopt;
14217 : PQExpBuffer query;
14218 : PQExpBuffer q;
14219 : PQExpBuffer delq;
14220 : PQExpBuffer details;
14221 : char *aggsig; /* identity signature */
14222 580 : char *aggfullsig = NULL; /* full signature */
14223 : char *aggsig_tag;
14224 : PGresult *res;
14225 : int i_agginitval;
14226 : int i_aggminitval;
14227 : const char *aggtransfn;
14228 : const char *aggfinalfn;
14229 : const char *aggcombinefn;
14230 : const char *aggserialfn;
14231 : const char *aggdeserialfn;
14232 : const char *aggmtransfn;
14233 : const char *aggminvtransfn;
14234 : const char *aggmfinalfn;
14235 : bool aggfinalextra;
14236 : bool aggmfinalextra;
14237 : char aggfinalmodify;
14238 : char aggmfinalmodify;
14239 : const char *aggsortop;
14240 : char *aggsortconvop;
14241 : char aggkind;
14242 : const char *aggtranstype;
14243 : const char *aggtransspace;
14244 : const char *aggmtranstype;
14245 : const char *aggmtransspace;
14246 : const char *agginitval;
14247 : const char *aggminitval;
14248 : const char *proparallel;
14249 : char defaultfinalmodify;
14250 :
14251 : /* Do nothing in data-only dump */
14252 580 : if (dopt->dataOnly)
14253 8 : return;
14254 :
14255 572 : query = createPQExpBuffer();
14256 572 : q = createPQExpBuffer();
14257 572 : delq = createPQExpBuffer();
14258 572 : details = createPQExpBuffer();
14259 :
14260 572 : if (!fout->is_prepared[PREPQUERY_DUMPAGG])
14261 : {
14262 : /* Set up query for aggregate-specific details */
14263 112 : appendPQExpBufferStr(query,
14264 : "PREPARE dumpAgg(pg_catalog.oid) AS\n");
14265 :
14266 112 : appendPQExpBufferStr(query,
14267 : "SELECT "
14268 : "aggtransfn,\n"
14269 : "aggfinalfn,\n"
14270 : "aggtranstype::pg_catalog.regtype,\n"
14271 : "agginitval,\n"
14272 : "aggsortop,\n"
14273 : "pg_catalog.pg_get_function_arguments(p.oid) AS funcargs,\n"
14274 : "pg_catalog.pg_get_function_identity_arguments(p.oid) AS funciargs,\n");
14275 :
14276 112 : if (fout->remoteVersion >= 90400)
14277 112 : appendPQExpBufferStr(query,
14278 : "aggkind,\n"
14279 : "aggmtransfn,\n"
14280 : "aggminvtransfn,\n"
14281 : "aggmfinalfn,\n"
14282 : "aggmtranstype::pg_catalog.regtype,\n"
14283 : "aggfinalextra,\n"
14284 : "aggmfinalextra,\n"
14285 : "aggtransspace,\n"
14286 : "aggmtransspace,\n"
14287 : "aggminitval,\n");
14288 : else
14289 0 : appendPQExpBufferStr(query,
14290 : "'n' AS aggkind,\n"
14291 : "'-' AS aggmtransfn,\n"
14292 : "'-' AS aggminvtransfn,\n"
14293 : "'-' AS aggmfinalfn,\n"
14294 : "0 AS aggmtranstype,\n"
14295 : "false AS aggfinalextra,\n"
14296 : "false AS aggmfinalextra,\n"
14297 : "0 AS aggtransspace,\n"
14298 : "0 AS aggmtransspace,\n"
14299 : "NULL AS aggminitval,\n");
14300 :
14301 112 : if (fout->remoteVersion >= 90600)
14302 112 : appendPQExpBufferStr(query,
14303 : "aggcombinefn,\n"
14304 : "aggserialfn,\n"
14305 : "aggdeserialfn,\n"
14306 : "proparallel,\n");
14307 : else
14308 0 : appendPQExpBufferStr(query,
14309 : "'-' AS aggcombinefn,\n"
14310 : "'-' AS aggserialfn,\n"
14311 : "'-' AS aggdeserialfn,\n"
14312 : "'u' AS proparallel,\n");
14313 :
14314 112 : if (fout->remoteVersion >= 110000)
14315 112 : appendPQExpBufferStr(query,
14316 : "aggfinalmodify,\n"
14317 : "aggmfinalmodify\n");
14318 : else
14319 0 : appendPQExpBufferStr(query,
14320 : "'0' AS aggfinalmodify,\n"
14321 : "'0' AS aggmfinalmodify\n");
14322 :
14323 112 : appendPQExpBufferStr(query,
14324 : "FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
14325 : "WHERE a.aggfnoid = p.oid "
14326 : "AND p.oid = $1");
14327 :
14328 112 : ExecuteSqlStatement(fout, query->data);
14329 :
14330 112 : fout->is_prepared[PREPQUERY_DUMPAGG] = true;
14331 : }
14332 :
14333 572 : printfPQExpBuffer(query,
14334 : "EXECUTE dumpAgg('%u')",
14335 : agginfo->aggfn.dobj.catId.oid);
14336 :
14337 572 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
14338 :
14339 572 : i_agginitval = PQfnumber(res, "agginitval");
14340 572 : i_aggminitval = PQfnumber(res, "aggminitval");
14341 :
14342 572 : aggtransfn = PQgetvalue(res, 0, PQfnumber(res, "aggtransfn"));
14343 572 : aggfinalfn = PQgetvalue(res, 0, PQfnumber(res, "aggfinalfn"));
14344 572 : aggcombinefn = PQgetvalue(res, 0, PQfnumber(res, "aggcombinefn"));
14345 572 : aggserialfn = PQgetvalue(res, 0, PQfnumber(res, "aggserialfn"));
14346 572 : aggdeserialfn = PQgetvalue(res, 0, PQfnumber(res, "aggdeserialfn"));
14347 572 : aggmtransfn = PQgetvalue(res, 0, PQfnumber(res, "aggmtransfn"));
14348 572 : aggminvtransfn = PQgetvalue(res, 0, PQfnumber(res, "aggminvtransfn"));
14349 572 : aggmfinalfn = PQgetvalue(res, 0, PQfnumber(res, "aggmfinalfn"));
14350 572 : aggfinalextra = (PQgetvalue(res, 0, PQfnumber(res, "aggfinalextra"))[0] == 't');
14351 572 : aggmfinalextra = (PQgetvalue(res, 0, PQfnumber(res, "aggmfinalextra"))[0] == 't');
14352 572 : aggfinalmodify = PQgetvalue(res, 0, PQfnumber(res, "aggfinalmodify"))[0];
14353 572 : aggmfinalmodify = PQgetvalue(res, 0, PQfnumber(res, "aggmfinalmodify"))[0];
14354 572 : aggsortop = PQgetvalue(res, 0, PQfnumber(res, "aggsortop"));
14355 572 : aggkind = PQgetvalue(res, 0, PQfnumber(res, "aggkind"))[0];
14356 572 : aggtranstype = PQgetvalue(res, 0, PQfnumber(res, "aggtranstype"));
14357 572 : aggtransspace = PQgetvalue(res, 0, PQfnumber(res, "aggtransspace"));
14358 572 : aggmtranstype = PQgetvalue(res, 0, PQfnumber(res, "aggmtranstype"));
14359 572 : aggmtransspace = PQgetvalue(res, 0, PQfnumber(res, "aggmtransspace"));
14360 572 : agginitval = PQgetvalue(res, 0, i_agginitval);
14361 572 : aggminitval = PQgetvalue(res, 0, i_aggminitval);
14362 572 : proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
14363 :
14364 : {
14365 : char *funcargs;
14366 : char *funciargs;
14367 :
14368 572 : funcargs = PQgetvalue(res, 0, PQfnumber(res, "funcargs"));
14369 572 : funciargs = PQgetvalue(res, 0, PQfnumber(res, "funciargs"));
14370 572 : aggfullsig = format_function_arguments(&agginfo->aggfn, funcargs, true);
14371 572 : aggsig = format_function_arguments(&agginfo->aggfn, funciargs, true);
14372 : }
14373 :
14374 572 : aggsig_tag = format_aggregate_signature(agginfo, fout, false);
14375 :
14376 : /* identify default modify flag for aggkind (must match DefineAggregate) */
14377 572 : defaultfinalmodify = (aggkind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
14378 : /* replace omitted flags for old versions */
14379 572 : if (aggfinalmodify == '0')
14380 0 : aggfinalmodify = defaultfinalmodify;
14381 572 : if (aggmfinalmodify == '0')
14382 0 : aggmfinalmodify = defaultfinalmodify;
14383 :
14384 : /* regproc and regtype output is already sufficiently quoted */
14385 572 : appendPQExpBuffer(details, " SFUNC = %s,\n STYPE = %s",
14386 : aggtransfn, aggtranstype);
14387 :
14388 572 : if (strcmp(aggtransspace, "0") != 0)
14389 : {
14390 10 : appendPQExpBuffer(details, ",\n SSPACE = %s",
14391 : aggtransspace);
14392 : }
14393 :
14394 572 : if (!PQgetisnull(res, 0, i_agginitval))
14395 : {
14396 416 : appendPQExpBufferStr(details, ",\n INITCOND = ");
14397 416 : appendStringLiteralAH(details, agginitval, fout);
14398 : }
14399 :
14400 572 : if (strcmp(aggfinalfn, "-") != 0)
14401 : {
14402 266 : appendPQExpBuffer(details, ",\n FINALFUNC = %s",
14403 : aggfinalfn);
14404 266 : if (aggfinalextra)
14405 20 : appendPQExpBufferStr(details, ",\n FINALFUNC_EXTRA");
14406 266 : if (aggfinalmodify != defaultfinalmodify)
14407 : {
14408 66 : switch (aggfinalmodify)
14409 : {
14410 0 : case AGGMODIFY_READ_ONLY:
14411 0 : appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_ONLY");
14412 0 : break;
14413 66 : case AGGMODIFY_SHAREABLE:
14414 66 : appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = SHAREABLE");
14415 66 : break;
14416 0 : case AGGMODIFY_READ_WRITE:
14417 0 : appendPQExpBufferStr(details, ",\n FINALFUNC_MODIFY = READ_WRITE");
14418 0 : break;
14419 0 : default:
14420 0 : pg_fatal("unrecognized aggfinalmodify value for aggregate \"%s\"",
14421 : agginfo->aggfn.dobj.name);
14422 : break;
14423 : }
14424 506 : }
14425 : }
14426 :
14427 572 : if (strcmp(aggcombinefn, "-") != 0)
14428 0 : appendPQExpBuffer(details, ",\n COMBINEFUNC = %s", aggcombinefn);
14429 :
14430 572 : if (strcmp(aggserialfn, "-") != 0)
14431 0 : appendPQExpBuffer(details, ",\n SERIALFUNC = %s", aggserialfn);
14432 :
14433 572 : if (strcmp(aggdeserialfn, "-") != 0)
14434 0 : appendPQExpBuffer(details, ",\n DESERIALFUNC = %s", aggdeserialfn);
14435 :
14436 572 : if (strcmp(aggmtransfn, "-") != 0)
14437 : {
14438 60 : appendPQExpBuffer(details, ",\n MSFUNC = %s,\n MINVFUNC = %s,\n MSTYPE = %s",
14439 : aggmtransfn,
14440 : aggminvtransfn,
14441 : aggmtranstype);
14442 : }
14443 :
14444 572 : if (strcmp(aggmtransspace, "0") != 0)
14445 : {
14446 0 : appendPQExpBuffer(details, ",\n MSSPACE = %s",
14447 : aggmtransspace);
14448 : }
14449 :
14450 572 : if (!PQgetisnull(res, 0, i_aggminitval))
14451 : {
14452 20 : appendPQExpBufferStr(details, ",\n MINITCOND = ");
14453 20 : appendStringLiteralAH(details, aggminitval, fout);
14454 : }
14455 :
14456 572 : if (strcmp(aggmfinalfn, "-") != 0)
14457 : {
14458 0 : appendPQExpBuffer(details, ",\n MFINALFUNC = %s",
14459 : aggmfinalfn);
14460 0 : if (aggmfinalextra)
14461 0 : appendPQExpBufferStr(details, ",\n MFINALFUNC_EXTRA");
14462 0 : if (aggmfinalmodify != defaultfinalmodify)
14463 : {
14464 0 : switch (aggmfinalmodify)
14465 : {
14466 0 : case AGGMODIFY_READ_ONLY:
14467 0 : appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_ONLY");
14468 0 : break;
14469 0 : case AGGMODIFY_SHAREABLE:
14470 0 : appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = SHAREABLE");
14471 0 : break;
14472 0 : case AGGMODIFY_READ_WRITE:
14473 0 : appendPQExpBufferStr(details, ",\n MFINALFUNC_MODIFY = READ_WRITE");
14474 0 : break;
14475 0 : default:
14476 0 : pg_fatal("unrecognized aggmfinalmodify value for aggregate \"%s\"",
14477 : agginfo->aggfn.dobj.name);
14478 : break;
14479 : }
14480 572 : }
14481 : }
14482 :
14483 572 : aggsortconvop = getFormattedOperatorName(aggsortop);
14484 572 : if (aggsortconvop)
14485 : {
14486 0 : appendPQExpBuffer(details, ",\n SORTOP = %s",
14487 : aggsortconvop);
14488 0 : free(aggsortconvop);
14489 : }
14490 :
14491 572 : if (aggkind == AGGKIND_HYPOTHETICAL)
14492 10 : appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
14493 :
14494 572 : if (proparallel[0] != PROPARALLEL_UNSAFE)
14495 : {
14496 10 : if (proparallel[0] == PROPARALLEL_SAFE)
14497 10 : appendPQExpBufferStr(details, ",\n PARALLEL = safe");
14498 0 : else if (proparallel[0] == PROPARALLEL_RESTRICTED)
14499 0 : appendPQExpBufferStr(details, ",\n PARALLEL = restricted");
14500 0 : else if (proparallel[0] != PROPARALLEL_UNSAFE)
14501 0 : pg_fatal("unrecognized proparallel value for function \"%s\"",
14502 : agginfo->aggfn.dobj.name);
14503 : }
14504 :
14505 572 : appendPQExpBuffer(delq, "DROP AGGREGATE %s.%s;\n",
14506 572 : fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14507 : aggsig);
14508 :
14509 1144 : appendPQExpBuffer(q, "CREATE AGGREGATE %s.%s (\n%s\n);\n",
14510 572 : fmtId(agginfo->aggfn.dobj.namespace->dobj.name),
14511 : aggfullsig ? aggfullsig : aggsig, details->data);
14512 :
14513 572 : if (dopt->binary_upgrade)
14514 98 : binary_upgrade_extension_member(q, &agginfo->aggfn.dobj,
14515 : "AGGREGATE", aggsig,
14516 98 : agginfo->aggfn.dobj.namespace->dobj.name);
14517 :
14518 572 : if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_DEFINITION)
14519 538 : ArchiveEntry(fout, agginfo->aggfn.dobj.catId,
14520 : agginfo->aggfn.dobj.dumpId,
14521 538 : ARCHIVE_OPTS(.tag = aggsig_tag,
14522 : .namespace = agginfo->aggfn.dobj.namespace->dobj.name,
14523 : .owner = agginfo->aggfn.rolname,
14524 : .description = "AGGREGATE",
14525 : .section = SECTION_PRE_DATA,
14526 : .createStmt = q->data,
14527 : .dropStmt = delq->data));
14528 :
14529 : /* Dump Aggregate Comments */
14530 572 : if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_COMMENT)
14531 20 : dumpComment(fout, "AGGREGATE", aggsig,
14532 20 : agginfo->aggfn.dobj.namespace->dobj.name,
14533 : agginfo->aggfn.rolname,
14534 : agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14535 :
14536 572 : if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_SECLABEL)
14537 0 : dumpSecLabel(fout, "AGGREGATE", aggsig,
14538 0 : agginfo->aggfn.dobj.namespace->dobj.name,
14539 : agginfo->aggfn.rolname,
14540 : agginfo->aggfn.dobj.catId, 0, agginfo->aggfn.dobj.dumpId);
14541 :
14542 : /*
14543 : * Since there is no GRANT ON AGGREGATE syntax, we have to make the ACL
14544 : * command look like a function's GRANT; in particular this affects the
14545 : * syntax for zero-argument aggregates and ordered-set aggregates.
14546 : */
14547 572 : free(aggsig);
14548 :
14549 572 : aggsig = format_function_signature(fout, &agginfo->aggfn, true);
14550 :
14551 572 : if (agginfo->aggfn.dobj.dump & DUMP_COMPONENT_ACL)
14552 36 : dumpACL(fout, agginfo->aggfn.dobj.dumpId, InvalidDumpId,
14553 : "FUNCTION", aggsig, NULL,
14554 36 : agginfo->aggfn.dobj.namespace->dobj.name,
14555 : NULL, agginfo->aggfn.rolname, &agginfo->aggfn.dacl);
14556 :
14557 572 : free(aggsig);
14558 572 : free(aggfullsig);
14559 572 : free(aggsig_tag);
14560 :
14561 572 : PQclear(res);
14562 :
14563 572 : destroyPQExpBuffer(query);
14564 572 : destroyPQExpBuffer(q);
14565 572 : destroyPQExpBuffer(delq);
14566 572 : destroyPQExpBuffer(details);
14567 : }
14568 :
14569 : /*
14570 : * dumpTSParser
14571 : * write out a single text search parser
14572 : */
14573 : static void
14574 78 : dumpTSParser(Archive *fout, const TSParserInfo *prsinfo)
14575 : {
14576 78 : DumpOptions *dopt = fout->dopt;
14577 : PQExpBuffer q;
14578 : PQExpBuffer delq;
14579 : char *qprsname;
14580 :
14581 : /* Do nothing in data-only dump */
14582 78 : if (dopt->dataOnly)
14583 6 : return;
14584 :
14585 72 : q = createPQExpBuffer();
14586 72 : delq = createPQExpBuffer();
14587 :
14588 72 : qprsname = pg_strdup(fmtId(prsinfo->dobj.name));
14589 :
14590 72 : appendPQExpBuffer(q, "CREATE TEXT SEARCH PARSER %s (\n",
14591 72 : fmtQualifiedDumpable(prsinfo));
14592 :
14593 72 : appendPQExpBuffer(q, " START = %s,\n",
14594 : convertTSFunction(fout, prsinfo->prsstart));
14595 72 : appendPQExpBuffer(q, " GETTOKEN = %s,\n",
14596 : convertTSFunction(fout, prsinfo->prstoken));
14597 72 : appendPQExpBuffer(q, " END = %s,\n",
14598 : convertTSFunction(fout, prsinfo->prsend));
14599 72 : if (prsinfo->prsheadline != InvalidOid)
14600 6 : appendPQExpBuffer(q, " HEADLINE = %s,\n",
14601 : convertTSFunction(fout, prsinfo->prsheadline));
14602 72 : appendPQExpBuffer(q, " LEXTYPES = %s );\n",
14603 : convertTSFunction(fout, prsinfo->prslextype));
14604 :
14605 72 : appendPQExpBuffer(delq, "DROP TEXT SEARCH PARSER %s;\n",
14606 72 : fmtQualifiedDumpable(prsinfo));
14607 :
14608 72 : if (dopt->binary_upgrade)
14609 2 : binary_upgrade_extension_member(q, &prsinfo->dobj,
14610 : "TEXT SEARCH PARSER", qprsname,
14611 2 : prsinfo->dobj.namespace->dobj.name);
14612 :
14613 72 : if (prsinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14614 72 : ArchiveEntry(fout, prsinfo->dobj.catId, prsinfo->dobj.dumpId,
14615 72 : ARCHIVE_OPTS(.tag = prsinfo->dobj.name,
14616 : .namespace = prsinfo->dobj.namespace->dobj.name,
14617 : .description = "TEXT SEARCH PARSER",
14618 : .section = SECTION_PRE_DATA,
14619 : .createStmt = q->data,
14620 : .dropStmt = delq->data));
14621 :
14622 : /* Dump Parser Comments */
14623 72 : if (prsinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14624 72 : dumpComment(fout, "TEXT SEARCH PARSER", qprsname,
14625 72 : prsinfo->dobj.namespace->dobj.name, "",
14626 : prsinfo->dobj.catId, 0, prsinfo->dobj.dumpId);
14627 :
14628 72 : destroyPQExpBuffer(q);
14629 72 : destroyPQExpBuffer(delq);
14630 72 : free(qprsname);
14631 : }
14632 :
14633 : /*
14634 : * dumpTSDictionary
14635 : * write out a single text search dictionary
14636 : */
14637 : static void
14638 336 : dumpTSDictionary(Archive *fout, const TSDictInfo *dictinfo)
14639 : {
14640 336 : DumpOptions *dopt = fout->dopt;
14641 : PQExpBuffer q;
14642 : PQExpBuffer delq;
14643 : PQExpBuffer query;
14644 : char *qdictname;
14645 : PGresult *res;
14646 : char *nspname;
14647 : char *tmplname;
14648 :
14649 : /* Do nothing in data-only dump */
14650 336 : if (dopt->dataOnly)
14651 6 : return;
14652 :
14653 330 : q = createPQExpBuffer();
14654 330 : delq = createPQExpBuffer();
14655 330 : query = createPQExpBuffer();
14656 :
14657 330 : qdictname = pg_strdup(fmtId(dictinfo->dobj.name));
14658 :
14659 : /* Fetch name and namespace of the dictionary's template */
14660 330 : appendPQExpBuffer(query, "SELECT nspname, tmplname "
14661 : "FROM pg_ts_template p, pg_namespace n "
14662 : "WHERE p.oid = '%u' AND n.oid = tmplnamespace",
14663 : dictinfo->dicttemplate);
14664 330 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
14665 330 : nspname = PQgetvalue(res, 0, 0);
14666 330 : tmplname = PQgetvalue(res, 0, 1);
14667 :
14668 330 : appendPQExpBuffer(q, "CREATE TEXT SEARCH DICTIONARY %s (\n",
14669 330 : fmtQualifiedDumpable(dictinfo));
14670 :
14671 330 : appendPQExpBufferStr(q, " TEMPLATE = ");
14672 330 : appendPQExpBuffer(q, "%s.", fmtId(nspname));
14673 330 : appendPQExpBufferStr(q, fmtId(tmplname));
14674 :
14675 330 : PQclear(res);
14676 :
14677 : /* the dictinitoption can be dumped straight into the command */
14678 330 : if (dictinfo->dictinitoption)
14679 258 : appendPQExpBuffer(q, ",\n %s", dictinfo->dictinitoption);
14680 :
14681 330 : appendPQExpBufferStr(q, " );\n");
14682 :
14683 330 : appendPQExpBuffer(delq, "DROP TEXT SEARCH DICTIONARY %s;\n",
14684 330 : fmtQualifiedDumpable(dictinfo));
14685 :
14686 330 : if (dopt->binary_upgrade)
14687 20 : binary_upgrade_extension_member(q, &dictinfo->dobj,
14688 : "TEXT SEARCH DICTIONARY", qdictname,
14689 20 : dictinfo->dobj.namespace->dobj.name);
14690 :
14691 330 : if (dictinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14692 330 : ArchiveEntry(fout, dictinfo->dobj.catId, dictinfo->dobj.dumpId,
14693 330 : ARCHIVE_OPTS(.tag = dictinfo->dobj.name,
14694 : .namespace = dictinfo->dobj.namespace->dobj.name,
14695 : .owner = dictinfo->rolname,
14696 : .description = "TEXT SEARCH DICTIONARY",
14697 : .section = SECTION_PRE_DATA,
14698 : .createStmt = q->data,
14699 : .dropStmt = delq->data));
14700 :
14701 : /* Dump Dictionary Comments */
14702 330 : if (dictinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14703 240 : dumpComment(fout, "TEXT SEARCH DICTIONARY", qdictname,
14704 240 : dictinfo->dobj.namespace->dobj.name, dictinfo->rolname,
14705 : dictinfo->dobj.catId, 0, dictinfo->dobj.dumpId);
14706 :
14707 330 : destroyPQExpBuffer(q);
14708 330 : destroyPQExpBuffer(delq);
14709 330 : destroyPQExpBuffer(query);
14710 330 : free(qdictname);
14711 : }
14712 :
14713 : /*
14714 : * dumpTSTemplate
14715 : * write out a single text search template
14716 : */
14717 : static void
14718 102 : dumpTSTemplate(Archive *fout, const TSTemplateInfo *tmplinfo)
14719 : {
14720 102 : DumpOptions *dopt = fout->dopt;
14721 : PQExpBuffer q;
14722 : PQExpBuffer delq;
14723 : char *qtmplname;
14724 :
14725 : /* Do nothing in data-only dump */
14726 102 : if (dopt->dataOnly)
14727 6 : return;
14728 :
14729 96 : q = createPQExpBuffer();
14730 96 : delq = createPQExpBuffer();
14731 :
14732 96 : qtmplname = pg_strdup(fmtId(tmplinfo->dobj.name));
14733 :
14734 96 : appendPQExpBuffer(q, "CREATE TEXT SEARCH TEMPLATE %s (\n",
14735 96 : fmtQualifiedDumpable(tmplinfo));
14736 :
14737 96 : if (tmplinfo->tmplinit != InvalidOid)
14738 30 : appendPQExpBuffer(q, " INIT = %s,\n",
14739 : convertTSFunction(fout, tmplinfo->tmplinit));
14740 96 : appendPQExpBuffer(q, " LEXIZE = %s );\n",
14741 : convertTSFunction(fout, tmplinfo->tmpllexize));
14742 :
14743 96 : appendPQExpBuffer(delq, "DROP TEXT SEARCH TEMPLATE %s;\n",
14744 96 : fmtQualifiedDumpable(tmplinfo));
14745 :
14746 96 : if (dopt->binary_upgrade)
14747 2 : binary_upgrade_extension_member(q, &tmplinfo->dobj,
14748 : "TEXT SEARCH TEMPLATE", qtmplname,
14749 2 : tmplinfo->dobj.namespace->dobj.name);
14750 :
14751 96 : if (tmplinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14752 96 : ArchiveEntry(fout, tmplinfo->dobj.catId, tmplinfo->dobj.dumpId,
14753 96 : ARCHIVE_OPTS(.tag = tmplinfo->dobj.name,
14754 : .namespace = tmplinfo->dobj.namespace->dobj.name,
14755 : .description = "TEXT SEARCH TEMPLATE",
14756 : .section = SECTION_PRE_DATA,
14757 : .createStmt = q->data,
14758 : .dropStmt = delq->data));
14759 :
14760 : /* Dump Template Comments */
14761 96 : if (tmplinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14762 96 : dumpComment(fout, "TEXT SEARCH TEMPLATE", qtmplname,
14763 96 : tmplinfo->dobj.namespace->dobj.name, "",
14764 : tmplinfo->dobj.catId, 0, tmplinfo->dobj.dumpId);
14765 :
14766 96 : destroyPQExpBuffer(q);
14767 96 : destroyPQExpBuffer(delq);
14768 96 : free(qtmplname);
14769 : }
14770 :
14771 : /*
14772 : * dumpTSConfig
14773 : * write out a single text search configuration
14774 : */
14775 : static void
14776 286 : dumpTSConfig(Archive *fout, const TSConfigInfo *cfginfo)
14777 : {
14778 286 : DumpOptions *dopt = fout->dopt;
14779 : PQExpBuffer q;
14780 : PQExpBuffer delq;
14781 : PQExpBuffer query;
14782 : char *qcfgname;
14783 : PGresult *res;
14784 : char *nspname;
14785 : char *prsname;
14786 : int ntups,
14787 : i;
14788 : int i_tokenname;
14789 : int i_dictname;
14790 :
14791 : /* Do nothing in data-only dump */
14792 286 : if (dopt->dataOnly)
14793 6 : return;
14794 :
14795 280 : q = createPQExpBuffer();
14796 280 : delq = createPQExpBuffer();
14797 280 : query = createPQExpBuffer();
14798 :
14799 280 : qcfgname = pg_strdup(fmtId(cfginfo->dobj.name));
14800 :
14801 : /* Fetch name and namespace of the config's parser */
14802 280 : appendPQExpBuffer(query, "SELECT nspname, prsname "
14803 : "FROM pg_ts_parser p, pg_namespace n "
14804 : "WHERE p.oid = '%u' AND n.oid = prsnamespace",
14805 : cfginfo->cfgparser);
14806 280 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
14807 280 : nspname = PQgetvalue(res, 0, 0);
14808 280 : prsname = PQgetvalue(res, 0, 1);
14809 :
14810 280 : appendPQExpBuffer(q, "CREATE TEXT SEARCH CONFIGURATION %s (\n",
14811 280 : fmtQualifiedDumpable(cfginfo));
14812 :
14813 280 : appendPQExpBuffer(q, " PARSER = %s.", fmtId(nspname));
14814 280 : appendPQExpBuffer(q, "%s );\n", fmtId(prsname));
14815 :
14816 280 : PQclear(res);
14817 :
14818 280 : resetPQExpBuffer(query);
14819 280 : appendPQExpBuffer(query,
14820 : "SELECT\n"
14821 : " ( SELECT alias FROM pg_catalog.ts_token_type('%u'::pg_catalog.oid) AS t\n"
14822 : " WHERE t.tokid = m.maptokentype ) AS tokenname,\n"
14823 : " m.mapdict::pg_catalog.regdictionary AS dictname\n"
14824 : "FROM pg_catalog.pg_ts_config_map AS m\n"
14825 : "WHERE m.mapcfg = '%u'\n"
14826 : "ORDER BY m.mapcfg, m.maptokentype, m.mapseqno",
14827 : cfginfo->cfgparser, cfginfo->dobj.catId.oid);
14828 :
14829 280 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
14830 280 : ntups = PQntuples(res);
14831 :
14832 280 : i_tokenname = PQfnumber(res, "tokenname");
14833 280 : i_dictname = PQfnumber(res, "dictname");
14834 :
14835 5870 : for (i = 0; i < ntups; i++)
14836 : {
14837 5590 : char *tokenname = PQgetvalue(res, i, i_tokenname);
14838 5590 : char *dictname = PQgetvalue(res, i, i_dictname);
14839 :
14840 5590 : if (i == 0 ||
14841 5310 : strcmp(tokenname, PQgetvalue(res, i - 1, i_tokenname)) != 0)
14842 : {
14843 : /* starting a new token type, so start a new command */
14844 5320 : if (i > 0)
14845 5040 : appendPQExpBufferStr(q, ";\n");
14846 5320 : appendPQExpBuffer(q, "\nALTER TEXT SEARCH CONFIGURATION %s\n",
14847 5320 : fmtQualifiedDumpable(cfginfo));
14848 : /* tokenname needs quoting, dictname does NOT */
14849 5320 : appendPQExpBuffer(q, " ADD MAPPING FOR %s WITH %s",
14850 : fmtId(tokenname), dictname);
14851 : }
14852 : else
14853 270 : appendPQExpBuffer(q, ", %s", dictname);
14854 : }
14855 :
14856 280 : if (ntups > 0)
14857 280 : appendPQExpBufferStr(q, ";\n");
14858 :
14859 280 : PQclear(res);
14860 :
14861 280 : appendPQExpBuffer(delq, "DROP TEXT SEARCH CONFIGURATION %s;\n",
14862 280 : fmtQualifiedDumpable(cfginfo));
14863 :
14864 280 : if (dopt->binary_upgrade)
14865 10 : binary_upgrade_extension_member(q, &cfginfo->dobj,
14866 : "TEXT SEARCH CONFIGURATION", qcfgname,
14867 10 : cfginfo->dobj.namespace->dobj.name);
14868 :
14869 280 : if (cfginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14870 280 : ArchiveEntry(fout, cfginfo->dobj.catId, cfginfo->dobj.dumpId,
14871 280 : ARCHIVE_OPTS(.tag = cfginfo->dobj.name,
14872 : .namespace = cfginfo->dobj.namespace->dobj.name,
14873 : .owner = cfginfo->rolname,
14874 : .description = "TEXT SEARCH CONFIGURATION",
14875 : .section = SECTION_PRE_DATA,
14876 : .createStmt = q->data,
14877 : .dropStmt = delq->data));
14878 :
14879 : /* Dump Configuration Comments */
14880 280 : if (cfginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14881 240 : dumpComment(fout, "TEXT SEARCH CONFIGURATION", qcfgname,
14882 240 : cfginfo->dobj.namespace->dobj.name, cfginfo->rolname,
14883 : cfginfo->dobj.catId, 0, cfginfo->dobj.dumpId);
14884 :
14885 280 : destroyPQExpBuffer(q);
14886 280 : destroyPQExpBuffer(delq);
14887 280 : destroyPQExpBuffer(query);
14888 280 : free(qcfgname);
14889 : }
14890 :
14891 : /*
14892 : * dumpForeignDataWrapper
14893 : * write out a single foreign-data wrapper definition
14894 : */
14895 : static void
14896 100 : dumpForeignDataWrapper(Archive *fout, const FdwInfo *fdwinfo)
14897 : {
14898 100 : DumpOptions *dopt = fout->dopt;
14899 : PQExpBuffer q;
14900 : PQExpBuffer delq;
14901 : char *qfdwname;
14902 :
14903 : /* Do nothing in data-only dump */
14904 100 : if (dopt->dataOnly)
14905 8 : return;
14906 :
14907 92 : q = createPQExpBuffer();
14908 92 : delq = createPQExpBuffer();
14909 :
14910 92 : qfdwname = pg_strdup(fmtId(fdwinfo->dobj.name));
14911 :
14912 92 : appendPQExpBuffer(q, "CREATE FOREIGN DATA WRAPPER %s",
14913 : qfdwname);
14914 :
14915 92 : if (strcmp(fdwinfo->fdwhandler, "-") != 0)
14916 0 : appendPQExpBuffer(q, " HANDLER %s", fdwinfo->fdwhandler);
14917 :
14918 92 : if (strcmp(fdwinfo->fdwvalidator, "-") != 0)
14919 0 : appendPQExpBuffer(q, " VALIDATOR %s", fdwinfo->fdwvalidator);
14920 :
14921 92 : if (strlen(fdwinfo->fdwoptions) > 0)
14922 0 : appendPQExpBuffer(q, " OPTIONS (\n %s\n)", fdwinfo->fdwoptions);
14923 :
14924 92 : appendPQExpBufferStr(q, ";\n");
14925 :
14926 92 : appendPQExpBuffer(delq, "DROP FOREIGN DATA WRAPPER %s;\n",
14927 : qfdwname);
14928 :
14929 92 : if (dopt->binary_upgrade)
14930 4 : binary_upgrade_extension_member(q, &fdwinfo->dobj,
14931 : "FOREIGN DATA WRAPPER", qfdwname,
14932 : NULL);
14933 :
14934 92 : if (fdwinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
14935 92 : ArchiveEntry(fout, fdwinfo->dobj.catId, fdwinfo->dobj.dumpId,
14936 92 : ARCHIVE_OPTS(.tag = fdwinfo->dobj.name,
14937 : .owner = fdwinfo->rolname,
14938 : .description = "FOREIGN DATA WRAPPER",
14939 : .section = SECTION_PRE_DATA,
14940 : .createStmt = q->data,
14941 : .dropStmt = delq->data));
14942 :
14943 : /* Dump Foreign Data Wrapper Comments */
14944 92 : if (fdwinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
14945 0 : dumpComment(fout, "FOREIGN DATA WRAPPER", qfdwname,
14946 : NULL, fdwinfo->rolname,
14947 : fdwinfo->dobj.catId, 0, fdwinfo->dobj.dumpId);
14948 :
14949 : /* Handle the ACL */
14950 92 : if (fdwinfo->dobj.dump & DUMP_COMPONENT_ACL)
14951 64 : dumpACL(fout, fdwinfo->dobj.dumpId, InvalidDumpId,
14952 : "FOREIGN DATA WRAPPER", qfdwname, NULL, NULL,
14953 : NULL, fdwinfo->rolname, &fdwinfo->dacl);
14954 :
14955 92 : free(qfdwname);
14956 :
14957 92 : destroyPQExpBuffer(q);
14958 92 : destroyPQExpBuffer(delq);
14959 : }
14960 :
14961 : /*
14962 : * dumpForeignServer
14963 : * write out a foreign server definition
14964 : */
14965 : static void
14966 108 : dumpForeignServer(Archive *fout, const ForeignServerInfo *srvinfo)
14967 : {
14968 108 : DumpOptions *dopt = fout->dopt;
14969 : PQExpBuffer q;
14970 : PQExpBuffer delq;
14971 : PQExpBuffer query;
14972 : PGresult *res;
14973 : char *qsrvname;
14974 : char *fdwname;
14975 :
14976 : /* Do nothing in data-only dump */
14977 108 : if (dopt->dataOnly)
14978 12 : return;
14979 :
14980 96 : q = createPQExpBuffer();
14981 96 : delq = createPQExpBuffer();
14982 96 : query = createPQExpBuffer();
14983 :
14984 96 : qsrvname = pg_strdup(fmtId(srvinfo->dobj.name));
14985 :
14986 : /* look up the foreign-data wrapper */
14987 96 : appendPQExpBuffer(query, "SELECT fdwname "
14988 : "FROM pg_foreign_data_wrapper w "
14989 : "WHERE w.oid = '%u'",
14990 : srvinfo->srvfdw);
14991 96 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
14992 96 : fdwname = PQgetvalue(res, 0, 0);
14993 :
14994 96 : appendPQExpBuffer(q, "CREATE SERVER %s", qsrvname);
14995 96 : if (srvinfo->srvtype && strlen(srvinfo->srvtype) > 0)
14996 : {
14997 0 : appendPQExpBufferStr(q, " TYPE ");
14998 0 : appendStringLiteralAH(q, srvinfo->srvtype, fout);
14999 : }
15000 96 : if (srvinfo->srvversion && strlen(srvinfo->srvversion) > 0)
15001 : {
15002 0 : appendPQExpBufferStr(q, " VERSION ");
15003 0 : appendStringLiteralAH(q, srvinfo->srvversion, fout);
15004 : }
15005 :
15006 96 : appendPQExpBufferStr(q, " FOREIGN DATA WRAPPER ");
15007 96 : appendPQExpBufferStr(q, fmtId(fdwname));
15008 :
15009 96 : if (srvinfo->srvoptions && strlen(srvinfo->srvoptions) > 0)
15010 0 : appendPQExpBuffer(q, " OPTIONS (\n %s\n)", srvinfo->srvoptions);
15011 :
15012 96 : appendPQExpBufferStr(q, ";\n");
15013 :
15014 96 : appendPQExpBuffer(delq, "DROP SERVER %s;\n",
15015 : qsrvname);
15016 :
15017 96 : if (dopt->binary_upgrade)
15018 4 : binary_upgrade_extension_member(q, &srvinfo->dobj,
15019 : "SERVER", qsrvname, NULL);
15020 :
15021 96 : if (srvinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15022 96 : ArchiveEntry(fout, srvinfo->dobj.catId, srvinfo->dobj.dumpId,
15023 96 : ARCHIVE_OPTS(.tag = srvinfo->dobj.name,
15024 : .owner = srvinfo->rolname,
15025 : .description = "SERVER",
15026 : .section = SECTION_PRE_DATA,
15027 : .createStmt = q->data,
15028 : .dropStmt = delq->data));
15029 :
15030 : /* Dump Foreign Server Comments */
15031 96 : if (srvinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
15032 0 : dumpComment(fout, "SERVER", qsrvname,
15033 : NULL, srvinfo->rolname,
15034 : srvinfo->dobj.catId, 0, srvinfo->dobj.dumpId);
15035 :
15036 : /* Handle the ACL */
15037 96 : if (srvinfo->dobj.dump & DUMP_COMPONENT_ACL)
15038 64 : dumpACL(fout, srvinfo->dobj.dumpId, InvalidDumpId,
15039 : "FOREIGN SERVER", qsrvname, NULL, NULL,
15040 : NULL, srvinfo->rolname, &srvinfo->dacl);
15041 :
15042 : /* Dump user mappings */
15043 96 : if (srvinfo->dobj.dump & DUMP_COMPONENT_USERMAP)
15044 96 : dumpUserMappings(fout,
15045 96 : srvinfo->dobj.name, NULL,
15046 : srvinfo->rolname,
15047 : srvinfo->dobj.catId, srvinfo->dobj.dumpId);
15048 :
15049 96 : PQclear(res);
15050 :
15051 96 : free(qsrvname);
15052 :
15053 96 : destroyPQExpBuffer(q);
15054 96 : destroyPQExpBuffer(delq);
15055 96 : destroyPQExpBuffer(query);
15056 : }
15057 :
15058 : /*
15059 : * dumpUserMappings
15060 : *
15061 : * This routine is used to dump any user mappings associated with the
15062 : * server handed to this routine. Should be called after ArchiveEntry()
15063 : * for the server.
15064 : */
15065 : static void
15066 96 : dumpUserMappings(Archive *fout,
15067 : const char *servername, const char *namespace,
15068 : const char *owner,
15069 : CatalogId catalogId, DumpId dumpId)
15070 : {
15071 : PQExpBuffer q;
15072 : PQExpBuffer delq;
15073 : PQExpBuffer query;
15074 : PQExpBuffer tag;
15075 : PGresult *res;
15076 : int ntups;
15077 : int i_usename;
15078 : int i_umoptions;
15079 : int i;
15080 :
15081 96 : q = createPQExpBuffer();
15082 96 : tag = createPQExpBuffer();
15083 96 : delq = createPQExpBuffer();
15084 96 : query = createPQExpBuffer();
15085 :
15086 : /*
15087 : * We read from the publicly accessible view pg_user_mappings, so as not
15088 : * to fail if run by a non-superuser. Note that the view will show
15089 : * umoptions as null if the user hasn't got privileges for the associated
15090 : * server; this means that pg_dump will dump such a mapping, but with no
15091 : * OPTIONS clause. A possible alternative is to skip such mappings
15092 : * altogether, but it's not clear that that's an improvement.
15093 : */
15094 96 : appendPQExpBuffer(query,
15095 : "SELECT usename, "
15096 : "array_to_string(ARRAY("
15097 : "SELECT quote_ident(option_name) || ' ' || "
15098 : "quote_literal(option_value) "
15099 : "FROM pg_options_to_table(umoptions) "
15100 : "ORDER BY option_name"
15101 : "), E',\n ') AS umoptions "
15102 : "FROM pg_user_mappings "
15103 : "WHERE srvid = '%u' "
15104 : "ORDER BY usename",
15105 : catalogId.oid);
15106 :
15107 96 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15108 :
15109 96 : ntups = PQntuples(res);
15110 96 : i_usename = PQfnumber(res, "usename");
15111 96 : i_umoptions = PQfnumber(res, "umoptions");
15112 :
15113 160 : for (i = 0; i < ntups; i++)
15114 : {
15115 : char *usename;
15116 : char *umoptions;
15117 :
15118 64 : usename = PQgetvalue(res, i, i_usename);
15119 64 : umoptions = PQgetvalue(res, i, i_umoptions);
15120 :
15121 64 : resetPQExpBuffer(q);
15122 64 : appendPQExpBuffer(q, "CREATE USER MAPPING FOR %s", fmtId(usename));
15123 64 : appendPQExpBuffer(q, " SERVER %s", fmtId(servername));
15124 :
15125 64 : if (umoptions && strlen(umoptions) > 0)
15126 0 : appendPQExpBuffer(q, " OPTIONS (\n %s\n)", umoptions);
15127 :
15128 64 : appendPQExpBufferStr(q, ";\n");
15129 :
15130 64 : resetPQExpBuffer(delq);
15131 64 : appendPQExpBuffer(delq, "DROP USER MAPPING FOR %s", fmtId(usename));
15132 64 : appendPQExpBuffer(delq, " SERVER %s;\n", fmtId(servername));
15133 :
15134 64 : resetPQExpBuffer(tag);
15135 64 : appendPQExpBuffer(tag, "USER MAPPING %s SERVER %s",
15136 : usename, servername);
15137 :
15138 64 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
15139 64 : ARCHIVE_OPTS(.tag = tag->data,
15140 : .namespace = namespace,
15141 : .owner = owner,
15142 : .description = "USER MAPPING",
15143 : .section = SECTION_PRE_DATA,
15144 : .createStmt = q->data,
15145 : .dropStmt = delq->data));
15146 : }
15147 :
15148 96 : PQclear(res);
15149 :
15150 96 : destroyPQExpBuffer(query);
15151 96 : destroyPQExpBuffer(delq);
15152 96 : destroyPQExpBuffer(tag);
15153 96 : destroyPQExpBuffer(q);
15154 96 : }
15155 :
15156 : /*
15157 : * Write out default privileges information
15158 : */
15159 : static void
15160 284 : dumpDefaultACL(Archive *fout, const DefaultACLInfo *daclinfo)
15161 : {
15162 284 : DumpOptions *dopt = fout->dopt;
15163 : PQExpBuffer q;
15164 : PQExpBuffer tag;
15165 : const char *type;
15166 :
15167 : /* Do nothing in data-only dump, or if we're skipping ACLs */
15168 284 : if (dopt->dataOnly || dopt->aclsSkip)
15169 32 : return;
15170 :
15171 252 : q = createPQExpBuffer();
15172 252 : tag = createPQExpBuffer();
15173 :
15174 252 : switch (daclinfo->defaclobjtype)
15175 : {
15176 126 : case DEFACLOBJ_RELATION:
15177 126 : type = "TABLES";
15178 126 : break;
15179 0 : case DEFACLOBJ_SEQUENCE:
15180 0 : type = "SEQUENCES";
15181 0 : break;
15182 126 : case DEFACLOBJ_FUNCTION:
15183 126 : type = "FUNCTIONS";
15184 126 : break;
15185 0 : case DEFACLOBJ_TYPE:
15186 0 : type = "TYPES";
15187 0 : break;
15188 0 : case DEFACLOBJ_NAMESPACE:
15189 0 : type = "SCHEMAS";
15190 0 : break;
15191 0 : default:
15192 : /* shouldn't get here */
15193 0 : pg_fatal("unrecognized object type in default privileges: %d",
15194 : (int) daclinfo->defaclobjtype);
15195 : type = ""; /* keep compiler quiet */
15196 : }
15197 :
15198 252 : appendPQExpBuffer(tag, "DEFAULT PRIVILEGES FOR %s", type);
15199 :
15200 : /* build the actual command(s) for this tuple */
15201 252 : if (!buildDefaultACLCommands(type,
15202 252 : daclinfo->dobj.namespace != NULL ?
15203 128 : daclinfo->dobj.namespace->dobj.name : NULL,
15204 252 : daclinfo->dacl.acl,
15205 252 : daclinfo->dacl.acldefault,
15206 : daclinfo->defaclrole,
15207 : fout->remoteVersion,
15208 : q))
15209 0 : pg_fatal("could not parse default ACL list (%s)",
15210 : daclinfo->dacl.acl);
15211 :
15212 252 : if (daclinfo->dobj.dump & DUMP_COMPONENT_ACL)
15213 252 : ArchiveEntry(fout, daclinfo->dobj.catId, daclinfo->dobj.dumpId,
15214 252 : ARCHIVE_OPTS(.tag = tag->data,
15215 : .namespace = daclinfo->dobj.namespace ?
15216 : daclinfo->dobj.namespace->dobj.name : NULL,
15217 : .owner = daclinfo->defaclrole,
15218 : .description = "DEFAULT ACL",
15219 : .section = SECTION_POST_DATA,
15220 : .createStmt = q->data));
15221 :
15222 252 : destroyPQExpBuffer(tag);
15223 252 : destroyPQExpBuffer(q);
15224 : }
15225 :
15226 : /*----------
15227 : * Write out grant/revoke information
15228 : *
15229 : * 'objDumpId' is the dump ID of the underlying object.
15230 : * 'altDumpId' can be a second dumpId that the ACL entry must also depend on,
15231 : * or InvalidDumpId if there is no need for a second dependency.
15232 : * 'type' must be one of
15233 : * TABLE, SEQUENCE, FUNCTION, LANGUAGE, SCHEMA, DATABASE, TABLESPACE,
15234 : * FOREIGN DATA WRAPPER, SERVER, or LARGE OBJECT.
15235 : * 'name' is the formatted name of the object. Must be quoted etc. already.
15236 : * 'subname' is the formatted name of the sub-object, if any. Must be quoted.
15237 : * (Currently we assume that subname is only provided for table columns.)
15238 : * 'nspname' is the namespace the object is in (NULL if none).
15239 : * 'tag' is the tag to use for the ACL TOC entry; typically, this is NULL
15240 : * to use the default for the object type.
15241 : * 'owner' is the owner, NULL if there is no owner (for languages).
15242 : * 'dacl' is the DumpableAcl struct for the object.
15243 : *
15244 : * Returns the dump ID assigned to the ACL TocEntry, or InvalidDumpId if
15245 : * no ACL entry was created.
15246 : *----------
15247 : */
15248 : static DumpId
15249 45836 : dumpACL(Archive *fout, DumpId objDumpId, DumpId altDumpId,
15250 : const char *type, const char *name, const char *subname,
15251 : const char *nspname, const char *tag, const char *owner,
15252 : const DumpableAcl *dacl)
15253 : {
15254 45836 : DumpId aclDumpId = InvalidDumpId;
15255 45836 : DumpOptions *dopt = fout->dopt;
15256 45836 : const char *acls = dacl->acl;
15257 45836 : const char *acldefault = dacl->acldefault;
15258 45836 : char privtype = dacl->privtype;
15259 45836 : const char *initprivs = dacl->initprivs;
15260 : const char *baseacls;
15261 : PQExpBuffer sql;
15262 :
15263 : /* Do nothing if ACL dump is not enabled */
15264 45836 : if (dopt->aclsSkip)
15265 636 : return InvalidDumpId;
15266 :
15267 : /* --data-only skips ACLs *except* large object ACLs */
15268 45200 : if (dopt->dataOnly && strcmp(type, "LARGE OBJECT") != 0)
15269 0 : return InvalidDumpId;
15270 :
15271 45200 : sql = createPQExpBuffer();
15272 :
15273 : /*
15274 : * In binary upgrade mode, we don't run an extension's script but instead
15275 : * dump out the objects independently and then recreate them. To preserve
15276 : * any initial privileges which were set on extension objects, we need to
15277 : * compute the set of GRANT and REVOKE commands necessary to get from the
15278 : * default privileges of an object to its initial privileges as recorded
15279 : * in pg_init_privs.
15280 : *
15281 : * At restore time, we apply these commands after having called
15282 : * binary_upgrade_set_record_init_privs(true). That tells the backend to
15283 : * copy the results into pg_init_privs. This is how we preserve the
15284 : * contents of that catalog across binary upgrades.
15285 : */
15286 45200 : if (dopt->binary_upgrade && privtype == 'e' &&
15287 26 : initprivs && *initprivs != '\0')
15288 : {
15289 26 : appendPQExpBufferStr(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(true);\n");
15290 26 : if (!buildACLCommands(name, subname, nspname, type,
15291 : initprivs, acldefault, owner,
15292 : "", fout->remoteVersion, sql))
15293 0 : pg_fatal("could not parse initial ACL list (%s) or default (%s) for object \"%s\" (%s)",
15294 : initprivs, acldefault, name, type);
15295 26 : appendPQExpBufferStr(sql, "SELECT pg_catalog.binary_upgrade_set_record_init_privs(false);\n");
15296 : }
15297 :
15298 : /*
15299 : * Now figure the GRANT and REVOKE commands needed to get to the object's
15300 : * actual current ACL, starting from the initprivs if given, else from the
15301 : * object-type-specific default. Also, while buildACLCommands will assume
15302 : * that a NULL/empty acls string means it needn't do anything, what that
15303 : * actually represents is the object-type-specific default; so we need to
15304 : * substitute the acldefault string to get the right results in that case.
15305 : */
15306 45200 : if (initprivs && *initprivs != '\0')
15307 : {
15308 41710 : baseacls = initprivs;
15309 41710 : if (acls == NULL || *acls == '\0')
15310 34 : acls = acldefault;
15311 : }
15312 : else
15313 3490 : baseacls = acldefault;
15314 :
15315 45200 : if (!buildACLCommands(name, subname, nspname, type,
15316 : acls, baseacls, owner,
15317 : "", fout->remoteVersion, sql))
15318 0 : pg_fatal("could not parse ACL list (%s) or default (%s) for object \"%s\" (%s)",
15319 : acls, baseacls, name, type);
15320 :
15321 45200 : if (sql->len > 0)
15322 : {
15323 3648 : PQExpBuffer tagbuf = createPQExpBuffer();
15324 : DumpId aclDeps[2];
15325 3648 : int nDeps = 0;
15326 :
15327 3648 : if (tag)
15328 0 : appendPQExpBufferStr(tagbuf, tag);
15329 3648 : else if (subname)
15330 2158 : appendPQExpBuffer(tagbuf, "COLUMN %s.%s", name, subname);
15331 : else
15332 1490 : appendPQExpBuffer(tagbuf, "%s %s", type, name);
15333 :
15334 3648 : aclDeps[nDeps++] = objDumpId;
15335 3648 : if (altDumpId != InvalidDumpId)
15336 1988 : aclDeps[nDeps++] = altDumpId;
15337 :
15338 3648 : aclDumpId = createDumpId();
15339 :
15340 3648 : ArchiveEntry(fout, nilCatalogId, aclDumpId,
15341 3648 : ARCHIVE_OPTS(.tag = tagbuf->data,
15342 : .namespace = nspname,
15343 : .owner = owner,
15344 : .description = "ACL",
15345 : .section = SECTION_NONE,
15346 : .createStmt = sql->data,
15347 : .deps = aclDeps,
15348 : .nDeps = nDeps));
15349 :
15350 3648 : destroyPQExpBuffer(tagbuf);
15351 : }
15352 :
15353 45200 : destroyPQExpBuffer(sql);
15354 :
15355 45200 : return aclDumpId;
15356 : }
15357 :
15358 : /*
15359 : * dumpSecLabel
15360 : *
15361 : * This routine is used to dump any security labels associated with the
15362 : * object handed to this routine. The routine takes the object type
15363 : * and object name (ready to print, except for schema decoration), plus
15364 : * the namespace and owner of the object (for labeling the ArchiveEntry),
15365 : * plus catalog ID and subid which are the lookup key for pg_seclabel,
15366 : * plus the dump ID for the object (for setting a dependency).
15367 : * If a matching pg_seclabel entry is found, it is dumped.
15368 : *
15369 : * Note: although this routine takes a dumpId for dependency purposes,
15370 : * that purpose is just to mark the dependency in the emitted dump file
15371 : * for possible future use by pg_restore. We do NOT use it for determining
15372 : * ordering of the label in the dump file, because this routine is called
15373 : * after dependency sorting occurs. This routine should be called just after
15374 : * calling ArchiveEntry() for the specified object.
15375 : */
15376 : static void
15377 0 : dumpSecLabel(Archive *fout, const char *type, const char *name,
15378 : const char *namespace, const char *owner,
15379 : CatalogId catalogId, int subid, DumpId dumpId)
15380 : {
15381 0 : DumpOptions *dopt = fout->dopt;
15382 : SecLabelItem *labels;
15383 : int nlabels;
15384 : int i;
15385 : PQExpBuffer query;
15386 :
15387 : /* do nothing, if --no-security-labels is supplied */
15388 0 : if (dopt->no_security_labels)
15389 0 : return;
15390 :
15391 : /*
15392 : * Security labels are schema not data ... except large object labels are
15393 : * data
15394 : */
15395 0 : if (strcmp(type, "LARGE OBJECT") != 0)
15396 : {
15397 0 : if (dopt->dataOnly)
15398 0 : return;
15399 : }
15400 : else
15401 : {
15402 : /* We do dump large object security labels in binary-upgrade mode */
15403 0 : if (dopt->schemaOnly && !dopt->binary_upgrade)
15404 0 : return;
15405 : }
15406 :
15407 : /* Search for security labels associated with catalogId, using table */
15408 0 : nlabels = findSecLabels(catalogId.tableoid, catalogId.oid, &labels);
15409 :
15410 0 : query = createPQExpBuffer();
15411 :
15412 0 : for (i = 0; i < nlabels; i++)
15413 : {
15414 : /*
15415 : * Ignore label entries for which the subid doesn't match.
15416 : */
15417 0 : if (labels[i].objsubid != subid)
15418 0 : continue;
15419 :
15420 0 : appendPQExpBuffer(query,
15421 : "SECURITY LABEL FOR %s ON %s ",
15422 0 : fmtId(labels[i].provider), type);
15423 0 : if (namespace && *namespace)
15424 0 : appendPQExpBuffer(query, "%s.", fmtId(namespace));
15425 0 : appendPQExpBuffer(query, "%s IS ", name);
15426 0 : appendStringLiteralAH(query, labels[i].label, fout);
15427 0 : appendPQExpBufferStr(query, ";\n");
15428 : }
15429 :
15430 0 : if (query->len > 0)
15431 : {
15432 0 : PQExpBuffer tag = createPQExpBuffer();
15433 :
15434 0 : appendPQExpBuffer(tag, "%s %s", type, name);
15435 0 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
15436 0 : ARCHIVE_OPTS(.tag = tag->data,
15437 : .namespace = namespace,
15438 : .owner = owner,
15439 : .description = "SECURITY LABEL",
15440 : .section = SECTION_NONE,
15441 : .createStmt = query->data,
15442 : .deps = &dumpId,
15443 : .nDeps = 1));
15444 0 : destroyPQExpBuffer(tag);
15445 : }
15446 :
15447 0 : destroyPQExpBuffer(query);
15448 : }
15449 :
15450 : /*
15451 : * dumpTableSecLabel
15452 : *
15453 : * As above, but dump security label for both the specified table (or view)
15454 : * and its columns.
15455 : */
15456 : static void
15457 0 : dumpTableSecLabel(Archive *fout, const TableInfo *tbinfo, const char *reltypename)
15458 : {
15459 0 : DumpOptions *dopt = fout->dopt;
15460 : SecLabelItem *labels;
15461 : int nlabels;
15462 : int i;
15463 : PQExpBuffer query;
15464 : PQExpBuffer target;
15465 :
15466 : /* do nothing, if --no-security-labels is supplied */
15467 0 : if (dopt->no_security_labels)
15468 0 : return;
15469 :
15470 : /* SecLabel are SCHEMA not data */
15471 0 : if (dopt->dataOnly)
15472 0 : return;
15473 :
15474 : /* Search for comments associated with relation, using table */
15475 0 : nlabels = findSecLabels(tbinfo->dobj.catId.tableoid,
15476 : tbinfo->dobj.catId.oid,
15477 : &labels);
15478 :
15479 : /* If security labels exist, build SECURITY LABEL statements */
15480 0 : if (nlabels <= 0)
15481 0 : return;
15482 :
15483 0 : query = createPQExpBuffer();
15484 0 : target = createPQExpBuffer();
15485 :
15486 0 : for (i = 0; i < nlabels; i++)
15487 : {
15488 : const char *colname;
15489 0 : const char *provider = labels[i].provider;
15490 0 : const char *label = labels[i].label;
15491 0 : int objsubid = labels[i].objsubid;
15492 :
15493 0 : resetPQExpBuffer(target);
15494 0 : if (objsubid == 0)
15495 : {
15496 0 : appendPQExpBuffer(target, "%s %s", reltypename,
15497 0 : fmtQualifiedDumpable(tbinfo));
15498 : }
15499 : else
15500 : {
15501 0 : colname = getAttrName(objsubid, tbinfo);
15502 : /* first fmtXXX result must be consumed before calling again */
15503 0 : appendPQExpBuffer(target, "COLUMN %s",
15504 0 : fmtQualifiedDumpable(tbinfo));
15505 0 : appendPQExpBuffer(target, ".%s", fmtId(colname));
15506 : }
15507 0 : appendPQExpBuffer(query, "SECURITY LABEL FOR %s ON %s IS ",
15508 : fmtId(provider), target->data);
15509 0 : appendStringLiteralAH(query, label, fout);
15510 0 : appendPQExpBufferStr(query, ";\n");
15511 : }
15512 0 : if (query->len > 0)
15513 : {
15514 0 : resetPQExpBuffer(target);
15515 0 : appendPQExpBuffer(target, "%s %s", reltypename,
15516 0 : fmtId(tbinfo->dobj.name));
15517 0 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
15518 0 : ARCHIVE_OPTS(.tag = target->data,
15519 : .namespace = tbinfo->dobj.namespace->dobj.name,
15520 : .owner = tbinfo->rolname,
15521 : .description = "SECURITY LABEL",
15522 : .section = SECTION_NONE,
15523 : .createStmt = query->data,
15524 : .deps = &(tbinfo->dobj.dumpId),
15525 : .nDeps = 1));
15526 : }
15527 0 : destroyPQExpBuffer(query);
15528 0 : destroyPQExpBuffer(target);
15529 : }
15530 :
15531 : /*
15532 : * findSecLabels
15533 : *
15534 : * Find the security label(s), if any, associated with the given object.
15535 : * All the objsubid values associated with the given classoid/objoid are
15536 : * found with one search.
15537 : */
15538 : static int
15539 0 : findSecLabels(Oid classoid, Oid objoid, SecLabelItem **items)
15540 : {
15541 0 : SecLabelItem *middle = NULL;
15542 : SecLabelItem *low;
15543 : SecLabelItem *high;
15544 : int nmatch;
15545 :
15546 0 : if (nseclabels <= 0) /* no labels, so no match is possible */
15547 : {
15548 0 : *items = NULL;
15549 0 : return 0;
15550 : }
15551 :
15552 : /*
15553 : * Do binary search to find some item matching the object.
15554 : */
15555 0 : low = &seclabels[0];
15556 0 : high = &seclabels[nseclabels - 1];
15557 0 : while (low <= high)
15558 : {
15559 0 : middle = low + (high - low) / 2;
15560 :
15561 0 : if (classoid < middle->classoid)
15562 0 : high = middle - 1;
15563 0 : else if (classoid > middle->classoid)
15564 0 : low = middle + 1;
15565 0 : else if (objoid < middle->objoid)
15566 0 : high = middle - 1;
15567 0 : else if (objoid > middle->objoid)
15568 0 : low = middle + 1;
15569 : else
15570 0 : break; /* found a match */
15571 : }
15572 :
15573 0 : if (low > high) /* no matches */
15574 : {
15575 0 : *items = NULL;
15576 0 : return 0;
15577 : }
15578 :
15579 : /*
15580 : * Now determine how many items match the object. The search loop
15581 : * invariant still holds: only items between low and high inclusive could
15582 : * match.
15583 : */
15584 0 : nmatch = 1;
15585 0 : while (middle > low)
15586 : {
15587 0 : if (classoid != middle[-1].classoid ||
15588 0 : objoid != middle[-1].objoid)
15589 : break;
15590 0 : middle--;
15591 0 : nmatch++;
15592 : }
15593 :
15594 0 : *items = middle;
15595 :
15596 0 : middle += nmatch;
15597 0 : while (middle <= high)
15598 : {
15599 0 : if (classoid != middle->classoid ||
15600 0 : objoid != middle->objoid)
15601 : break;
15602 0 : middle++;
15603 0 : nmatch++;
15604 : }
15605 :
15606 0 : return nmatch;
15607 : }
15608 :
15609 : /*
15610 : * collectSecLabels
15611 : *
15612 : * Construct a table of all security labels available for database objects;
15613 : * also set the has-seclabel component flag for each relevant object.
15614 : *
15615 : * The table is sorted by classoid/objid/objsubid for speed in lookup.
15616 : */
15617 : static void
15618 308 : collectSecLabels(Archive *fout)
15619 : {
15620 : PGresult *res;
15621 : PQExpBuffer query;
15622 : int i_label;
15623 : int i_provider;
15624 : int i_classoid;
15625 : int i_objoid;
15626 : int i_objsubid;
15627 : int ntups;
15628 : int i;
15629 : DumpableObject *dobj;
15630 :
15631 308 : query = createPQExpBuffer();
15632 :
15633 308 : appendPQExpBufferStr(query,
15634 : "SELECT label, provider, classoid, objoid, objsubid "
15635 : "FROM pg_catalog.pg_seclabel "
15636 : "ORDER BY classoid, objoid, objsubid");
15637 :
15638 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15639 :
15640 : /* Construct lookup table containing OIDs in numeric form */
15641 308 : i_label = PQfnumber(res, "label");
15642 308 : i_provider = PQfnumber(res, "provider");
15643 308 : i_classoid = PQfnumber(res, "classoid");
15644 308 : i_objoid = PQfnumber(res, "objoid");
15645 308 : i_objsubid = PQfnumber(res, "objsubid");
15646 :
15647 308 : ntups = PQntuples(res);
15648 :
15649 308 : seclabels = (SecLabelItem *) pg_malloc(ntups * sizeof(SecLabelItem));
15650 308 : nseclabels = 0;
15651 308 : dobj = NULL;
15652 :
15653 308 : for (i = 0; i < ntups; i++)
15654 : {
15655 : CatalogId objId;
15656 : int subid;
15657 :
15658 0 : objId.tableoid = atooid(PQgetvalue(res, i, i_classoid));
15659 0 : objId.oid = atooid(PQgetvalue(res, i, i_objoid));
15660 0 : subid = atoi(PQgetvalue(res, i, i_objsubid));
15661 :
15662 : /* We needn't remember labels that don't match any dumpable object */
15663 0 : if (dobj == NULL ||
15664 0 : dobj->catId.tableoid != objId.tableoid ||
15665 0 : dobj->catId.oid != objId.oid)
15666 0 : dobj = findObjectByCatalogId(objId);
15667 0 : if (dobj == NULL)
15668 0 : continue;
15669 :
15670 : /*
15671 : * Labels on columns of composite types are linked to the type's
15672 : * pg_class entry, but we need to set the DUMP_COMPONENT_SECLABEL flag
15673 : * in the type's own DumpableObject.
15674 : */
15675 0 : if (subid != 0 && dobj->objType == DO_TABLE &&
15676 0 : ((TableInfo *) dobj)->relkind == RELKIND_COMPOSITE_TYPE)
15677 0 : {
15678 : TypeInfo *cTypeInfo;
15679 :
15680 0 : cTypeInfo = findTypeByOid(((TableInfo *) dobj)->reltype);
15681 0 : if (cTypeInfo)
15682 0 : cTypeInfo->dobj.components |= DUMP_COMPONENT_SECLABEL;
15683 : }
15684 : else
15685 0 : dobj->components |= DUMP_COMPONENT_SECLABEL;
15686 :
15687 0 : seclabels[nseclabels].label = pg_strdup(PQgetvalue(res, i, i_label));
15688 0 : seclabels[nseclabels].provider = pg_strdup(PQgetvalue(res, i, i_provider));
15689 0 : seclabels[nseclabels].classoid = objId.tableoid;
15690 0 : seclabels[nseclabels].objoid = objId.oid;
15691 0 : seclabels[nseclabels].objsubid = subid;
15692 0 : nseclabels++;
15693 : }
15694 :
15695 308 : PQclear(res);
15696 308 : destroyPQExpBuffer(query);
15697 308 : }
15698 :
15699 : /*
15700 : * dumpTable
15701 : * write out to fout the declarations (not data) of a user-defined table
15702 : */
15703 : static void
15704 49974 : dumpTable(Archive *fout, const TableInfo *tbinfo)
15705 : {
15706 49974 : DumpOptions *dopt = fout->dopt;
15707 49974 : DumpId tableAclDumpId = InvalidDumpId;
15708 : char *namecopy;
15709 :
15710 : /* Do nothing in data-only dump */
15711 49974 : if (dopt->dataOnly)
15712 1734 : return;
15713 :
15714 48240 : if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
15715 : {
15716 11866 : if (tbinfo->relkind == RELKIND_SEQUENCE)
15717 696 : dumpSequence(fout, tbinfo);
15718 : else
15719 11170 : dumpTableSchema(fout, tbinfo);
15720 : }
15721 :
15722 : /* Handle the ACL here */
15723 48240 : namecopy = pg_strdup(fmtId(tbinfo->dobj.name));
15724 48240 : if (tbinfo->dobj.dump & DUMP_COMPONENT_ACL)
15725 : {
15726 37806 : const char *objtype =
15727 37806 : (tbinfo->relkind == RELKIND_SEQUENCE) ? "SEQUENCE" : "TABLE";
15728 :
15729 : tableAclDumpId =
15730 37806 : dumpACL(fout, tbinfo->dobj.dumpId, InvalidDumpId,
15731 : objtype, namecopy, NULL,
15732 37806 : tbinfo->dobj.namespace->dobj.name,
15733 : NULL, tbinfo->rolname, &tbinfo->dacl);
15734 : }
15735 :
15736 : /*
15737 : * Handle column ACLs, if any. Note: we pull these with a separate query
15738 : * rather than trying to fetch them during getTableAttrs, so that we won't
15739 : * miss ACLs on system columns. Doing it this way also allows us to dump
15740 : * ACLs for catalogs that we didn't mark "interesting" back in getTables.
15741 : */
15742 48240 : if ((tbinfo->dobj.dump & DUMP_COMPONENT_ACL) && tbinfo->hascolumnACLs)
15743 : {
15744 510 : PQExpBuffer query = createPQExpBuffer();
15745 : PGresult *res;
15746 : int i;
15747 :
15748 510 : if (!fout->is_prepared[PREPQUERY_GETCOLUMNACLS])
15749 : {
15750 : /* Set up query for column ACLs */
15751 262 : appendPQExpBufferStr(query,
15752 : "PREPARE getColumnACLs(pg_catalog.oid) AS\n");
15753 :
15754 262 : if (fout->remoteVersion >= 90600)
15755 : {
15756 : /*
15757 : * In principle we should call acldefault('c', relowner) to
15758 : * get the default ACL for a column. However, we don't
15759 : * currently store the numeric OID of the relowner in
15760 : * TableInfo. We could convert the owner name using regrole,
15761 : * but that creates a risk of failure due to concurrent role
15762 : * renames. Given that the default ACL for columns is empty
15763 : * and is likely to stay that way, it's not worth extra cycles
15764 : * and risk to avoid hard-wiring that knowledge here.
15765 : */
15766 262 : appendPQExpBufferStr(query,
15767 : "SELECT at.attname, "
15768 : "at.attacl, "
15769 : "'{}' AS acldefault, "
15770 : "pip.privtype, pip.initprivs "
15771 : "FROM pg_catalog.pg_attribute at "
15772 : "LEFT JOIN pg_catalog.pg_init_privs pip ON "
15773 : "(at.attrelid = pip.objoid "
15774 : "AND pip.classoid = 'pg_catalog.pg_class'::pg_catalog.regclass "
15775 : "AND at.attnum = pip.objsubid) "
15776 : "WHERE at.attrelid = $1 AND "
15777 : "NOT at.attisdropped "
15778 : "AND (at.attacl IS NOT NULL OR pip.initprivs IS NOT NULL) "
15779 : "ORDER BY at.attnum");
15780 : }
15781 : else
15782 : {
15783 0 : appendPQExpBufferStr(query,
15784 : "SELECT attname, attacl, '{}' AS acldefault, "
15785 : "NULL AS privtype, NULL AS initprivs "
15786 : "FROM pg_catalog.pg_attribute "
15787 : "WHERE attrelid = $1 AND NOT attisdropped "
15788 : "AND attacl IS NOT NULL "
15789 : "ORDER BY attnum");
15790 : }
15791 :
15792 262 : ExecuteSqlStatement(fout, query->data);
15793 :
15794 262 : fout->is_prepared[PREPQUERY_GETCOLUMNACLS] = true;
15795 : }
15796 :
15797 510 : printfPQExpBuffer(query,
15798 : "EXECUTE getColumnACLs('%u')",
15799 : tbinfo->dobj.catId.oid);
15800 :
15801 510 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15802 :
15803 7020 : for (i = 0; i < PQntuples(res); i++)
15804 : {
15805 6510 : char *attname = PQgetvalue(res, i, 0);
15806 6510 : char *attacl = PQgetvalue(res, i, 1);
15807 6510 : char *acldefault = PQgetvalue(res, i, 2);
15808 6510 : char privtype = *(PQgetvalue(res, i, 3));
15809 6510 : char *initprivs = PQgetvalue(res, i, 4);
15810 : DumpableAcl coldacl;
15811 : char *attnamecopy;
15812 :
15813 6510 : coldacl.acl = attacl;
15814 6510 : coldacl.acldefault = acldefault;
15815 6510 : coldacl.privtype = privtype;
15816 6510 : coldacl.initprivs = initprivs;
15817 6510 : attnamecopy = pg_strdup(fmtId(attname));
15818 :
15819 : /*
15820 : * Column's GRANT type is always TABLE. Each column ACL depends
15821 : * on the table-level ACL, since we can restore column ACLs in
15822 : * parallel but the table-level ACL has to be done first.
15823 : */
15824 6510 : dumpACL(fout, tbinfo->dobj.dumpId, tableAclDumpId,
15825 : "TABLE", namecopy, attnamecopy,
15826 6510 : tbinfo->dobj.namespace->dobj.name,
15827 : NULL, tbinfo->rolname, &coldacl);
15828 6510 : free(attnamecopy);
15829 : }
15830 510 : PQclear(res);
15831 510 : destroyPQExpBuffer(query);
15832 : }
15833 :
15834 48240 : free(namecopy);
15835 : }
15836 :
15837 : /*
15838 : * Create the AS clause for a view or materialized view. The semicolon is
15839 : * stripped because a materialized view must add a WITH NO DATA clause.
15840 : *
15841 : * This returns a new buffer which must be freed by the caller.
15842 : */
15843 : static PQExpBuffer
15844 1688 : createViewAsClause(Archive *fout, const TableInfo *tbinfo)
15845 : {
15846 1688 : PQExpBuffer query = createPQExpBuffer();
15847 1688 : PQExpBuffer result = createPQExpBuffer();
15848 : PGresult *res;
15849 : int len;
15850 :
15851 : /* Fetch the view definition */
15852 1688 : appendPQExpBuffer(query,
15853 : "SELECT pg_catalog.pg_get_viewdef('%u'::pg_catalog.oid) AS viewdef",
15854 : tbinfo->dobj.catId.oid);
15855 :
15856 1688 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
15857 :
15858 1688 : if (PQntuples(res) != 1)
15859 : {
15860 0 : if (PQntuples(res) < 1)
15861 0 : pg_fatal("query to obtain definition of view \"%s\" returned no data",
15862 : tbinfo->dobj.name);
15863 : else
15864 0 : pg_fatal("query to obtain definition of view \"%s\" returned more than one definition",
15865 : tbinfo->dobj.name);
15866 : }
15867 :
15868 1688 : len = PQgetlength(res, 0, 0);
15869 :
15870 1688 : if (len == 0)
15871 0 : pg_fatal("definition of view \"%s\" appears to be empty (length zero)",
15872 : tbinfo->dobj.name);
15873 :
15874 : /* Strip off the trailing semicolon so that other things may follow. */
15875 : Assert(PQgetvalue(res, 0, 0)[len - 1] == ';');
15876 1688 : appendBinaryPQExpBuffer(result, PQgetvalue(res, 0, 0), len - 1);
15877 :
15878 1688 : PQclear(res);
15879 1688 : destroyPQExpBuffer(query);
15880 :
15881 1688 : return result;
15882 : }
15883 :
15884 : /*
15885 : * Create a dummy AS clause for a view. This is used when the real view
15886 : * definition has to be postponed because of circular dependencies.
15887 : * We must duplicate the view's external properties -- column names and types
15888 : * (including collation) -- so that it works for subsequent references.
15889 : *
15890 : * This returns a new buffer which must be freed by the caller.
15891 : */
15892 : static PQExpBuffer
15893 40 : createDummyViewAsClause(Archive *fout, const TableInfo *tbinfo)
15894 : {
15895 40 : PQExpBuffer result = createPQExpBuffer();
15896 : int j;
15897 :
15898 40 : appendPQExpBufferStr(result, "SELECT");
15899 :
15900 80 : for (j = 0; j < tbinfo->numatts; j++)
15901 : {
15902 40 : if (j > 0)
15903 20 : appendPQExpBufferChar(result, ',');
15904 40 : appendPQExpBufferStr(result, "\n ");
15905 :
15906 40 : appendPQExpBuffer(result, "NULL::%s", tbinfo->atttypnames[j]);
15907 :
15908 : /*
15909 : * Must add collation if not default for the type, because CREATE OR
15910 : * REPLACE VIEW won't change it
15911 : */
15912 40 : if (OidIsValid(tbinfo->attcollation[j]))
15913 : {
15914 : CollInfo *coll;
15915 :
15916 0 : coll = findCollationByOid(tbinfo->attcollation[j]);
15917 0 : if (coll)
15918 0 : appendPQExpBuffer(result, " COLLATE %s",
15919 0 : fmtQualifiedDumpable(coll));
15920 : }
15921 :
15922 40 : appendPQExpBuffer(result, " AS %s", fmtId(tbinfo->attnames[j]));
15923 : }
15924 :
15925 40 : return result;
15926 : }
15927 :
15928 : /*
15929 : * dumpTableSchema
15930 : * write the declaration (not data) of one user-defined table or view
15931 : */
15932 : static void
15933 11170 : dumpTableSchema(Archive *fout, const TableInfo *tbinfo)
15934 : {
15935 11170 : DumpOptions *dopt = fout->dopt;
15936 11170 : PQExpBuffer q = createPQExpBuffer();
15937 11170 : PQExpBuffer delq = createPQExpBuffer();
15938 11170 : PQExpBuffer extra = createPQExpBuffer();
15939 : char *qrelname;
15940 : char *qualrelname;
15941 : int numParents;
15942 : TableInfo **parents;
15943 : int actual_atts; /* number of attrs in this CREATE statement */
15944 : const char *reltypename;
15945 : char *storage;
15946 : int j,
15947 : k;
15948 :
15949 : /* We had better have loaded per-column details about this table */
15950 : Assert(tbinfo->interesting);
15951 :
15952 11170 : qrelname = pg_strdup(fmtId(tbinfo->dobj.name));
15953 11170 : qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
15954 :
15955 11170 : if (tbinfo->hasoids)
15956 0 : pg_log_warning("WITH OIDS is not supported anymore (table \"%s\")",
15957 : qrelname);
15958 :
15959 11170 : if (dopt->binary_upgrade)
15960 1522 : binary_upgrade_set_type_oids_by_rel(fout, q, tbinfo);
15961 :
15962 : /* Is it a table or a view? */
15963 11170 : if (tbinfo->relkind == RELKIND_VIEW)
15964 : {
15965 : PQExpBuffer result;
15966 :
15967 : /*
15968 : * Note: keep this code in sync with the is_view case in dumpRule()
15969 : */
15970 :
15971 1014 : reltypename = "VIEW";
15972 :
15973 1014 : appendPQExpBuffer(delq, "DROP VIEW %s;\n", qualrelname);
15974 :
15975 1014 : if (dopt->binary_upgrade)
15976 98 : binary_upgrade_set_pg_class_oids(fout, q,
15977 : tbinfo->dobj.catId.oid);
15978 :
15979 1014 : appendPQExpBuffer(q, "CREATE VIEW %s", qualrelname);
15980 :
15981 1014 : if (tbinfo->dummy_view)
15982 20 : result = createDummyViewAsClause(fout, tbinfo);
15983 : else
15984 : {
15985 994 : if (nonemptyReloptions(tbinfo->reloptions))
15986 : {
15987 124 : appendPQExpBufferStr(q, " WITH (");
15988 124 : appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
15989 124 : appendPQExpBufferChar(q, ')');
15990 : }
15991 994 : result = createViewAsClause(fout, tbinfo);
15992 : }
15993 1014 : appendPQExpBuffer(q, " AS\n%s", result->data);
15994 1014 : destroyPQExpBuffer(result);
15995 :
15996 1014 : if (tbinfo->checkoption != NULL && !tbinfo->dummy_view)
15997 66 : appendPQExpBuffer(q, "\n WITH %s CHECK OPTION", tbinfo->checkoption);
15998 1014 : appendPQExpBufferStr(q, ";\n");
15999 : }
16000 : else
16001 : {
16002 10156 : char *partkeydef = NULL;
16003 10156 : char *ftoptions = NULL;
16004 10156 : char *srvname = NULL;
16005 10156 : const char *foreign = "";
16006 :
16007 : /*
16008 : * Set reltypename, and collect any relkind-specific data that we
16009 : * didn't fetch during getTables().
16010 : */
16011 10156 : switch (tbinfo->relkind)
16012 : {
16013 1036 : case RELKIND_PARTITIONED_TABLE:
16014 : {
16015 1036 : PQExpBuffer query = createPQExpBuffer();
16016 : PGresult *res;
16017 :
16018 1036 : reltypename = "TABLE";
16019 :
16020 : /* retrieve partition key definition */
16021 1036 : appendPQExpBuffer(query,
16022 : "SELECT pg_get_partkeydef('%u')",
16023 : tbinfo->dobj.catId.oid);
16024 1036 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
16025 1036 : partkeydef = pg_strdup(PQgetvalue(res, 0, 0));
16026 1036 : PQclear(res);
16027 1036 : destroyPQExpBuffer(query);
16028 1036 : break;
16029 : }
16030 70 : case RELKIND_FOREIGN_TABLE:
16031 : {
16032 70 : PQExpBuffer query = createPQExpBuffer();
16033 : PGresult *res;
16034 : int i_srvname;
16035 : int i_ftoptions;
16036 :
16037 70 : reltypename = "FOREIGN TABLE";
16038 :
16039 : /* retrieve name of foreign server and generic options */
16040 70 : appendPQExpBuffer(query,
16041 : "SELECT fs.srvname, "
16042 : "pg_catalog.array_to_string(ARRAY("
16043 : "SELECT pg_catalog.quote_ident(option_name) || "
16044 : "' ' || pg_catalog.quote_literal(option_value) "
16045 : "FROM pg_catalog.pg_options_to_table(ftoptions) "
16046 : "ORDER BY option_name"
16047 : "), E',\n ') AS ftoptions "
16048 : "FROM pg_catalog.pg_foreign_table ft "
16049 : "JOIN pg_catalog.pg_foreign_server fs "
16050 : "ON (fs.oid = ft.ftserver) "
16051 : "WHERE ft.ftrelid = '%u'",
16052 : tbinfo->dobj.catId.oid);
16053 70 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
16054 70 : i_srvname = PQfnumber(res, "srvname");
16055 70 : i_ftoptions = PQfnumber(res, "ftoptions");
16056 70 : srvname = pg_strdup(PQgetvalue(res, 0, i_srvname));
16057 70 : ftoptions = pg_strdup(PQgetvalue(res, 0, i_ftoptions));
16058 70 : PQclear(res);
16059 70 : destroyPQExpBuffer(query);
16060 :
16061 70 : foreign = "FOREIGN ";
16062 70 : break;
16063 : }
16064 674 : case RELKIND_MATVIEW:
16065 674 : reltypename = "MATERIALIZED VIEW";
16066 674 : break;
16067 8376 : default:
16068 8376 : reltypename = "TABLE";
16069 8376 : break;
16070 : }
16071 :
16072 10156 : numParents = tbinfo->numParents;
16073 10156 : parents = tbinfo->parents;
16074 :
16075 10156 : appendPQExpBuffer(delq, "DROP %s %s;\n", reltypename, qualrelname);
16076 :
16077 10156 : if (dopt->binary_upgrade)
16078 1424 : binary_upgrade_set_pg_class_oids(fout, q,
16079 : tbinfo->dobj.catId.oid);
16080 :
16081 : /*
16082 : * PostgreSQL 18 has disabled UNLOGGED for partitioned tables, so
16083 : * ignore it when dumping if it was set in this case.
16084 : */
16085 10156 : appendPQExpBuffer(q, "CREATE %s%s %s",
16086 10156 : (tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED &&
16087 40 : tbinfo->relkind != RELKIND_PARTITIONED_TABLE) ?
16088 : "UNLOGGED " : "",
16089 : reltypename,
16090 : qualrelname);
16091 :
16092 : /*
16093 : * Attach to type, if reloftype; except in case of a binary upgrade,
16094 : * we dump the table normally and attach it to the type afterward.
16095 : */
16096 10156 : if (OidIsValid(tbinfo->reloftype) && !dopt->binary_upgrade)
16097 48 : appendPQExpBuffer(q, " OF %s",
16098 : getFormattedTypeName(fout, tbinfo->reloftype,
16099 : zeroIsError));
16100 :
16101 10156 : if (tbinfo->relkind != RELKIND_MATVIEW)
16102 : {
16103 : /* Dump the attributes */
16104 9482 : actual_atts = 0;
16105 46736 : for (j = 0; j < tbinfo->numatts; j++)
16106 : {
16107 : /*
16108 : * Normally, dump if it's locally defined in this table, and
16109 : * not dropped. But for binary upgrade, we'll dump all the
16110 : * columns, and then fix up the dropped and nonlocal cases
16111 : * below.
16112 : */
16113 37254 : if (shouldPrintColumn(dopt, tbinfo, j))
16114 : {
16115 : bool print_default;
16116 : bool print_notnull;
16117 :
16118 : /*
16119 : * Default value --- suppress if to be printed separately
16120 : * or not at all.
16121 : */
16122 72886 : print_default = (tbinfo->attrdefs[j] != NULL &&
16123 37126 : tbinfo->attrdefs[j]->dobj.dump &&
16124 1446 : !tbinfo->attrdefs[j]->separate);
16125 :
16126 : /*
16127 : * Not Null constraint --- print it if it is locally
16128 : * defined, or if binary upgrade. (In the latter case, we
16129 : * reset conislocal below.)
16130 : */
16131 39604 : print_notnull = (tbinfo->notnull_constrs[j] != NULL &&
16132 3924 : (tbinfo->notnull_islocal[j] ||
16133 1076 : dopt->binary_upgrade ||
16134 932 : tbinfo->ispartition));
16135 :
16136 : /*
16137 : * Skip column if fully defined by reloftype, except in
16138 : * binary upgrade
16139 : */
16140 35680 : if (OidIsValid(tbinfo->reloftype) &&
16141 100 : !print_default && !print_notnull &&
16142 60 : !dopt->binary_upgrade)
16143 48 : continue;
16144 :
16145 : /* Format properly if not first attr */
16146 35632 : if (actual_atts == 0)
16147 9002 : appendPQExpBufferStr(q, " (");
16148 : else
16149 26630 : appendPQExpBufferChar(q, ',');
16150 35632 : appendPQExpBufferStr(q, "\n ");
16151 35632 : actual_atts++;
16152 :
16153 : /* Attribute name */
16154 35632 : appendPQExpBufferStr(q, fmtId(tbinfo->attnames[j]));
16155 :
16156 35632 : if (tbinfo->attisdropped[j])
16157 : {
16158 : /*
16159 : * ALTER TABLE DROP COLUMN clears
16160 : * pg_attribute.atttypid, so we will not have gotten a
16161 : * valid type name; insert INTEGER as a stopgap. We'll
16162 : * clean things up later.
16163 : */
16164 158 : appendPQExpBufferStr(q, " INTEGER /* dummy */");
16165 : /* and skip to the next column */
16166 158 : continue;
16167 : }
16168 :
16169 : /*
16170 : * Attribute type; print it except when creating a typed
16171 : * table ('OF type_name'), but in binary-upgrade mode,
16172 : * print it in that case too.
16173 : */
16174 35474 : if (dopt->binary_upgrade || !OidIsValid(tbinfo->reloftype))
16175 : {
16176 35442 : appendPQExpBuffer(q, " %s",
16177 35442 : tbinfo->atttypnames[j]);
16178 : }
16179 :
16180 35474 : if (print_default)
16181 : {
16182 1232 : if (tbinfo->attgenerated[j] == ATTRIBUTE_GENERATED_STORED)
16183 530 : appendPQExpBuffer(q, " GENERATED ALWAYS AS (%s) STORED",
16184 530 : tbinfo->attrdefs[j]->adef_expr);
16185 : else
16186 702 : appendPQExpBuffer(q, " DEFAULT %s",
16187 702 : tbinfo->attrdefs[j]->adef_expr);
16188 : }
16189 :
16190 39398 : print_notnull = (tbinfo->notnull_constrs[j] != NULL &&
16191 3924 : (tbinfo->notnull_islocal[j] ||
16192 1076 : dopt->binary_upgrade ||
16193 932 : tbinfo->ispartition));
16194 :
16195 35474 : if (print_notnull)
16196 : {
16197 3860 : if (tbinfo->notnull_constrs[j][0] == '\0')
16198 2766 : appendPQExpBufferStr(q, " NOT NULL");
16199 : else
16200 1094 : appendPQExpBuffer(q, " CONSTRAINT %s NOT NULL",
16201 1094 : fmtId(tbinfo->notnull_constrs[j]));
16202 :
16203 3860 : if (tbinfo->notnull_noinh[j])
16204 0 : appendPQExpBufferStr(q, " NO INHERIT");
16205 : }
16206 :
16207 : /* Add collation if not default for the type */
16208 35474 : if (OidIsValid(tbinfo->attcollation[j]))
16209 : {
16210 : CollInfo *coll;
16211 :
16212 394 : coll = findCollationByOid(tbinfo->attcollation[j]);
16213 394 : if (coll)
16214 394 : appendPQExpBuffer(q, " COLLATE %s",
16215 394 : fmtQualifiedDumpable(coll));
16216 : }
16217 : }
16218 : }
16219 :
16220 : /*
16221 : * Add non-inherited CHECK constraints, if any.
16222 : *
16223 : * For partitions, we need to include check constraints even if
16224 : * they're not defined locally, because the ALTER TABLE ATTACH
16225 : * PARTITION that we'll emit later expects the constraint to be
16226 : * there. (No need to fix conislocal: ATTACH PARTITION does that)
16227 : */
16228 10558 : for (j = 0; j < tbinfo->ncheck; j++)
16229 : {
16230 1076 : ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16231 :
16232 1076 : if (constr->separate ||
16233 996 : (!constr->conislocal && !tbinfo->ispartition))
16234 156 : continue;
16235 :
16236 920 : if (actual_atts == 0)
16237 32 : appendPQExpBufferStr(q, " (\n ");
16238 : else
16239 888 : appendPQExpBufferStr(q, ",\n ");
16240 :
16241 920 : appendPQExpBuffer(q, "CONSTRAINT %s ",
16242 920 : fmtId(constr->dobj.name));
16243 920 : appendPQExpBufferStr(q, constr->condef);
16244 :
16245 920 : actual_atts++;
16246 : }
16247 :
16248 9482 : if (actual_atts)
16249 9034 : appendPQExpBufferStr(q, "\n)");
16250 448 : else if (!(OidIsValid(tbinfo->reloftype) && !dopt->binary_upgrade))
16251 : {
16252 : /*
16253 : * No attributes? we must have a parenthesized attribute list,
16254 : * even though empty, when not using the OF TYPE syntax.
16255 : */
16256 424 : appendPQExpBufferStr(q, " (\n)");
16257 : }
16258 :
16259 : /*
16260 : * Emit the INHERITS clause (not for partitions), except in
16261 : * binary-upgrade mode.
16262 : */
16263 9482 : if (numParents > 0 && !tbinfo->ispartition &&
16264 672 : !dopt->binary_upgrade)
16265 : {
16266 574 : appendPQExpBufferStr(q, "\nINHERITS (");
16267 1204 : for (k = 0; k < numParents; k++)
16268 : {
16269 630 : TableInfo *parentRel = parents[k];
16270 :
16271 630 : if (k > 0)
16272 56 : appendPQExpBufferStr(q, ", ");
16273 630 : appendPQExpBufferStr(q, fmtQualifiedDumpable(parentRel));
16274 : }
16275 574 : appendPQExpBufferChar(q, ')');
16276 : }
16277 :
16278 9482 : if (tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
16279 1036 : appendPQExpBuffer(q, "\nPARTITION BY %s", partkeydef);
16280 :
16281 9482 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE)
16282 70 : appendPQExpBuffer(q, "\nSERVER %s", fmtId(srvname));
16283 : }
16284 :
16285 20026 : if (nonemptyReloptions(tbinfo->reloptions) ||
16286 9870 : nonemptyReloptions(tbinfo->toast_reloptions))
16287 : {
16288 286 : bool addcomma = false;
16289 :
16290 286 : appendPQExpBufferStr(q, "\nWITH (");
16291 286 : if (nonemptyReloptions(tbinfo->reloptions))
16292 : {
16293 286 : addcomma = true;
16294 286 : appendReloptionsArrayAH(q, tbinfo->reloptions, "", fout);
16295 : }
16296 286 : if (nonemptyReloptions(tbinfo->toast_reloptions))
16297 : {
16298 10 : if (addcomma)
16299 10 : appendPQExpBufferStr(q, ", ");
16300 10 : appendReloptionsArrayAH(q, tbinfo->toast_reloptions, "toast.",
16301 : fout);
16302 : }
16303 286 : appendPQExpBufferChar(q, ')');
16304 : }
16305 :
16306 : /* Dump generic options if any */
16307 10156 : if (ftoptions && ftoptions[0])
16308 66 : appendPQExpBuffer(q, "\nOPTIONS (\n %s\n)", ftoptions);
16309 :
16310 : /*
16311 : * For materialized views, create the AS clause just like a view. At
16312 : * this point, we always mark the view as not populated.
16313 : */
16314 10156 : if (tbinfo->relkind == RELKIND_MATVIEW)
16315 : {
16316 : PQExpBuffer result;
16317 :
16318 674 : result = createViewAsClause(fout, tbinfo);
16319 674 : appendPQExpBuffer(q, " AS\n%s\n WITH NO DATA;\n",
16320 : result->data);
16321 674 : destroyPQExpBuffer(result);
16322 : }
16323 : else
16324 9482 : appendPQExpBufferStr(q, ";\n");
16325 :
16326 : /* Materialized views can depend on extensions */
16327 10156 : if (tbinfo->relkind == RELKIND_MATVIEW)
16328 674 : append_depends_on_extension(fout, q, &tbinfo->dobj,
16329 : "pg_catalog.pg_class",
16330 : "MATERIALIZED VIEW",
16331 : qualrelname);
16332 :
16333 : /*
16334 : * in binary upgrade mode, update the catalog with any missing values
16335 : * that might be present.
16336 : */
16337 10156 : if (dopt->binary_upgrade)
16338 : {
16339 7296 : for (j = 0; j < tbinfo->numatts; j++)
16340 : {
16341 5872 : if (tbinfo->attmissingval[j][0] != '\0')
16342 : {
16343 4 : appendPQExpBufferStr(q, "\n-- set missing value.\n");
16344 4 : appendPQExpBufferStr(q,
16345 : "SELECT pg_catalog.binary_upgrade_set_missing_value(");
16346 4 : appendStringLiteralAH(q, qualrelname, fout);
16347 4 : appendPQExpBufferStr(q, "::pg_catalog.regclass,");
16348 4 : appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16349 4 : appendPQExpBufferChar(q, ',');
16350 4 : appendStringLiteralAH(q, tbinfo->attmissingval[j], fout);
16351 4 : appendPQExpBufferStr(q, ");\n\n");
16352 : }
16353 : }
16354 : }
16355 :
16356 : /*
16357 : * To create binary-compatible heap files, we have to ensure the same
16358 : * physical column order, including dropped columns, as in the
16359 : * original. Therefore, we create dropped columns above and drop them
16360 : * here, also updating their attlen/attalign values so that the
16361 : * dropped column can be skipped properly. (We do not bother with
16362 : * restoring the original attbyval setting.) Also, inheritance
16363 : * relationships are set up by doing ALTER TABLE INHERIT rather than
16364 : * using an INHERITS clause --- the latter would possibly mess up the
16365 : * column order. That also means we have to take care about setting
16366 : * attislocal correctly, plus fix up any inherited CHECK constraints.
16367 : * Analogously, we set up typed tables using ALTER TABLE / OF here.
16368 : *
16369 : * We process foreign and partitioned tables here, even though they
16370 : * lack heap storage, because they can participate in inheritance
16371 : * relationships and we want this stuff to be consistent across the
16372 : * inheritance tree. We can exclude indexes, toast tables, sequences
16373 : * and matviews, even though they have storage, because we don't
16374 : * support altering or dropping columns in them, nor can they be part
16375 : * of inheritance trees.
16376 : */
16377 10156 : if (dopt->binary_upgrade &&
16378 1424 : (tbinfo->relkind == RELKIND_RELATION ||
16379 208 : tbinfo->relkind == RELKIND_FOREIGN_TABLE ||
16380 206 : tbinfo->relkind == RELKIND_PARTITIONED_TABLE))
16381 : {
16382 : bool firstitem;
16383 : bool firstitem_extra;
16384 :
16385 : /*
16386 : * Drop any dropped columns. Merge the pg_attribute manipulations
16387 : * into a single SQL command, so that we don't cause repeated
16388 : * relcache flushes on the target table. Otherwise we risk O(N^2)
16389 : * relcache bloat while dropping N columns.
16390 : */
16391 1390 : resetPQExpBuffer(extra);
16392 1390 : firstitem = true;
16393 7222 : for (j = 0; j < tbinfo->numatts; j++)
16394 : {
16395 5832 : if (tbinfo->attisdropped[j])
16396 : {
16397 158 : if (firstitem)
16398 : {
16399 68 : appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate dropped columns.\n"
16400 : "UPDATE pg_catalog.pg_attribute\n"
16401 : "SET attlen = v.dlen, "
16402 : "attalign = v.dalign, "
16403 : "attbyval = false\n"
16404 : "FROM (VALUES ");
16405 68 : firstitem = false;
16406 : }
16407 : else
16408 90 : appendPQExpBufferStr(q, ",\n ");
16409 158 : appendPQExpBufferChar(q, '(');
16410 158 : appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16411 158 : appendPQExpBuffer(q, ", %d, '%c')",
16412 158 : tbinfo->attlen[j],
16413 158 : tbinfo->attalign[j]);
16414 : /* The ALTER ... DROP COLUMN commands must come after */
16415 158 : appendPQExpBuffer(extra, "ALTER %sTABLE ONLY %s ",
16416 : foreign, qualrelname);
16417 158 : appendPQExpBuffer(extra, "DROP COLUMN %s;\n",
16418 158 : fmtId(tbinfo->attnames[j]));
16419 : }
16420 : }
16421 1390 : if (!firstitem)
16422 : {
16423 68 : appendPQExpBufferStr(q, ") v(dname, dlen, dalign)\n"
16424 : "WHERE attrelid = ");
16425 68 : appendStringLiteralAH(q, qualrelname, fout);
16426 68 : appendPQExpBufferStr(q, "::pg_catalog.regclass\n"
16427 : " AND attname = v.dname;\n");
16428 : /* Now we can issue the actual DROP COLUMN commands */
16429 68 : appendBinaryPQExpBuffer(q, extra->data, extra->len);
16430 : }
16431 :
16432 : /*
16433 : * Fix up inherited columns. As above, do the pg_attribute
16434 : * manipulations in a single SQL command.
16435 : */
16436 1390 : firstitem = true;
16437 7222 : for (j = 0; j < tbinfo->numatts; j++)
16438 : {
16439 5832 : if (!tbinfo->attisdropped[j] &&
16440 5674 : !tbinfo->attislocal[j])
16441 : {
16442 1118 : if (firstitem)
16443 : {
16444 488 : appendPQExpBufferStr(q, "\n-- For binary upgrade, recreate inherited columns.\n");
16445 488 : appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_attribute\n"
16446 : "SET attislocal = false\n"
16447 : "WHERE attrelid = ");
16448 488 : appendStringLiteralAH(q, qualrelname, fout);
16449 488 : appendPQExpBufferStr(q, "::pg_catalog.regclass\n"
16450 : " AND attname IN (");
16451 488 : firstitem = false;
16452 : }
16453 : else
16454 630 : appendPQExpBufferStr(q, ", ");
16455 1118 : appendStringLiteralAH(q, tbinfo->attnames[j], fout);
16456 : }
16457 : }
16458 1390 : if (!firstitem)
16459 488 : appendPQExpBufferStr(q, ");\n");
16460 :
16461 : /*
16462 : * Fix up not-null constraints that come from inheritance. As
16463 : * above, do the pg_constraint manipulations in a single SQL
16464 : * command. (Actually, two in special cases, if we're doing an
16465 : * upgrade from < 18).
16466 : */
16467 1390 : firstitem = true;
16468 1390 : firstitem_extra = true;
16469 1390 : resetPQExpBuffer(extra);
16470 7222 : for (j = 0; j < tbinfo->numatts; j++)
16471 : {
16472 : /*
16473 : * If a not-null constraint comes from inheritance, reset
16474 : * conislocal. The inhcount is fixed by ALTER TABLE INHERIT,
16475 : * below. Special hack: in versions < 18, columns with no
16476 : * local definition need their constraint to be matched by
16477 : * column number in conkeys instead of by contraint name,
16478 : * because the latter is not available. (We distinguish the
16479 : * case because the constraint name is the empty string.)
16480 : */
16481 5832 : if (tbinfo->notnull_constrs[j] != NULL &&
16482 480 : !tbinfo->notnull_islocal[j])
16483 : {
16484 144 : if (tbinfo->notnull_constrs[j][0] != '\0')
16485 : {
16486 120 : if (firstitem)
16487 : {
16488 104 : appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_constraint\n"
16489 : "SET conislocal = false\n"
16490 : "WHERE contype = 'n' AND conrelid = ");
16491 104 : appendStringLiteralAH(q, qualrelname, fout);
16492 104 : appendPQExpBufferStr(q, "::pg_catalog.regclass AND\n"
16493 : "conname IN (");
16494 104 : firstitem = false;
16495 : }
16496 : else
16497 16 : appendPQExpBufferStr(q, ", ");
16498 120 : appendStringLiteralAH(q, tbinfo->notnull_constrs[j], fout);
16499 : }
16500 : else
16501 : {
16502 24 : if (firstitem_extra)
16503 : {
16504 24 : appendPQExpBufferStr(extra, "UPDATE pg_catalog.pg_constraint\n"
16505 : "SET conislocal = false\n"
16506 : "WHERE contype = 'n' AND conrelid = ");
16507 24 : appendStringLiteralAH(extra, qualrelname, fout);
16508 24 : appendPQExpBufferStr(extra, "::pg_catalog.regclass AND\n"
16509 : "conkey IN (");
16510 24 : firstitem_extra = false;
16511 : }
16512 : else
16513 0 : appendPQExpBufferStr(extra, ", ");
16514 24 : appendPQExpBuffer(extra, "'{%d}'", j + 1);
16515 : }
16516 : }
16517 : }
16518 1390 : if (!firstitem)
16519 104 : appendPQExpBufferStr(q, ");\n");
16520 1390 : if (!firstitem_extra)
16521 24 : appendPQExpBufferStr(extra, ");\n");
16522 :
16523 1390 : if (extra->len > 0)
16524 24 : appendBinaryPQExpBuffer(q, extra->data, extra->len);
16525 :
16526 : /*
16527 : * Add inherited CHECK constraints, if any.
16528 : *
16529 : * For partitions, they were already dumped, and conislocal
16530 : * doesn't need fixing.
16531 : *
16532 : * As above, issue only one direct manipulation of pg_constraint.
16533 : * Although it is tempting to merge the ALTER ADD CONSTRAINT
16534 : * commands into one as well, refrain for now due to concern about
16535 : * possible backend memory bloat if there are many such
16536 : * constraints.
16537 : */
16538 1390 : resetPQExpBuffer(extra);
16539 1390 : firstitem = true;
16540 1496 : for (k = 0; k < tbinfo->ncheck; k++)
16541 : {
16542 106 : ConstraintInfo *constr = &(tbinfo->checkexprs[k]);
16543 :
16544 106 : if (constr->separate || constr->conislocal || tbinfo->ispartition)
16545 102 : continue;
16546 :
16547 4 : if (firstitem)
16548 4 : appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inherited constraints.\n");
16549 4 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ADD CONSTRAINT %s %s;\n",
16550 : foreign, qualrelname,
16551 4 : fmtId(constr->dobj.name),
16552 : constr->condef);
16553 : /* Update pg_constraint after all the ALTER TABLEs */
16554 4 : if (firstitem)
16555 : {
16556 4 : appendPQExpBufferStr(extra, "UPDATE pg_catalog.pg_constraint\n"
16557 : "SET conislocal = false\n"
16558 : "WHERE contype = 'c' AND conrelid = ");
16559 4 : appendStringLiteralAH(extra, qualrelname, fout);
16560 4 : appendPQExpBufferStr(extra, "::pg_catalog.regclass\n");
16561 4 : appendPQExpBufferStr(extra, " AND conname IN (");
16562 4 : firstitem = false;
16563 : }
16564 : else
16565 0 : appendPQExpBufferStr(extra, ", ");
16566 4 : appendStringLiteralAH(extra, constr->dobj.name, fout);
16567 : }
16568 1390 : if (!firstitem)
16569 : {
16570 4 : appendPQExpBufferStr(extra, ");\n");
16571 4 : appendBinaryPQExpBuffer(q, extra->data, extra->len);
16572 : }
16573 :
16574 1390 : if (numParents > 0 && !tbinfo->ispartition)
16575 : {
16576 98 : appendPQExpBufferStr(q, "\n-- For binary upgrade, set up inheritance this way.\n");
16577 210 : for (k = 0; k < numParents; k++)
16578 : {
16579 112 : TableInfo *parentRel = parents[k];
16580 :
16581 112 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s INHERIT %s;\n", foreign,
16582 : qualrelname,
16583 112 : fmtQualifiedDumpable(parentRel));
16584 : }
16585 : }
16586 :
16587 1390 : if (OidIsValid(tbinfo->reloftype))
16588 : {
16589 12 : appendPQExpBufferStr(q, "\n-- For binary upgrade, set up typed tables this way.\n");
16590 12 : appendPQExpBuffer(q, "ALTER TABLE ONLY %s OF %s;\n",
16591 : qualrelname,
16592 : getFormattedTypeName(fout, tbinfo->reloftype,
16593 : zeroIsError));
16594 : }
16595 : }
16596 :
16597 : /*
16598 : * In binary_upgrade mode, arrange to restore the old relfrozenxid and
16599 : * relminmxid of all vacuumable relations. (While vacuum.c processes
16600 : * TOAST tables semi-independently, here we see them only as children
16601 : * of other relations; so this "if" lacks RELKIND_TOASTVALUE, and the
16602 : * child toast table is handled below.)
16603 : */
16604 10156 : if (dopt->binary_upgrade &&
16605 1424 : (tbinfo->relkind == RELKIND_RELATION ||
16606 208 : tbinfo->relkind == RELKIND_MATVIEW))
16607 : {
16608 1250 : appendPQExpBufferStr(q, "\n-- For binary upgrade, set heap's relfrozenxid and relminmxid\n");
16609 1250 : appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16610 : "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16611 : "WHERE oid = ",
16612 : tbinfo->frozenxid, tbinfo->minmxid);
16613 1250 : appendStringLiteralAH(q, qualrelname, fout);
16614 1250 : appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16615 :
16616 1250 : if (tbinfo->toast_oid)
16617 : {
16618 : /*
16619 : * The toast table will have the same OID at restore, so we
16620 : * can safely target it by OID.
16621 : */
16622 548 : appendPQExpBufferStr(q, "\n-- For binary upgrade, set toast's relfrozenxid and relminmxid\n");
16623 548 : appendPQExpBuffer(q, "UPDATE pg_catalog.pg_class\n"
16624 : "SET relfrozenxid = '%u', relminmxid = '%u'\n"
16625 : "WHERE oid = '%u';\n",
16626 : tbinfo->toast_frozenxid,
16627 : tbinfo->toast_minmxid, tbinfo->toast_oid);
16628 : }
16629 : }
16630 :
16631 : /*
16632 : * In binary_upgrade mode, restore matviews' populated status by
16633 : * poking pg_class directly. This is pretty ugly, but we can't use
16634 : * REFRESH MATERIALIZED VIEW since it's possible that some underlying
16635 : * matview is not populated even though this matview is; in any case,
16636 : * we want to transfer the matview's heap storage, not run REFRESH.
16637 : */
16638 10156 : if (dopt->binary_upgrade && tbinfo->relkind == RELKIND_MATVIEW &&
16639 34 : tbinfo->relispopulated)
16640 : {
16641 30 : appendPQExpBufferStr(q, "\n-- For binary upgrade, mark materialized view as populated\n");
16642 30 : appendPQExpBufferStr(q, "UPDATE pg_catalog.pg_class\n"
16643 : "SET relispopulated = 't'\n"
16644 : "WHERE oid = ");
16645 30 : appendStringLiteralAH(q, qualrelname, fout);
16646 30 : appendPQExpBufferStr(q, "::pg_catalog.regclass;\n");
16647 : }
16648 :
16649 : /*
16650 : * Dump additional per-column properties that we can't handle in the
16651 : * main CREATE TABLE command.
16652 : */
16653 48170 : for (j = 0; j < tbinfo->numatts; j++)
16654 : {
16655 : /* None of this applies to dropped columns */
16656 38014 : if (tbinfo->attisdropped[j])
16657 846 : continue;
16658 :
16659 : /*
16660 : * If we didn't dump the column definition explicitly above, and
16661 : * it is not-null and did not inherit that property from a parent,
16662 : * we have to mark it separately.
16663 : */
16664 37168 : if (!shouldPrintColumn(dopt, tbinfo, j) &&
16665 886 : tbinfo->notnull_constrs[j] != NULL &&
16666 176 : (tbinfo->notnull_islocal[j] && !tbinfo->ispartition && !dopt->binary_upgrade))
16667 : {
16668 : /* No constraint name desired? */
16669 32 : if (tbinfo->notnull_constrs[j][0] == '\0')
16670 8 : appendPQExpBuffer(q,
16671 : "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET NOT NULL;\n",
16672 : foreign, qualrelname,
16673 8 : fmtId(tbinfo->attnames[j]));
16674 : else
16675 48 : appendPQExpBuffer(q,
16676 : "ALTER %sTABLE ONLY %s ADD CONSTRAINT %s NOT NULL %s;\n",
16677 : foreign, qualrelname,
16678 24 : tbinfo->notnull_constrs[j],
16679 24 : fmtId(tbinfo->attnames[j]));
16680 : }
16681 :
16682 : /*
16683 : * Dump per-column statistics information. We only issue an ALTER
16684 : * TABLE statement if the attstattarget entry for this column is
16685 : * not the default value.
16686 : */
16687 37168 : if (tbinfo->attstattarget[j] >= 0)
16688 66 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET STATISTICS %d;\n",
16689 : foreign, qualrelname,
16690 66 : fmtId(tbinfo->attnames[j]),
16691 66 : tbinfo->attstattarget[j]);
16692 :
16693 : /*
16694 : * Dump per-column storage information. The statement is only
16695 : * dumped if the storage has been changed from the type's default.
16696 : */
16697 37168 : if (tbinfo->attstorage[j] != tbinfo->typstorage[j])
16698 : {
16699 162 : switch (tbinfo->attstorage[j])
16700 : {
16701 20 : case TYPSTORAGE_PLAIN:
16702 20 : storage = "PLAIN";
16703 20 : break;
16704 76 : case TYPSTORAGE_EXTERNAL:
16705 76 : storage = "EXTERNAL";
16706 76 : break;
16707 0 : case TYPSTORAGE_EXTENDED:
16708 0 : storage = "EXTENDED";
16709 0 : break;
16710 66 : case TYPSTORAGE_MAIN:
16711 66 : storage = "MAIN";
16712 66 : break;
16713 0 : default:
16714 0 : storage = NULL;
16715 : }
16716 :
16717 : /*
16718 : * Only dump the statement if it's a storage type we recognize
16719 : */
16720 162 : if (storage != NULL)
16721 162 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET STORAGE %s;\n",
16722 : foreign, qualrelname,
16723 162 : fmtId(tbinfo->attnames[j]),
16724 : storage);
16725 : }
16726 :
16727 : /*
16728 : * Dump per-column compression, if it's been set.
16729 : */
16730 37168 : if (!dopt->no_toast_compression)
16731 : {
16732 : const char *cmname;
16733 :
16734 37002 : switch (tbinfo->attcompression[j])
16735 : {
16736 114 : case 'p':
16737 114 : cmname = "pglz";
16738 114 : break;
16739 188 : case 'l':
16740 188 : cmname = "lz4";
16741 188 : break;
16742 36700 : default:
16743 36700 : cmname = NULL;
16744 36700 : break;
16745 : }
16746 :
16747 37002 : if (cmname != NULL)
16748 302 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET COMPRESSION %s;\n",
16749 : foreign, qualrelname,
16750 302 : fmtId(tbinfo->attnames[j]),
16751 : cmname);
16752 : }
16753 :
16754 : /*
16755 : * Dump per-column attributes.
16756 : */
16757 37168 : if (tbinfo->attoptions[j][0] != '\0')
16758 66 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET (%s);\n",
16759 : foreign, qualrelname,
16760 66 : fmtId(tbinfo->attnames[j]),
16761 66 : tbinfo->attoptions[j]);
16762 :
16763 : /*
16764 : * Dump per-column fdw options.
16765 : */
16766 37168 : if (tbinfo->relkind == RELKIND_FOREIGN_TABLE &&
16767 70 : tbinfo->attfdwoptions[j][0] != '\0')
16768 66 : appendPQExpBuffer(q,
16769 : "ALTER FOREIGN TABLE ONLY %s ALTER COLUMN %s OPTIONS (\n"
16770 : " %s\n"
16771 : ");\n",
16772 : qualrelname,
16773 66 : fmtId(tbinfo->attnames[j]),
16774 66 : tbinfo->attfdwoptions[j]);
16775 : } /* end loop over columns */
16776 :
16777 10156 : free(partkeydef);
16778 10156 : free(ftoptions);
16779 10156 : free(srvname);
16780 : }
16781 :
16782 : /*
16783 : * dump properties we only have ALTER TABLE syntax for
16784 : */
16785 11170 : if ((tbinfo->relkind == RELKIND_RELATION ||
16786 2794 : tbinfo->relkind == RELKIND_PARTITIONED_TABLE ||
16787 1758 : tbinfo->relkind == RELKIND_MATVIEW) &&
16788 10086 : tbinfo->relreplident != REPLICA_IDENTITY_DEFAULT)
16789 : {
16790 384 : if (tbinfo->relreplident == REPLICA_IDENTITY_INDEX)
16791 : {
16792 : /* nothing to do, will be set when the index is dumped */
16793 : }
16794 384 : else if (tbinfo->relreplident == REPLICA_IDENTITY_NOTHING)
16795 : {
16796 384 : appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY NOTHING;\n",
16797 : qualrelname);
16798 : }
16799 0 : else if (tbinfo->relreplident == REPLICA_IDENTITY_FULL)
16800 : {
16801 0 : appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY FULL;\n",
16802 : qualrelname);
16803 : }
16804 : }
16805 :
16806 11170 : if (tbinfo->forcerowsec)
16807 10 : appendPQExpBuffer(q, "\nALTER TABLE ONLY %s FORCE ROW LEVEL SECURITY;\n",
16808 : qualrelname);
16809 :
16810 11170 : if (dopt->binary_upgrade)
16811 1522 : binary_upgrade_extension_member(q, &tbinfo->dobj,
16812 : reltypename, qrelname,
16813 1522 : tbinfo->dobj.namespace->dobj.name);
16814 :
16815 11170 : if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16816 : {
16817 11170 : char *tablespace = NULL;
16818 11170 : char *tableam = NULL;
16819 :
16820 : /*
16821 : * _selectTablespace() relies on tablespace-enabled objects in the
16822 : * default tablespace to have a tablespace of "" (empty string) versus
16823 : * non-tablespace-enabled objects to have a tablespace of NULL.
16824 : * getTables() sets tbinfo->reltablespace to "" for the default
16825 : * tablespace (not NULL).
16826 : */
16827 11170 : if (RELKIND_HAS_TABLESPACE(tbinfo->relkind))
16828 10086 : tablespace = tbinfo->reltablespace;
16829 :
16830 11170 : if (RELKIND_HAS_TABLE_AM(tbinfo->relkind) ||
16831 2120 : tbinfo->relkind == RELKIND_PARTITIONED_TABLE)
16832 10086 : tableam = tbinfo->amname;
16833 :
16834 11170 : ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
16835 11170 : ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
16836 : .namespace = tbinfo->dobj.namespace->dobj.name,
16837 : .tablespace = tablespace,
16838 : .tableam = tableam,
16839 : .relkind = tbinfo->relkind,
16840 : .owner = tbinfo->rolname,
16841 : .description = reltypename,
16842 : .section = tbinfo->postponed_def ?
16843 : SECTION_POST_DATA : SECTION_PRE_DATA,
16844 : .createStmt = q->data,
16845 : .dropStmt = delq->data));
16846 : }
16847 :
16848 : /* Dump Table Comments */
16849 11170 : if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
16850 152 : dumpTableComment(fout, tbinfo, reltypename);
16851 :
16852 : /* Dump Table Security Labels */
16853 11170 : if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
16854 0 : dumpTableSecLabel(fout, tbinfo, reltypename);
16855 :
16856 : /* Dump comments on inlined table constraints */
16857 12246 : for (j = 0; j < tbinfo->ncheck; j++)
16858 : {
16859 1076 : ConstraintInfo *constr = &(tbinfo->checkexprs[j]);
16860 :
16861 1076 : if (constr->separate || !constr->conislocal)
16862 438 : continue;
16863 :
16864 638 : if (constr->dobj.dump & DUMP_COMPONENT_COMMENT)
16865 76 : dumpTableConstraintComment(fout, constr);
16866 : }
16867 :
16868 11170 : destroyPQExpBuffer(q);
16869 11170 : destroyPQExpBuffer(delq);
16870 11170 : destroyPQExpBuffer(extra);
16871 11170 : free(qrelname);
16872 11170 : free(qualrelname);
16873 11170 : }
16874 :
16875 : /*
16876 : * dumpTableAttach
16877 : * write to fout the commands to attach a child partition
16878 : *
16879 : * Child partitions are always made by creating them separately
16880 : * and then using ATTACH PARTITION, rather than using
16881 : * CREATE TABLE ... PARTITION OF. This is important for preserving
16882 : * any possible discrepancy in column layout, to allow assigning the
16883 : * correct tablespace if different, and so that it's possible to restore
16884 : * a partition without restoring its parent. (You'll get an error from
16885 : * the ATTACH PARTITION command, but that can be ignored, or skipped
16886 : * using "pg_restore -L" if you prefer.) The last point motivates
16887 : * treating ATTACH PARTITION as a completely separate ArchiveEntry
16888 : * rather than emitting it within the child partition's ArchiveEntry.
16889 : */
16890 : static void
16891 2496 : dumpTableAttach(Archive *fout, const TableAttachInfo *attachinfo)
16892 : {
16893 2496 : DumpOptions *dopt = fout->dopt;
16894 : PQExpBuffer q;
16895 : PGresult *res;
16896 : char *partbound;
16897 :
16898 : /* Do nothing in data-only dump */
16899 2496 : if (dopt->dataOnly)
16900 42 : return;
16901 :
16902 2454 : q = createPQExpBuffer();
16903 :
16904 2454 : if (!fout->is_prepared[PREPQUERY_DUMPTABLEATTACH])
16905 : {
16906 : /* Set up query for partbound details */
16907 88 : appendPQExpBufferStr(q,
16908 : "PREPARE dumpTableAttach(pg_catalog.oid) AS\n");
16909 :
16910 88 : appendPQExpBufferStr(q,
16911 : "SELECT pg_get_expr(c.relpartbound, c.oid) "
16912 : "FROM pg_class c "
16913 : "WHERE c.oid = $1");
16914 :
16915 88 : ExecuteSqlStatement(fout, q->data);
16916 :
16917 88 : fout->is_prepared[PREPQUERY_DUMPTABLEATTACH] = true;
16918 : }
16919 :
16920 2454 : printfPQExpBuffer(q,
16921 : "EXECUTE dumpTableAttach('%u')",
16922 2454 : attachinfo->partitionTbl->dobj.catId.oid);
16923 :
16924 2454 : res = ExecuteSqlQueryForSingleRow(fout, q->data);
16925 2454 : partbound = PQgetvalue(res, 0, 0);
16926 :
16927 : /* Perform ALTER TABLE on the parent */
16928 2454 : printfPQExpBuffer(q,
16929 : "ALTER TABLE ONLY %s ",
16930 2454 : fmtQualifiedDumpable(attachinfo->parentTbl));
16931 2454 : appendPQExpBuffer(q,
16932 : "ATTACH PARTITION %s %s;\n",
16933 2454 : fmtQualifiedDumpable(attachinfo->partitionTbl),
16934 : partbound);
16935 :
16936 : /*
16937 : * There is no point in creating a drop query as the drop is done by table
16938 : * drop. (If you think to change this, see also _printTocEntry().)
16939 : * Although this object doesn't really have ownership as such, set the
16940 : * owner field anyway to ensure that the command is run by the correct
16941 : * role at restore time.
16942 : */
16943 2454 : ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
16944 2454 : ARCHIVE_OPTS(.tag = attachinfo->dobj.name,
16945 : .namespace = attachinfo->dobj.namespace->dobj.name,
16946 : .owner = attachinfo->partitionTbl->rolname,
16947 : .description = "TABLE ATTACH",
16948 : .section = SECTION_PRE_DATA,
16949 : .createStmt = q->data));
16950 :
16951 2454 : PQclear(res);
16952 2454 : destroyPQExpBuffer(q);
16953 : }
16954 :
16955 : /*
16956 : * dumpAttrDef --- dump an attribute's default-value declaration
16957 : */
16958 : static void
16959 1520 : dumpAttrDef(Archive *fout, const AttrDefInfo *adinfo)
16960 : {
16961 1520 : DumpOptions *dopt = fout->dopt;
16962 1520 : TableInfo *tbinfo = adinfo->adtable;
16963 1520 : int adnum = adinfo->adnum;
16964 : PQExpBuffer q;
16965 : PQExpBuffer delq;
16966 : char *qualrelname;
16967 : char *tag;
16968 : char *foreign;
16969 :
16970 : /* Do nothing in data-only dump */
16971 1520 : if (dopt->dataOnly)
16972 0 : return;
16973 :
16974 : /* Skip if not "separate"; it was dumped in the table's definition */
16975 1520 : if (!adinfo->separate)
16976 1232 : return;
16977 :
16978 288 : q = createPQExpBuffer();
16979 288 : delq = createPQExpBuffer();
16980 :
16981 288 : qualrelname = pg_strdup(fmtQualifiedDumpable(tbinfo));
16982 :
16983 288 : foreign = tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "";
16984 :
16985 288 : appendPQExpBuffer(q,
16986 : "ALTER %sTABLE ONLY %s ALTER COLUMN %s SET DEFAULT %s;\n",
16987 288 : foreign, qualrelname, fmtId(tbinfo->attnames[adnum - 1]),
16988 : adinfo->adef_expr);
16989 :
16990 288 : appendPQExpBuffer(delq, "ALTER %sTABLE %s ALTER COLUMN %s DROP DEFAULT;\n",
16991 : foreign, qualrelname,
16992 288 : fmtId(tbinfo->attnames[adnum - 1]));
16993 :
16994 288 : tag = psprintf("%s %s", tbinfo->dobj.name, tbinfo->attnames[adnum - 1]);
16995 :
16996 288 : if (adinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
16997 288 : ArchiveEntry(fout, adinfo->dobj.catId, adinfo->dobj.dumpId,
16998 288 : ARCHIVE_OPTS(.tag = tag,
16999 : .namespace = tbinfo->dobj.namespace->dobj.name,
17000 : .owner = tbinfo->rolname,
17001 : .description = "DEFAULT",
17002 : .section = SECTION_PRE_DATA,
17003 : .createStmt = q->data,
17004 : .dropStmt = delq->data));
17005 :
17006 288 : free(tag);
17007 288 : destroyPQExpBuffer(q);
17008 288 : destroyPQExpBuffer(delq);
17009 288 : free(qualrelname);
17010 : }
17011 :
17012 : /*
17013 : * getAttrName: extract the correct name for an attribute
17014 : *
17015 : * The array tblInfo->attnames[] only provides names of user attributes;
17016 : * if a system attribute number is supplied, we have to fake it.
17017 : * We also do a little bit of bounds checking for safety's sake.
17018 : */
17019 : static const char *
17020 3916 : getAttrName(int attrnum, const TableInfo *tblInfo)
17021 : {
17022 3916 : if (attrnum > 0 && attrnum <= tblInfo->numatts)
17023 3916 : return tblInfo->attnames[attrnum - 1];
17024 0 : switch (attrnum)
17025 : {
17026 0 : case SelfItemPointerAttributeNumber:
17027 0 : return "ctid";
17028 0 : case MinTransactionIdAttributeNumber:
17029 0 : return "xmin";
17030 0 : case MinCommandIdAttributeNumber:
17031 0 : return "cmin";
17032 0 : case MaxTransactionIdAttributeNumber:
17033 0 : return "xmax";
17034 0 : case MaxCommandIdAttributeNumber:
17035 0 : return "cmax";
17036 0 : case TableOidAttributeNumber:
17037 0 : return "tableoid";
17038 : }
17039 0 : pg_fatal("invalid column number %d for table \"%s\"",
17040 : attrnum, tblInfo->dobj.name);
17041 : return NULL; /* keep compiler quiet */
17042 : }
17043 :
17044 : /*
17045 : * dumpIndex
17046 : * write out to fout a user-defined index
17047 : */
17048 : static void
17049 4740 : dumpIndex(Archive *fout, const IndxInfo *indxinfo)
17050 : {
17051 4740 : DumpOptions *dopt = fout->dopt;
17052 4740 : TableInfo *tbinfo = indxinfo->indextable;
17053 4740 : bool is_constraint = (indxinfo->indexconstraint != 0);
17054 : PQExpBuffer q;
17055 : PQExpBuffer delq;
17056 : char *qindxname;
17057 : char *qqindxname;
17058 :
17059 : /* Do nothing in data-only dump */
17060 4740 : if (dopt->dataOnly)
17061 114 : return;
17062 :
17063 4626 : q = createPQExpBuffer();
17064 4626 : delq = createPQExpBuffer();
17065 :
17066 4626 : qindxname = pg_strdup(fmtId(indxinfo->dobj.name));
17067 4626 : qqindxname = pg_strdup(fmtQualifiedDumpable(indxinfo));
17068 :
17069 : /*
17070 : * If there's an associated constraint, don't dump the index per se, but
17071 : * do dump any comment for it. (This is safe because dependency ordering
17072 : * will have ensured the constraint is emitted first.) Note that the
17073 : * emitted comment has to be shown as depending on the constraint, not the
17074 : * index, in such cases.
17075 : */
17076 4626 : if (!is_constraint)
17077 : {
17078 1958 : char *indstatcols = indxinfo->indstatcols;
17079 1958 : char *indstatvals = indxinfo->indstatvals;
17080 1958 : char **indstatcolsarray = NULL;
17081 1958 : char **indstatvalsarray = NULL;
17082 1958 : int nstatcols = 0;
17083 1958 : int nstatvals = 0;
17084 :
17085 1958 : if (dopt->binary_upgrade)
17086 298 : binary_upgrade_set_pg_class_oids(fout, q,
17087 : indxinfo->dobj.catId.oid);
17088 :
17089 : /* Plain secondary index */
17090 1958 : appendPQExpBuffer(q, "%s;\n", indxinfo->indexdef);
17091 :
17092 : /*
17093 : * Append ALTER TABLE commands as needed to set properties that we
17094 : * only have ALTER TABLE syntax for. Keep this in sync with the
17095 : * similar code in dumpConstraint!
17096 : */
17097 :
17098 : /* If the index is clustered, we need to record that. */
17099 1958 : if (indxinfo->indisclustered)
17100 : {
17101 0 : appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
17102 0 : fmtQualifiedDumpable(tbinfo));
17103 : /* index name is not qualified in this syntax */
17104 0 : appendPQExpBuffer(q, " ON %s;\n",
17105 : qindxname);
17106 : }
17107 :
17108 : /*
17109 : * If the index has any statistics on some of its columns, generate
17110 : * the associated ALTER INDEX queries.
17111 : */
17112 1958 : if (strlen(indstatcols) != 0 || strlen(indstatvals) != 0)
17113 : {
17114 : int j;
17115 :
17116 66 : if (!parsePGArray(indstatcols, &indstatcolsarray, &nstatcols))
17117 0 : pg_fatal("could not parse index statistic columns");
17118 66 : if (!parsePGArray(indstatvals, &indstatvalsarray, &nstatvals))
17119 0 : pg_fatal("could not parse index statistic values");
17120 66 : if (nstatcols != nstatvals)
17121 0 : pg_fatal("mismatched number of columns and values for index statistics");
17122 :
17123 198 : for (j = 0; j < nstatcols; j++)
17124 : {
17125 132 : appendPQExpBuffer(q, "ALTER INDEX %s ", qqindxname);
17126 :
17127 : /*
17128 : * Note that this is a column number, so no quotes should be
17129 : * used.
17130 : */
17131 132 : appendPQExpBuffer(q, "ALTER COLUMN %s ",
17132 132 : indstatcolsarray[j]);
17133 132 : appendPQExpBuffer(q, "SET STATISTICS %s;\n",
17134 132 : indstatvalsarray[j]);
17135 : }
17136 : }
17137 :
17138 : /* Indexes can depend on extensions */
17139 1958 : append_depends_on_extension(fout, q, &indxinfo->dobj,
17140 : "pg_catalog.pg_class",
17141 : "INDEX", qqindxname);
17142 :
17143 : /* If the index defines identity, we need to record that. */
17144 1958 : if (indxinfo->indisreplident)
17145 : {
17146 0 : appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
17147 0 : fmtQualifiedDumpable(tbinfo));
17148 : /* index name is not qualified in this syntax */
17149 0 : appendPQExpBuffer(q, " INDEX %s;\n",
17150 : qindxname);
17151 : }
17152 :
17153 1958 : appendPQExpBuffer(delq, "DROP INDEX %s;\n", qqindxname);
17154 :
17155 1958 : if (indxinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17156 1958 : ArchiveEntry(fout, indxinfo->dobj.catId, indxinfo->dobj.dumpId,
17157 1958 : ARCHIVE_OPTS(.tag = indxinfo->dobj.name,
17158 : .namespace = tbinfo->dobj.namespace->dobj.name,
17159 : .tablespace = indxinfo->tablespace,
17160 : .owner = tbinfo->rolname,
17161 : .description = "INDEX",
17162 : .section = SECTION_POST_DATA,
17163 : .createStmt = q->data,
17164 : .dropStmt = delq->data));
17165 :
17166 1958 : free(indstatcolsarray);
17167 1958 : free(indstatvalsarray);
17168 : }
17169 :
17170 : /* Dump Index Comments */
17171 4626 : if (indxinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17172 30 : dumpComment(fout, "INDEX", qindxname,
17173 30 : tbinfo->dobj.namespace->dobj.name,
17174 : tbinfo->rolname,
17175 : indxinfo->dobj.catId, 0,
17176 : is_constraint ? indxinfo->indexconstraint :
17177 : indxinfo->dobj.dumpId);
17178 :
17179 4626 : destroyPQExpBuffer(q);
17180 4626 : destroyPQExpBuffer(delq);
17181 4626 : free(qindxname);
17182 4626 : free(qqindxname);
17183 : }
17184 :
17185 : /*
17186 : * dumpIndexAttach
17187 : * write out to fout a partitioned-index attachment clause
17188 : */
17189 : static void
17190 1096 : dumpIndexAttach(Archive *fout, const IndexAttachInfo *attachinfo)
17191 : {
17192 : /* Do nothing in data-only dump */
17193 1096 : if (fout->dopt->dataOnly)
17194 48 : return;
17195 :
17196 1048 : if (attachinfo->partitionIdx->dobj.dump & DUMP_COMPONENT_DEFINITION)
17197 : {
17198 1048 : PQExpBuffer q = createPQExpBuffer();
17199 :
17200 1048 : appendPQExpBuffer(q, "ALTER INDEX %s ",
17201 1048 : fmtQualifiedDumpable(attachinfo->parentIdx));
17202 1048 : appendPQExpBuffer(q, "ATTACH PARTITION %s;\n",
17203 1048 : fmtQualifiedDumpable(attachinfo->partitionIdx));
17204 :
17205 : /*
17206 : * There is no point in creating a drop query as the drop is done by
17207 : * index drop. (If you think to change this, see also
17208 : * _printTocEntry().) Although this object doesn't really have
17209 : * ownership as such, set the owner field anyway to ensure that the
17210 : * command is run by the correct role at restore time.
17211 : */
17212 1048 : ArchiveEntry(fout, attachinfo->dobj.catId, attachinfo->dobj.dumpId,
17213 1048 : ARCHIVE_OPTS(.tag = attachinfo->dobj.name,
17214 : .namespace = attachinfo->dobj.namespace->dobj.name,
17215 : .owner = attachinfo->parentIdx->indextable->rolname,
17216 : .description = "INDEX ATTACH",
17217 : .section = SECTION_POST_DATA,
17218 : .createStmt = q->data));
17219 :
17220 1048 : destroyPQExpBuffer(q);
17221 : }
17222 : }
17223 :
17224 : /*
17225 : * dumpStatisticsExt
17226 : * write out to fout an extended statistics object
17227 : */
17228 : static void
17229 254 : dumpStatisticsExt(Archive *fout, const StatsExtInfo *statsextinfo)
17230 : {
17231 254 : DumpOptions *dopt = fout->dopt;
17232 : PQExpBuffer q;
17233 : PQExpBuffer delq;
17234 : PQExpBuffer query;
17235 : char *qstatsextname;
17236 : PGresult *res;
17237 : char *stxdef;
17238 :
17239 : /* Do nothing in data-only dump */
17240 254 : if (dopt->dataOnly)
17241 18 : return;
17242 :
17243 236 : q = createPQExpBuffer();
17244 236 : delq = createPQExpBuffer();
17245 236 : query = createPQExpBuffer();
17246 :
17247 236 : qstatsextname = pg_strdup(fmtId(statsextinfo->dobj.name));
17248 :
17249 236 : appendPQExpBuffer(query, "SELECT "
17250 : "pg_catalog.pg_get_statisticsobjdef('%u'::pg_catalog.oid)",
17251 : statsextinfo->dobj.catId.oid);
17252 :
17253 236 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
17254 :
17255 236 : stxdef = PQgetvalue(res, 0, 0);
17256 :
17257 : /* Result of pg_get_statisticsobjdef is complete except for semicolon */
17258 236 : appendPQExpBuffer(q, "%s;\n", stxdef);
17259 :
17260 : /*
17261 : * We only issue an ALTER STATISTICS statement if the stxstattarget entry
17262 : * for this statistics object is not the default value.
17263 : */
17264 236 : if (statsextinfo->stattarget >= 0)
17265 : {
17266 66 : appendPQExpBuffer(q, "ALTER STATISTICS %s ",
17267 66 : fmtQualifiedDumpable(statsextinfo));
17268 66 : appendPQExpBuffer(q, "SET STATISTICS %d;\n",
17269 : statsextinfo->stattarget);
17270 : }
17271 :
17272 236 : appendPQExpBuffer(delq, "DROP STATISTICS %s;\n",
17273 236 : fmtQualifiedDumpable(statsextinfo));
17274 :
17275 236 : if (statsextinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17276 236 : ArchiveEntry(fout, statsextinfo->dobj.catId,
17277 : statsextinfo->dobj.dumpId,
17278 236 : ARCHIVE_OPTS(.tag = statsextinfo->dobj.name,
17279 : .namespace = statsextinfo->dobj.namespace->dobj.name,
17280 : .owner = statsextinfo->rolname,
17281 : .description = "STATISTICS",
17282 : .section = SECTION_POST_DATA,
17283 : .createStmt = q->data,
17284 : .dropStmt = delq->data));
17285 :
17286 : /* Dump Statistics Comments */
17287 236 : if (statsextinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17288 0 : dumpComment(fout, "STATISTICS", qstatsextname,
17289 0 : statsextinfo->dobj.namespace->dobj.name,
17290 : statsextinfo->rolname,
17291 : statsextinfo->dobj.catId, 0,
17292 : statsextinfo->dobj.dumpId);
17293 :
17294 236 : PQclear(res);
17295 236 : destroyPQExpBuffer(q);
17296 236 : destroyPQExpBuffer(delq);
17297 236 : destroyPQExpBuffer(query);
17298 236 : free(qstatsextname);
17299 : }
17300 :
17301 : /*
17302 : * dumpConstraint
17303 : * write out to fout a user-defined constraint
17304 : */
17305 : static void
17306 4346 : dumpConstraint(Archive *fout, const ConstraintInfo *coninfo)
17307 : {
17308 4346 : DumpOptions *dopt = fout->dopt;
17309 4346 : TableInfo *tbinfo = coninfo->contable;
17310 : PQExpBuffer q;
17311 : PQExpBuffer delq;
17312 4346 : char *tag = NULL;
17313 : char *foreign;
17314 :
17315 : /* Do nothing in data-only dump */
17316 4346 : if (dopt->dataOnly)
17317 94 : return;
17318 :
17319 4252 : q = createPQExpBuffer();
17320 4252 : delq = createPQExpBuffer();
17321 :
17322 8328 : foreign = tbinfo &&
17323 4252 : tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "";
17324 :
17325 4252 : if (coninfo->contype == 'p' ||
17326 2044 : coninfo->contype == 'u' ||
17327 1604 : coninfo->contype == 'x')
17328 2668 : {
17329 : /* Index-related constraint */
17330 : IndxInfo *indxinfo;
17331 : int k;
17332 :
17333 2668 : indxinfo = (IndxInfo *) findObjectByDumpId(coninfo->conindex);
17334 :
17335 2668 : if (indxinfo == NULL)
17336 0 : pg_fatal("missing index for constraint \"%s\"",
17337 : coninfo->dobj.name);
17338 :
17339 2668 : if (dopt->binary_upgrade)
17340 252 : binary_upgrade_set_pg_class_oids(fout, q,
17341 : indxinfo->dobj.catId.oid);
17342 :
17343 2668 : appendPQExpBuffer(q, "ALTER %sTABLE ONLY %s\n", foreign,
17344 2668 : fmtQualifiedDumpable(tbinfo));
17345 2668 : appendPQExpBuffer(q, " ADD CONSTRAINT %s ",
17346 2668 : fmtId(coninfo->dobj.name));
17347 :
17348 2668 : if (coninfo->condef)
17349 : {
17350 : /* pg_get_constraintdef should have provided everything */
17351 20 : appendPQExpBuffer(q, "%s;\n", coninfo->condef);
17352 : }
17353 : else
17354 : {
17355 2648 : appendPQExpBufferStr(q,
17356 2648 : coninfo->contype == 'p' ? "PRIMARY KEY" : "UNIQUE");
17357 :
17358 : /*
17359 : * PRIMARY KEY constraints should not be using NULLS NOT DISTINCT
17360 : * indexes. Being able to create this was fixed, but we need to
17361 : * make the index distinct in order to be able to restore the
17362 : * dump.
17363 : */
17364 2648 : if (indxinfo->indnullsnotdistinct && coninfo->contype != 'p')
17365 0 : appendPQExpBufferStr(q, " NULLS NOT DISTINCT");
17366 2648 : appendPQExpBufferStr(q, " (");
17367 6484 : for (k = 0; k < indxinfo->indnkeyattrs; k++)
17368 : {
17369 3836 : int indkey = (int) indxinfo->indkeys[k];
17370 : const char *attname;
17371 :
17372 3836 : if (indkey == InvalidAttrNumber)
17373 0 : break;
17374 3836 : attname = getAttrName(indkey, tbinfo);
17375 :
17376 3836 : appendPQExpBuffer(q, "%s%s",
17377 : (k == 0) ? "" : ", ",
17378 : fmtId(attname));
17379 : }
17380 2648 : if (coninfo->conperiod)
17381 212 : appendPQExpBufferStr(q, " WITHOUT OVERLAPS");
17382 :
17383 2648 : if (indxinfo->indnkeyattrs < indxinfo->indnattrs)
17384 40 : appendPQExpBufferStr(q, ") INCLUDE (");
17385 :
17386 2728 : for (k = indxinfo->indnkeyattrs; k < indxinfo->indnattrs; k++)
17387 : {
17388 80 : int indkey = (int) indxinfo->indkeys[k];
17389 : const char *attname;
17390 :
17391 80 : if (indkey == InvalidAttrNumber)
17392 0 : break;
17393 80 : attname = getAttrName(indkey, tbinfo);
17394 :
17395 160 : appendPQExpBuffer(q, "%s%s",
17396 80 : (k == indxinfo->indnkeyattrs) ? "" : ", ",
17397 : fmtId(attname));
17398 : }
17399 :
17400 2648 : appendPQExpBufferChar(q, ')');
17401 :
17402 2648 : if (nonemptyReloptions(indxinfo->indreloptions))
17403 : {
17404 0 : appendPQExpBufferStr(q, " WITH (");
17405 0 : appendReloptionsArrayAH(q, indxinfo->indreloptions, "", fout);
17406 0 : appendPQExpBufferChar(q, ')');
17407 : }
17408 :
17409 2648 : if (coninfo->condeferrable)
17410 : {
17411 50 : appendPQExpBufferStr(q, " DEFERRABLE");
17412 50 : if (coninfo->condeferred)
17413 30 : appendPQExpBufferStr(q, " INITIALLY DEFERRED");
17414 : }
17415 :
17416 2648 : appendPQExpBufferStr(q, ";\n");
17417 : }
17418 :
17419 : /*
17420 : * Append ALTER TABLE commands as needed to set properties that we
17421 : * only have ALTER TABLE syntax for. Keep this in sync with the
17422 : * similar code in dumpIndex!
17423 : */
17424 :
17425 : /* If the index is clustered, we need to record that. */
17426 2668 : if (indxinfo->indisclustered)
17427 : {
17428 66 : appendPQExpBuffer(q, "\nALTER TABLE %s CLUSTER",
17429 66 : fmtQualifiedDumpable(tbinfo));
17430 : /* index name is not qualified in this syntax */
17431 66 : appendPQExpBuffer(q, " ON %s;\n",
17432 66 : fmtId(indxinfo->dobj.name));
17433 : }
17434 :
17435 : /* If the index defines identity, we need to record that. */
17436 2668 : if (indxinfo->indisreplident)
17437 : {
17438 0 : appendPQExpBuffer(q, "\nALTER TABLE ONLY %s REPLICA IDENTITY USING",
17439 0 : fmtQualifiedDumpable(tbinfo));
17440 : /* index name is not qualified in this syntax */
17441 0 : appendPQExpBuffer(q, " INDEX %s;\n",
17442 0 : fmtId(indxinfo->dobj.name));
17443 : }
17444 :
17445 : /* Indexes can depend on extensions */
17446 2668 : append_depends_on_extension(fout, q, &indxinfo->dobj,
17447 : "pg_catalog.pg_class", "INDEX",
17448 2668 : fmtQualifiedDumpable(indxinfo));
17449 :
17450 2668 : appendPQExpBuffer(delq, "ALTER %sTABLE ONLY %s ", foreign,
17451 2668 : fmtQualifiedDumpable(tbinfo));
17452 2668 : appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17453 2668 : fmtId(coninfo->dobj.name));
17454 :
17455 2668 : tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17456 :
17457 2668 : if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17458 2668 : ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17459 2668 : ARCHIVE_OPTS(.tag = tag,
17460 : .namespace = tbinfo->dobj.namespace->dobj.name,
17461 : .tablespace = indxinfo->tablespace,
17462 : .owner = tbinfo->rolname,
17463 : .description = "CONSTRAINT",
17464 : .section = SECTION_POST_DATA,
17465 : .createStmt = q->data,
17466 : .dropStmt = delq->data));
17467 : }
17468 1584 : else if (coninfo->contype == 'f')
17469 : {
17470 : char *only;
17471 :
17472 : /*
17473 : * Foreign keys on partitioned tables are always declared as
17474 : * inheriting to partitions; for all other cases, emit them as
17475 : * applying ONLY directly to the named table, because that's how they
17476 : * work for regular inherited tables.
17477 : */
17478 332 : only = tbinfo->relkind == RELKIND_PARTITIONED_TABLE ? "" : "ONLY ";
17479 :
17480 : /*
17481 : * XXX Potentially wrap in a 'SET CONSTRAINTS OFF' block so that the
17482 : * current table data is not processed
17483 : */
17484 332 : appendPQExpBuffer(q, "ALTER %sTABLE %s%s\n", foreign,
17485 332 : only, fmtQualifiedDumpable(tbinfo));
17486 332 : appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17487 332 : fmtId(coninfo->dobj.name),
17488 : coninfo->condef);
17489 :
17490 332 : appendPQExpBuffer(delq, "ALTER %sTABLE %s%s ", foreign,
17491 332 : only, fmtQualifiedDumpable(tbinfo));
17492 332 : appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17493 332 : fmtId(coninfo->dobj.name));
17494 :
17495 332 : tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17496 :
17497 332 : if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17498 332 : ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17499 332 : ARCHIVE_OPTS(.tag = tag,
17500 : .namespace = tbinfo->dobj.namespace->dobj.name,
17501 : .owner = tbinfo->rolname,
17502 : .description = "FK CONSTRAINT",
17503 : .section = SECTION_POST_DATA,
17504 : .createStmt = q->data,
17505 : .dropStmt = delq->data));
17506 : }
17507 1252 : else if (coninfo->contype == 'c' && tbinfo)
17508 : {
17509 : /* CHECK constraint on a table */
17510 :
17511 : /* Ignore if not to be dumped separately, or if it was inherited */
17512 1076 : if (coninfo->separate && coninfo->conislocal)
17513 : {
17514 : /* not ONLY since we want it to propagate to children */
17515 50 : appendPQExpBuffer(q, "ALTER %sTABLE %s\n", foreign,
17516 50 : fmtQualifiedDumpable(tbinfo));
17517 50 : appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17518 50 : fmtId(coninfo->dobj.name),
17519 : coninfo->condef);
17520 :
17521 50 : appendPQExpBuffer(delq, "ALTER %sTABLE %s ", foreign,
17522 50 : fmtQualifiedDumpable(tbinfo));
17523 50 : appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17524 50 : fmtId(coninfo->dobj.name));
17525 :
17526 50 : tag = psprintf("%s %s", tbinfo->dobj.name, coninfo->dobj.name);
17527 :
17528 50 : if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17529 50 : ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17530 50 : ARCHIVE_OPTS(.tag = tag,
17531 : .namespace = tbinfo->dobj.namespace->dobj.name,
17532 : .owner = tbinfo->rolname,
17533 : .description = "CHECK CONSTRAINT",
17534 : .section = SECTION_POST_DATA,
17535 : .createStmt = q->data,
17536 : .dropStmt = delq->data));
17537 : }
17538 : }
17539 176 : else if (coninfo->contype == 'c' && tbinfo == NULL)
17540 176 : {
17541 : /* CHECK constraint on a domain */
17542 176 : TypeInfo *tyinfo = coninfo->condomain;
17543 :
17544 : /* Ignore if not to be dumped separately */
17545 176 : if (coninfo->separate)
17546 : {
17547 0 : appendPQExpBuffer(q, "ALTER DOMAIN %s\n",
17548 0 : fmtQualifiedDumpable(tyinfo));
17549 0 : appendPQExpBuffer(q, " ADD CONSTRAINT %s %s;\n",
17550 0 : fmtId(coninfo->dobj.name),
17551 : coninfo->condef);
17552 :
17553 0 : appendPQExpBuffer(delq, "ALTER DOMAIN %s ",
17554 0 : fmtQualifiedDumpable(tyinfo));
17555 0 : appendPQExpBuffer(delq, "DROP CONSTRAINT %s;\n",
17556 0 : fmtId(coninfo->dobj.name));
17557 :
17558 0 : tag = psprintf("%s %s", tyinfo->dobj.name, coninfo->dobj.name);
17559 :
17560 0 : if (coninfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17561 0 : ArchiveEntry(fout, coninfo->dobj.catId, coninfo->dobj.dumpId,
17562 0 : ARCHIVE_OPTS(.tag = tag,
17563 : .namespace = tyinfo->dobj.namespace->dobj.name,
17564 : .owner = tyinfo->rolname,
17565 : .description = "CHECK CONSTRAINT",
17566 : .section = SECTION_POST_DATA,
17567 : .createStmt = q->data,
17568 : .dropStmt = delq->data));
17569 : }
17570 : }
17571 : else
17572 : {
17573 0 : pg_fatal("unrecognized constraint type: %c",
17574 : coninfo->contype);
17575 : }
17576 :
17577 : /* Dump Constraint Comments --- only works for table constraints */
17578 4252 : if (tbinfo && coninfo->separate &&
17579 3080 : coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17580 20 : dumpTableConstraintComment(fout, coninfo);
17581 :
17582 4252 : free(tag);
17583 4252 : destroyPQExpBuffer(q);
17584 4252 : destroyPQExpBuffer(delq);
17585 : }
17586 :
17587 : /*
17588 : * dumpTableConstraintComment --- dump a constraint's comment if any
17589 : *
17590 : * This is split out because we need the function in two different places
17591 : * depending on whether the constraint is dumped as part of CREATE TABLE
17592 : * or as a separate ALTER command.
17593 : */
17594 : static void
17595 96 : dumpTableConstraintComment(Archive *fout, const ConstraintInfo *coninfo)
17596 : {
17597 96 : TableInfo *tbinfo = coninfo->contable;
17598 96 : PQExpBuffer conprefix = createPQExpBuffer();
17599 : char *qtabname;
17600 :
17601 96 : qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
17602 :
17603 96 : appendPQExpBuffer(conprefix, "CONSTRAINT %s ON",
17604 96 : fmtId(coninfo->dobj.name));
17605 :
17606 96 : if (coninfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17607 96 : dumpComment(fout, conprefix->data, qtabname,
17608 96 : tbinfo->dobj.namespace->dobj.name,
17609 : tbinfo->rolname,
17610 : coninfo->dobj.catId, 0,
17611 96 : coninfo->separate ? coninfo->dobj.dumpId : tbinfo->dobj.dumpId);
17612 :
17613 96 : destroyPQExpBuffer(conprefix);
17614 96 : free(qtabname);
17615 96 : }
17616 :
17617 : static inline SeqType
17618 1184 : parse_sequence_type(const char *name)
17619 : {
17620 2656 : for (int i = 0; i < lengthof(SeqTypeNames); i++)
17621 : {
17622 2656 : if (strcmp(SeqTypeNames[i], name) == 0)
17623 1184 : return (SeqType) i;
17624 : }
17625 :
17626 0 : pg_fatal("unrecognized sequence type: %s", name);
17627 : return (SeqType) 0; /* keep compiler quiet */
17628 : }
17629 :
17630 : /*
17631 : * bsearch() comparator for SequenceItem
17632 : */
17633 : static int
17634 5338 : SequenceItemCmp(const void *p1, const void *p2)
17635 : {
17636 5338 : SequenceItem v1 = *((const SequenceItem *) p1);
17637 5338 : SequenceItem v2 = *((const SequenceItem *) p2);
17638 :
17639 5338 : return pg_cmp_u32(v1.oid, v2.oid);
17640 : }
17641 :
17642 : /*
17643 : * collectSequences
17644 : *
17645 : * Construct a table of sequence information. This table is sorted by OID for
17646 : * speed in lookup.
17647 : */
17648 : static void
17649 308 : collectSequences(Archive *fout)
17650 : {
17651 : PGresult *res;
17652 : const char *query;
17653 :
17654 : /*
17655 : * Before Postgres 10, sequence metadata is in the sequence itself. With
17656 : * some extra effort, we might be able to use the sorted table for those
17657 : * versions, but for now it seems unlikely to be worth it.
17658 : *
17659 : * Since version 18, we can gather the sequence data in this query with
17660 : * pg_get_sequence_data(), but we only do so for non-schema-only dumps.
17661 : */
17662 308 : if (fout->remoteVersion < 100000)
17663 0 : return;
17664 308 : else if (fout->remoteVersion < 180000 ||
17665 308 : (fout->dopt->schemaOnly && !fout->dopt->sequence_data))
17666 4 : query = "SELECT seqrelid, format_type(seqtypid, NULL), "
17667 : "seqstart, seqincrement, "
17668 : "seqmax, seqmin, "
17669 : "seqcache, seqcycle, "
17670 : "NULL, 'f' "
17671 : "FROM pg_catalog.pg_sequence "
17672 : "ORDER BY seqrelid";
17673 : else
17674 304 : query = "SELECT seqrelid, format_type(seqtypid, NULL), "
17675 : "seqstart, seqincrement, "
17676 : "seqmax, seqmin, "
17677 : "seqcache, seqcycle, "
17678 : "last_value, is_called "
17679 : "FROM pg_catalog.pg_sequence, "
17680 : "pg_get_sequence_data(seqrelid) "
17681 : "ORDER BY seqrelid;";
17682 :
17683 308 : res = ExecuteSqlQuery(fout, query, PGRES_TUPLES_OK);
17684 :
17685 308 : nsequences = PQntuples(res);
17686 308 : sequences = (SequenceItem *) pg_malloc(nsequences * sizeof(SequenceItem));
17687 :
17688 1492 : for (int i = 0; i < nsequences; i++)
17689 : {
17690 1184 : sequences[i].oid = atooid(PQgetvalue(res, i, 0));
17691 1184 : sequences[i].seqtype = parse_sequence_type(PQgetvalue(res, i, 1));
17692 1184 : sequences[i].startv = strtoi64(PQgetvalue(res, i, 2), NULL, 10);
17693 1184 : sequences[i].incby = strtoi64(PQgetvalue(res, i, 3), NULL, 10);
17694 1184 : sequences[i].maxv = strtoi64(PQgetvalue(res, i, 4), NULL, 10);
17695 1184 : sequences[i].minv = strtoi64(PQgetvalue(res, i, 5), NULL, 10);
17696 1184 : sequences[i].cache = strtoi64(PQgetvalue(res, i, 6), NULL, 10);
17697 1184 : sequences[i].cycled = (strcmp(PQgetvalue(res, i, 7), "t") == 0);
17698 1184 : sequences[i].last_value = strtoi64(PQgetvalue(res, i, 8), NULL, 10);
17699 1184 : sequences[i].is_called = (strcmp(PQgetvalue(res, i, 9), "t") == 0);
17700 : }
17701 :
17702 308 : PQclear(res);
17703 : }
17704 :
17705 : /*
17706 : * dumpSequence
17707 : * write the declaration (not data) of one user-defined sequence
17708 : */
17709 : static void
17710 696 : dumpSequence(Archive *fout, const TableInfo *tbinfo)
17711 : {
17712 696 : DumpOptions *dopt = fout->dopt;
17713 : SequenceItem *seq;
17714 : bool is_ascending;
17715 : int64 default_minv,
17716 : default_maxv;
17717 696 : PQExpBuffer query = createPQExpBuffer();
17718 696 : PQExpBuffer delqry = createPQExpBuffer();
17719 : char *qseqname;
17720 696 : TableInfo *owning_tab = NULL;
17721 :
17722 696 : qseqname = pg_strdup(fmtId(tbinfo->dobj.name));
17723 :
17724 : /*
17725 : * For versions >= 10, the sequence information is gathered in a sorted
17726 : * table before any calls to dumpSequence(). See collectSequences() for
17727 : * more information.
17728 : */
17729 696 : if (fout->remoteVersion >= 100000)
17730 : {
17731 696 : SequenceItem key = {0};
17732 :
17733 : Assert(sequences);
17734 :
17735 696 : key.oid = tbinfo->dobj.catId.oid;
17736 696 : seq = bsearch(&key, sequences, nsequences,
17737 : sizeof(SequenceItem), SequenceItemCmp);
17738 : }
17739 : else
17740 : {
17741 : PGresult *res;
17742 :
17743 : /*
17744 : * Before PostgreSQL 10, sequence metadata is in the sequence itself.
17745 : *
17746 : * Note: it might seem that 'bigint' potentially needs to be
17747 : * schema-qualified, but actually that's a keyword.
17748 : */
17749 0 : appendPQExpBuffer(query,
17750 : "SELECT 'bigint' AS sequence_type, "
17751 : "start_value, increment_by, max_value, min_value, "
17752 : "cache_value, is_cycled FROM %s",
17753 0 : fmtQualifiedDumpable(tbinfo));
17754 :
17755 0 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17756 :
17757 0 : if (PQntuples(res) != 1)
17758 0 : pg_fatal(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17759 : "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17760 : PQntuples(res)),
17761 : tbinfo->dobj.name, PQntuples(res));
17762 :
17763 0 : seq = pg_malloc0(sizeof(SequenceItem));
17764 0 : seq->seqtype = parse_sequence_type(PQgetvalue(res, 0, 0));
17765 0 : seq->startv = strtoi64(PQgetvalue(res, 0, 1), NULL, 10);
17766 0 : seq->incby = strtoi64(PQgetvalue(res, 0, 2), NULL, 10);
17767 0 : seq->maxv = strtoi64(PQgetvalue(res, 0, 3), NULL, 10);
17768 0 : seq->minv = strtoi64(PQgetvalue(res, 0, 4), NULL, 10);
17769 0 : seq->cache = strtoi64(PQgetvalue(res, 0, 5), NULL, 10);
17770 0 : seq->cycled = (strcmp(PQgetvalue(res, 0, 6), "t") == 0);
17771 :
17772 0 : PQclear(res);
17773 : }
17774 :
17775 : /* Calculate default limits for a sequence of this type */
17776 696 : is_ascending = (seq->incby >= 0);
17777 696 : if (seq->seqtype == SEQTYPE_SMALLINT)
17778 : {
17779 50 : default_minv = is_ascending ? 1 : PG_INT16_MIN;
17780 50 : default_maxv = is_ascending ? PG_INT16_MAX : -1;
17781 : }
17782 646 : else if (seq->seqtype == SEQTYPE_INTEGER)
17783 : {
17784 524 : default_minv = is_ascending ? 1 : PG_INT32_MIN;
17785 524 : default_maxv = is_ascending ? PG_INT32_MAX : -1;
17786 : }
17787 122 : else if (seq->seqtype == SEQTYPE_BIGINT)
17788 : {
17789 122 : default_minv = is_ascending ? 1 : PG_INT64_MIN;
17790 122 : default_maxv = is_ascending ? PG_INT64_MAX : -1;
17791 : }
17792 : else
17793 : {
17794 0 : pg_fatal("unrecognized sequence type: %d", seq->seqtype);
17795 : default_minv = default_maxv = 0; /* keep compiler quiet */
17796 : }
17797 :
17798 : /*
17799 : * Identity sequences are not to be dropped separately.
17800 : */
17801 696 : if (!tbinfo->is_identity_sequence)
17802 : {
17803 410 : appendPQExpBuffer(delqry, "DROP SEQUENCE %s;\n",
17804 410 : fmtQualifiedDumpable(tbinfo));
17805 : }
17806 :
17807 696 : resetPQExpBuffer(query);
17808 :
17809 696 : if (dopt->binary_upgrade)
17810 : {
17811 112 : binary_upgrade_set_pg_class_oids(fout, query,
17812 : tbinfo->dobj.catId.oid);
17813 :
17814 : /*
17815 : * In older PG versions a sequence will have a pg_type entry, but v14
17816 : * and up don't use that, so don't attempt to preserve the type OID.
17817 : */
17818 : }
17819 :
17820 696 : if (tbinfo->is_identity_sequence)
17821 : {
17822 286 : owning_tab = findTableByOid(tbinfo->owning_tab);
17823 :
17824 286 : appendPQExpBuffer(query,
17825 : "ALTER TABLE %s ",
17826 286 : fmtQualifiedDumpable(owning_tab));
17827 286 : appendPQExpBuffer(query,
17828 : "ALTER COLUMN %s ADD GENERATED ",
17829 286 : fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17830 286 : if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_ALWAYS)
17831 206 : appendPQExpBufferStr(query, "ALWAYS");
17832 80 : else if (owning_tab->attidentity[tbinfo->owning_col - 1] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
17833 80 : appendPQExpBufferStr(query, "BY DEFAULT");
17834 286 : appendPQExpBuffer(query, " AS IDENTITY (\n SEQUENCE NAME %s\n",
17835 286 : fmtQualifiedDumpable(tbinfo));
17836 :
17837 : /*
17838 : * Emit persistence option only if it's different from the owning
17839 : * table's. This avoids using this new syntax unnecessarily.
17840 : */
17841 286 : if (tbinfo->relpersistence != owning_tab->relpersistence)
17842 20 : appendPQExpBuffer(query, " %s\n",
17843 20 : tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
17844 : "UNLOGGED" : "LOGGED");
17845 : }
17846 : else
17847 : {
17848 410 : appendPQExpBuffer(query,
17849 : "CREATE %sSEQUENCE %s\n",
17850 410 : tbinfo->relpersistence == RELPERSISTENCE_UNLOGGED ?
17851 : "UNLOGGED " : "",
17852 410 : fmtQualifiedDumpable(tbinfo));
17853 :
17854 410 : if (seq->seqtype != SEQTYPE_BIGINT)
17855 318 : appendPQExpBuffer(query, " AS %s\n", SeqTypeNames[seq->seqtype]);
17856 : }
17857 :
17858 696 : appendPQExpBuffer(query, " START WITH " INT64_FORMAT "\n", seq->startv);
17859 :
17860 696 : appendPQExpBuffer(query, " INCREMENT BY " INT64_FORMAT "\n", seq->incby);
17861 :
17862 696 : if (seq->minv != default_minv)
17863 30 : appendPQExpBuffer(query, " MINVALUE " INT64_FORMAT "\n", seq->minv);
17864 : else
17865 666 : appendPQExpBufferStr(query, " NO MINVALUE\n");
17866 :
17867 696 : if (seq->maxv != default_maxv)
17868 30 : appendPQExpBuffer(query, " MAXVALUE " INT64_FORMAT "\n", seq->maxv);
17869 : else
17870 666 : appendPQExpBufferStr(query, " NO MAXVALUE\n");
17871 :
17872 696 : appendPQExpBuffer(query,
17873 : " CACHE " INT64_FORMAT "%s",
17874 696 : seq->cache, (seq->cycled ? "\n CYCLE" : ""));
17875 :
17876 696 : if (tbinfo->is_identity_sequence)
17877 286 : appendPQExpBufferStr(query, "\n);\n");
17878 : else
17879 410 : appendPQExpBufferStr(query, ";\n");
17880 :
17881 : /* binary_upgrade: no need to clear TOAST table oid */
17882 :
17883 696 : if (dopt->binary_upgrade)
17884 112 : binary_upgrade_extension_member(query, &tbinfo->dobj,
17885 : "SEQUENCE", qseqname,
17886 112 : tbinfo->dobj.namespace->dobj.name);
17887 :
17888 696 : if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17889 696 : ArchiveEntry(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId,
17890 696 : ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17891 : .namespace = tbinfo->dobj.namespace->dobj.name,
17892 : .owner = tbinfo->rolname,
17893 : .description = "SEQUENCE",
17894 : .section = SECTION_PRE_DATA,
17895 : .createStmt = query->data,
17896 : .dropStmt = delqry->data));
17897 :
17898 : /*
17899 : * If the sequence is owned by a table column, emit the ALTER for it as a
17900 : * separate TOC entry immediately following the sequence's own entry. It's
17901 : * OK to do this rather than using full sorting logic, because the
17902 : * dependency that tells us it's owned will have forced the table to be
17903 : * created first. We can't just include the ALTER in the TOC entry
17904 : * because it will fail if we haven't reassigned the sequence owner to
17905 : * match the table's owner.
17906 : *
17907 : * We need not schema-qualify the table reference because both sequence
17908 : * and table must be in the same schema.
17909 : */
17910 696 : if (OidIsValid(tbinfo->owning_tab) && !tbinfo->is_identity_sequence)
17911 : {
17912 228 : owning_tab = findTableByOid(tbinfo->owning_tab);
17913 :
17914 228 : if (owning_tab == NULL)
17915 0 : pg_fatal("failed sanity check, parent table with OID %u of sequence with OID %u not found",
17916 : tbinfo->owning_tab, tbinfo->dobj.catId.oid);
17917 :
17918 228 : if (owning_tab->dobj.dump & DUMP_COMPONENT_DEFINITION)
17919 : {
17920 224 : resetPQExpBuffer(query);
17921 224 : appendPQExpBuffer(query, "ALTER SEQUENCE %s",
17922 224 : fmtQualifiedDumpable(tbinfo));
17923 224 : appendPQExpBuffer(query, " OWNED BY %s",
17924 224 : fmtQualifiedDumpable(owning_tab));
17925 224 : appendPQExpBuffer(query, ".%s;\n",
17926 224 : fmtId(owning_tab->attnames[tbinfo->owning_col - 1]));
17927 :
17928 224 : if (tbinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
17929 224 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
17930 224 : ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
17931 : .namespace = tbinfo->dobj.namespace->dobj.name,
17932 : .owner = tbinfo->rolname,
17933 : .description = "SEQUENCE OWNED BY",
17934 : .section = SECTION_PRE_DATA,
17935 : .createStmt = query->data,
17936 : .deps = &(tbinfo->dobj.dumpId),
17937 : .nDeps = 1));
17938 : }
17939 : }
17940 :
17941 : /* Dump Sequence Comments and Security Labels */
17942 696 : if (tbinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
17943 0 : dumpComment(fout, "SEQUENCE", qseqname,
17944 0 : tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17945 : tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17946 :
17947 696 : if (tbinfo->dobj.dump & DUMP_COMPONENT_SECLABEL)
17948 0 : dumpSecLabel(fout, "SEQUENCE", qseqname,
17949 0 : tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
17950 : tbinfo->dobj.catId, 0, tbinfo->dobj.dumpId);
17951 :
17952 696 : if (fout->remoteVersion < 100000)
17953 0 : pg_free(seq);
17954 696 : destroyPQExpBuffer(query);
17955 696 : destroyPQExpBuffer(delqry);
17956 696 : free(qseqname);
17957 696 : }
17958 :
17959 : /*
17960 : * dumpSequenceData
17961 : * write the data of one user-defined sequence
17962 : */
17963 : static void
17964 728 : dumpSequenceData(Archive *fout, const TableDataInfo *tdinfo)
17965 : {
17966 728 : TableInfo *tbinfo = tdinfo->tdtable;
17967 : int64 last;
17968 : bool called;
17969 728 : PQExpBuffer query = createPQExpBuffer();
17970 :
17971 : /*
17972 : * For versions >= 18, the sequence information is gathered in the sorted
17973 : * array before any calls to dumpSequenceData(). See collectSequences()
17974 : * for more information.
17975 : *
17976 : * For older versions, we have to query the sequence relations
17977 : * individually.
17978 : */
17979 728 : if (fout->remoteVersion < 180000)
17980 : {
17981 : PGresult *res;
17982 :
17983 0 : appendPQExpBuffer(query,
17984 : "SELECT last_value, is_called FROM %s",
17985 0 : fmtQualifiedDumpable(tbinfo));
17986 :
17987 0 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
17988 :
17989 0 : if (PQntuples(res) != 1)
17990 0 : pg_fatal(ngettext("query to get data of sequence \"%s\" returned %d row (expected 1)",
17991 : "query to get data of sequence \"%s\" returned %d rows (expected 1)",
17992 : PQntuples(res)),
17993 : tbinfo->dobj.name, PQntuples(res));
17994 :
17995 0 : last = strtoi64(PQgetvalue(res, 0, 0), NULL, 10);
17996 0 : called = (strcmp(PQgetvalue(res, 0, 1), "t") == 0);
17997 :
17998 0 : PQclear(res);
17999 : }
18000 : else
18001 : {
18002 728 : SequenceItem key = {0};
18003 : SequenceItem *entry;
18004 :
18005 : Assert(sequences);
18006 : Assert(tbinfo->dobj.catId.oid);
18007 :
18008 728 : key.oid = tbinfo->dobj.catId.oid;
18009 728 : entry = bsearch(&key, sequences, nsequences,
18010 : sizeof(SequenceItem), SequenceItemCmp);
18011 :
18012 728 : last = entry->last_value;
18013 728 : called = entry->is_called;
18014 : }
18015 :
18016 728 : resetPQExpBuffer(query);
18017 728 : appendPQExpBufferStr(query, "SELECT pg_catalog.setval(");
18018 728 : appendStringLiteralAH(query, fmtQualifiedDumpable(tbinfo), fout);
18019 728 : appendPQExpBuffer(query, ", " INT64_FORMAT ", %s);\n",
18020 : last, (called ? "true" : "false"));
18021 :
18022 728 : if (tdinfo->dobj.dump & DUMP_COMPONENT_DATA)
18023 728 : ArchiveEntry(fout, nilCatalogId, createDumpId(),
18024 728 : ARCHIVE_OPTS(.tag = tbinfo->dobj.name,
18025 : .namespace = tbinfo->dobj.namespace->dobj.name,
18026 : .owner = tbinfo->rolname,
18027 : .description = "SEQUENCE SET",
18028 : .section = SECTION_DATA,
18029 : .createStmt = query->data,
18030 : .deps = &(tbinfo->dobj.dumpId),
18031 : .nDeps = 1));
18032 :
18033 728 : destroyPQExpBuffer(query);
18034 728 : }
18035 :
18036 : /*
18037 : * dumpTrigger
18038 : * write the declaration of one user-defined table trigger
18039 : */
18040 : static void
18041 986 : dumpTrigger(Archive *fout, const TriggerInfo *tginfo)
18042 : {
18043 986 : DumpOptions *dopt = fout->dopt;
18044 986 : TableInfo *tbinfo = tginfo->tgtable;
18045 : PQExpBuffer query;
18046 : PQExpBuffer delqry;
18047 : PQExpBuffer trigprefix;
18048 : PQExpBuffer trigidentity;
18049 : char *qtabname;
18050 : char *tag;
18051 :
18052 : /* Do nothing in data-only dump */
18053 986 : if (dopt->dataOnly)
18054 32 : return;
18055 :
18056 954 : query = createPQExpBuffer();
18057 954 : delqry = createPQExpBuffer();
18058 954 : trigprefix = createPQExpBuffer();
18059 954 : trigidentity = createPQExpBuffer();
18060 :
18061 954 : qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
18062 :
18063 954 : appendPQExpBuffer(trigidentity, "%s ", fmtId(tginfo->dobj.name));
18064 954 : appendPQExpBuffer(trigidentity, "ON %s", fmtQualifiedDumpable(tbinfo));
18065 :
18066 954 : appendPQExpBuffer(query, "%s;\n", tginfo->tgdef);
18067 954 : appendPQExpBuffer(delqry, "DROP TRIGGER %s;\n", trigidentity->data);
18068 :
18069 : /* Triggers can depend on extensions */
18070 954 : append_depends_on_extension(fout, query, &tginfo->dobj,
18071 : "pg_catalog.pg_trigger", "TRIGGER",
18072 954 : trigidentity->data);
18073 :
18074 954 : if (tginfo->tgispartition)
18075 : {
18076 : Assert(tbinfo->ispartition);
18077 :
18078 : /*
18079 : * Partition triggers only appear here because their 'tgenabled' flag
18080 : * differs from its parent's. The trigger is created already, so
18081 : * remove the CREATE and replace it with an ALTER. (Clear out the
18082 : * DROP query too, so that pg_dump --create does not cause errors.)
18083 : */
18084 224 : resetPQExpBuffer(query);
18085 224 : resetPQExpBuffer(delqry);
18086 224 : appendPQExpBuffer(query, "\nALTER %sTABLE %s ",
18087 224 : tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "",
18088 224 : fmtQualifiedDumpable(tbinfo));
18089 224 : switch (tginfo->tgenabled)
18090 : {
18091 78 : case 'f':
18092 : case 'D':
18093 78 : appendPQExpBufferStr(query, "DISABLE");
18094 78 : break;
18095 0 : case 't':
18096 : case 'O':
18097 0 : appendPQExpBufferStr(query, "ENABLE");
18098 0 : break;
18099 68 : case 'R':
18100 68 : appendPQExpBufferStr(query, "ENABLE REPLICA");
18101 68 : break;
18102 78 : case 'A':
18103 78 : appendPQExpBufferStr(query, "ENABLE ALWAYS");
18104 78 : break;
18105 : }
18106 224 : appendPQExpBuffer(query, " TRIGGER %s;\n",
18107 224 : fmtId(tginfo->dobj.name));
18108 : }
18109 730 : else if (tginfo->tgenabled != 't' && tginfo->tgenabled != 'O')
18110 : {
18111 0 : appendPQExpBuffer(query, "\nALTER %sTABLE %s ",
18112 0 : tbinfo->relkind == RELKIND_FOREIGN_TABLE ? "FOREIGN " : "",
18113 0 : fmtQualifiedDumpable(tbinfo));
18114 0 : switch (tginfo->tgenabled)
18115 : {
18116 0 : case 'D':
18117 : case 'f':
18118 0 : appendPQExpBufferStr(query, "DISABLE");
18119 0 : break;
18120 0 : case 'A':
18121 0 : appendPQExpBufferStr(query, "ENABLE ALWAYS");
18122 0 : break;
18123 0 : case 'R':
18124 0 : appendPQExpBufferStr(query, "ENABLE REPLICA");
18125 0 : break;
18126 0 : default:
18127 0 : appendPQExpBufferStr(query, "ENABLE");
18128 0 : break;
18129 : }
18130 0 : appendPQExpBuffer(query, " TRIGGER %s;\n",
18131 0 : fmtId(tginfo->dobj.name));
18132 : }
18133 :
18134 954 : appendPQExpBuffer(trigprefix, "TRIGGER %s ON",
18135 954 : fmtId(tginfo->dobj.name));
18136 :
18137 954 : tag = psprintf("%s %s", tbinfo->dobj.name, tginfo->dobj.name);
18138 :
18139 954 : if (tginfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
18140 954 : ArchiveEntry(fout, tginfo->dobj.catId, tginfo->dobj.dumpId,
18141 954 : ARCHIVE_OPTS(.tag = tag,
18142 : .namespace = tbinfo->dobj.namespace->dobj.name,
18143 : .owner = tbinfo->rolname,
18144 : .description = "TRIGGER",
18145 : .section = SECTION_POST_DATA,
18146 : .createStmt = query->data,
18147 : .dropStmt = delqry->data));
18148 :
18149 954 : if (tginfo->dobj.dump & DUMP_COMPONENT_COMMENT)
18150 0 : dumpComment(fout, trigprefix->data, qtabname,
18151 0 : tbinfo->dobj.namespace->dobj.name, tbinfo->rolname,
18152 : tginfo->dobj.catId, 0, tginfo->dobj.dumpId);
18153 :
18154 954 : free(tag);
18155 954 : destroyPQExpBuffer(query);
18156 954 : destroyPQExpBuffer(delqry);
18157 954 : destroyPQExpBuffer(trigprefix);
18158 954 : destroyPQExpBuffer(trigidentity);
18159 954 : free(qtabname);
18160 : }
18161 :
18162 : /*
18163 : * dumpEventTrigger
18164 : * write the declaration of one user-defined event trigger
18165 : */
18166 : static void
18167 80 : dumpEventTrigger(Archive *fout, const EventTriggerInfo *evtinfo)
18168 : {
18169 80 : DumpOptions *dopt = fout->dopt;
18170 : PQExpBuffer query;
18171 : PQExpBuffer delqry;
18172 : char *qevtname;
18173 :
18174 : /* Do nothing in data-only dump */
18175 80 : if (dopt->dataOnly)
18176 6 : return;
18177 :
18178 74 : query = createPQExpBuffer();
18179 74 : delqry = createPQExpBuffer();
18180 :
18181 74 : qevtname = pg_strdup(fmtId(evtinfo->dobj.name));
18182 :
18183 74 : appendPQExpBufferStr(query, "CREATE EVENT TRIGGER ");
18184 74 : appendPQExpBufferStr(query, qevtname);
18185 74 : appendPQExpBufferStr(query, " ON ");
18186 74 : appendPQExpBufferStr(query, fmtId(evtinfo->evtevent));
18187 :
18188 74 : if (strcmp("", evtinfo->evttags) != 0)
18189 : {
18190 10 : appendPQExpBufferStr(query, "\n WHEN TAG IN (");
18191 10 : appendPQExpBufferStr(query, evtinfo->evttags);
18192 10 : appendPQExpBufferChar(query, ')');
18193 : }
18194 :
18195 74 : appendPQExpBufferStr(query, "\n EXECUTE FUNCTION ");
18196 74 : appendPQExpBufferStr(query, evtinfo->evtfname);
18197 74 : appendPQExpBufferStr(query, "();\n");
18198 :
18199 74 : if (evtinfo->evtenabled != 'O')
18200 : {
18201 0 : appendPQExpBuffer(query, "\nALTER EVENT TRIGGER %s ",
18202 : qevtname);
18203 0 : switch (evtinfo->evtenabled)
18204 : {
18205 0 : case 'D':
18206 0 : appendPQExpBufferStr(query, "DISABLE");
18207 0 : break;
18208 0 : case 'A':
18209 0 : appendPQExpBufferStr(query, "ENABLE ALWAYS");
18210 0 : break;
18211 0 : case 'R':
18212 0 : appendPQExpBufferStr(query, "ENABLE REPLICA");
18213 0 : break;
18214 0 : default:
18215 0 : appendPQExpBufferStr(query, "ENABLE");
18216 0 : break;
18217 : }
18218 0 : appendPQExpBufferStr(query, ";\n");
18219 : }
18220 :
18221 74 : appendPQExpBuffer(delqry, "DROP EVENT TRIGGER %s;\n",
18222 : qevtname);
18223 :
18224 74 : if (dopt->binary_upgrade)
18225 4 : binary_upgrade_extension_member(query, &evtinfo->dobj,
18226 : "EVENT TRIGGER", qevtname, NULL);
18227 :
18228 74 : if (evtinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
18229 74 : ArchiveEntry(fout, evtinfo->dobj.catId, evtinfo->dobj.dumpId,
18230 74 : ARCHIVE_OPTS(.tag = evtinfo->dobj.name,
18231 : .owner = evtinfo->evtowner,
18232 : .description = "EVENT TRIGGER",
18233 : .section = SECTION_POST_DATA,
18234 : .createStmt = query->data,
18235 : .dropStmt = delqry->data));
18236 :
18237 74 : if (evtinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
18238 0 : dumpComment(fout, "EVENT TRIGGER", qevtname,
18239 : NULL, evtinfo->evtowner,
18240 : evtinfo->dobj.catId, 0, evtinfo->dobj.dumpId);
18241 :
18242 74 : destroyPQExpBuffer(query);
18243 74 : destroyPQExpBuffer(delqry);
18244 74 : free(qevtname);
18245 : }
18246 :
18247 : /*
18248 : * dumpRule
18249 : * Dump a rule
18250 : */
18251 : static void
18252 2150 : dumpRule(Archive *fout, const RuleInfo *rinfo)
18253 : {
18254 2150 : DumpOptions *dopt = fout->dopt;
18255 2150 : TableInfo *tbinfo = rinfo->ruletable;
18256 : bool is_view;
18257 : PQExpBuffer query;
18258 : PQExpBuffer cmd;
18259 : PQExpBuffer delcmd;
18260 : PQExpBuffer ruleprefix;
18261 : char *qtabname;
18262 : PGresult *res;
18263 : char *tag;
18264 :
18265 : /* Do nothing in data-only dump */
18266 2150 : if (dopt->dataOnly)
18267 60 : return;
18268 :
18269 : /*
18270 : * If it is an ON SELECT rule that is created implicitly by CREATE VIEW,
18271 : * we do not want to dump it as a separate object.
18272 : */
18273 2090 : if (!rinfo->separate)
18274 1668 : return;
18275 :
18276 : /*
18277 : * If it's an ON SELECT rule, we want to print it as a view definition,
18278 : * instead of a rule.
18279 : */
18280 422 : is_view = (rinfo->ev_type == '1' && rinfo->is_instead);
18281 :
18282 422 : query = createPQExpBuffer();
18283 422 : cmd = createPQExpBuffer();
18284 422 : delcmd = createPQExpBuffer();
18285 422 : ruleprefix = createPQExpBuffer();
18286 :
18287 422 : qtabname = pg_strdup(fmtId(tbinfo->dobj.name));
18288 :
18289 422 : if (is_view)
18290 : {
18291 : PQExpBuffer result;
18292 :
18293 : /*
18294 : * We need OR REPLACE here because we'll be replacing a dummy view.
18295 : * Otherwise this should look largely like the regular view dump code.
18296 : */
18297 20 : appendPQExpBuffer(cmd, "CREATE OR REPLACE VIEW %s",
18298 20 : fmtQualifiedDumpable(tbinfo));
18299 20 : if (nonemptyReloptions(tbinfo->reloptions))
18300 : {
18301 0 : appendPQExpBufferStr(cmd, " WITH (");
18302 0 : appendReloptionsArrayAH(cmd, tbinfo->reloptions, "", fout);
18303 0 : appendPQExpBufferChar(cmd, ')');
18304 : }
18305 20 : result = createViewAsClause(fout, tbinfo);
18306 20 : appendPQExpBuffer(cmd, " AS\n%s", result->data);
18307 20 : destroyPQExpBuffer(result);
18308 20 : if (tbinfo->checkoption != NULL)
18309 0 : appendPQExpBuffer(cmd, "\n WITH %s CHECK OPTION",
18310 : tbinfo->checkoption);
18311 20 : appendPQExpBufferStr(cmd, ";\n");
18312 : }
18313 : else
18314 : {
18315 : /* In the rule case, just print pg_get_ruledef's result verbatim */
18316 402 : appendPQExpBuffer(query,
18317 : "SELECT pg_catalog.pg_get_ruledef('%u'::pg_catalog.oid)",
18318 : rinfo->dobj.catId.oid);
18319 :
18320 402 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18321 :
18322 402 : if (PQntuples(res) != 1)
18323 0 : pg_fatal("query to get rule \"%s\" for table \"%s\" failed: wrong number of rows returned",
18324 : rinfo->dobj.name, tbinfo->dobj.name);
18325 :
18326 402 : printfPQExpBuffer(cmd, "%s\n", PQgetvalue(res, 0, 0));
18327 :
18328 402 : PQclear(res);
18329 : }
18330 :
18331 : /*
18332 : * Add the command to alter the rules replication firing semantics if it
18333 : * differs from the default.
18334 : */
18335 422 : if (rinfo->ev_enabled != 'O')
18336 : {
18337 30 : appendPQExpBuffer(cmd, "ALTER TABLE %s ", fmtQualifiedDumpable(tbinfo));
18338 30 : switch (rinfo->ev_enabled)
18339 : {
18340 0 : case 'A':
18341 0 : appendPQExpBuffer(cmd, "ENABLE ALWAYS RULE %s;\n",
18342 0 : fmtId(rinfo->dobj.name));
18343 0 : break;
18344 0 : case 'R':
18345 0 : appendPQExpBuffer(cmd, "ENABLE REPLICA RULE %s;\n",
18346 0 : fmtId(rinfo->dobj.name));
18347 0 : break;
18348 30 : case 'D':
18349 30 : appendPQExpBuffer(cmd, "DISABLE RULE %s;\n",
18350 30 : fmtId(rinfo->dobj.name));
18351 30 : break;
18352 : }
18353 392 : }
18354 :
18355 422 : if (is_view)
18356 : {
18357 : /*
18358 : * We can't DROP a view's ON SELECT rule. Instead, use CREATE OR
18359 : * REPLACE VIEW to replace the rule with something with minimal
18360 : * dependencies.
18361 : */
18362 : PQExpBuffer result;
18363 :
18364 20 : appendPQExpBuffer(delcmd, "CREATE OR REPLACE VIEW %s",
18365 20 : fmtQualifiedDumpable(tbinfo));
18366 20 : result = createDummyViewAsClause(fout, tbinfo);
18367 20 : appendPQExpBuffer(delcmd, " AS\n%s;\n", result->data);
18368 20 : destroyPQExpBuffer(result);
18369 : }
18370 : else
18371 : {
18372 402 : appendPQExpBuffer(delcmd, "DROP RULE %s ",
18373 402 : fmtId(rinfo->dobj.name));
18374 402 : appendPQExpBuffer(delcmd, "ON %s;\n",
18375 402 : fmtQualifiedDumpable(tbinfo));
18376 : }
18377 :
18378 422 : appendPQExpBuffer(ruleprefix, "RULE %s ON",
18379 422 : fmtId(rinfo->dobj.name));
18380 :
18381 422 : tag = psprintf("%s %s", tbinfo->dobj.name, rinfo->dobj.name);
18382 :
18383 422 : if (rinfo->dobj.dump & DUMP_COMPONENT_DEFINITION)
18384 422 : ArchiveEntry(fout, rinfo->dobj.catId, rinfo->dobj.dumpId,
18385 422 : ARCHIVE_OPTS(.tag = tag,
18386 : .namespace = tbinfo->dobj.namespace->dobj.name,
18387 : .owner = tbinfo->rolname,
18388 : .description = "RULE",
18389 : .section = SECTION_POST_DATA,
18390 : .createStmt = cmd->data,
18391 : .dropStmt = delcmd->data));
18392 :
18393 : /* Dump rule comments */
18394 422 : if (rinfo->dobj.dump & DUMP_COMPONENT_COMMENT)
18395 0 : dumpComment(fout, ruleprefix->data, qtabname,
18396 0 : tbinfo->dobj.namespace->dobj.name,
18397 : tbinfo->rolname,
18398 : rinfo->dobj.catId, 0, rinfo->dobj.dumpId);
18399 :
18400 422 : free(tag);
18401 422 : destroyPQExpBuffer(query);
18402 422 : destroyPQExpBuffer(cmd);
18403 422 : destroyPQExpBuffer(delcmd);
18404 422 : destroyPQExpBuffer(ruleprefix);
18405 422 : free(qtabname);
18406 : }
18407 :
18408 : /*
18409 : * getExtensionMembership --- obtain extension membership data
18410 : *
18411 : * We need to identify objects that are extension members as soon as they're
18412 : * loaded, so that we can correctly determine whether they need to be dumped.
18413 : * Generally speaking, extension member objects will get marked as *not* to
18414 : * be dumped, as they will be recreated by the single CREATE EXTENSION
18415 : * command. However, in binary upgrade mode we still need to dump the members
18416 : * individually.
18417 : */
18418 : void
18419 310 : getExtensionMembership(Archive *fout, ExtensionInfo extinfo[],
18420 : int numExtensions)
18421 : {
18422 : PQExpBuffer query;
18423 : PGresult *res;
18424 : int ntups,
18425 : i;
18426 : int i_classid,
18427 : i_objid,
18428 : i_refobjid;
18429 : ExtensionInfo *ext;
18430 :
18431 : /* Nothing to do if no extensions */
18432 310 : if (numExtensions == 0)
18433 0 : return;
18434 :
18435 310 : query = createPQExpBuffer();
18436 :
18437 : /* refclassid constraint is redundant but may speed the search */
18438 310 : appendPQExpBufferStr(query, "SELECT "
18439 : "classid, objid, refobjid "
18440 : "FROM pg_depend "
18441 : "WHERE refclassid = 'pg_extension'::regclass "
18442 : "AND deptype = 'e' "
18443 : "ORDER BY 3");
18444 :
18445 310 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18446 :
18447 310 : ntups = PQntuples(res);
18448 :
18449 310 : i_classid = PQfnumber(res, "classid");
18450 310 : i_objid = PQfnumber(res, "objid");
18451 310 : i_refobjid = PQfnumber(res, "refobjid");
18452 :
18453 : /*
18454 : * Since we ordered the SELECT by referenced ID, we can expect that
18455 : * multiple entries for the same extension will appear together; this
18456 : * saves on searches.
18457 : */
18458 310 : ext = NULL;
18459 :
18460 2750 : for (i = 0; i < ntups; i++)
18461 : {
18462 : CatalogId objId;
18463 : Oid extId;
18464 :
18465 2440 : objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
18466 2440 : objId.oid = atooid(PQgetvalue(res, i, i_objid));
18467 2440 : extId = atooid(PQgetvalue(res, i, i_refobjid));
18468 :
18469 2440 : if (ext == NULL ||
18470 2130 : ext->dobj.catId.oid != extId)
18471 360 : ext = findExtensionByOid(extId);
18472 :
18473 2440 : if (ext == NULL)
18474 : {
18475 : /* shouldn't happen */
18476 0 : pg_log_warning("could not find referenced extension %u", extId);
18477 0 : continue;
18478 : }
18479 :
18480 2440 : recordExtensionMembership(objId, ext);
18481 : }
18482 :
18483 310 : PQclear(res);
18484 :
18485 310 : destroyPQExpBuffer(query);
18486 : }
18487 :
18488 : /*
18489 : * processExtensionTables --- deal with extension configuration tables
18490 : *
18491 : * There are two parts to this process:
18492 : *
18493 : * 1. Identify and create dump records for extension configuration tables.
18494 : *
18495 : * Extensions can mark tables as "configuration", which means that the user
18496 : * is able and expected to modify those tables after the extension has been
18497 : * loaded. For these tables, we dump out only the data- the structure is
18498 : * expected to be handled at CREATE EXTENSION time, including any indexes or
18499 : * foreign keys, which brings us to-
18500 : *
18501 : * 2. Record FK dependencies between configuration tables.
18502 : *
18503 : * Due to the FKs being created at CREATE EXTENSION time and therefore before
18504 : * the data is loaded, we have to work out what the best order for reloading
18505 : * the data is, to avoid FK violations when the tables are restored. This is
18506 : * not perfect- we can't handle circular dependencies and if any exist they
18507 : * will cause an invalid dump to be produced (though at least all of the data
18508 : * is included for a user to manually restore). This is currently documented
18509 : * but perhaps we can provide a better solution in the future.
18510 : */
18511 : void
18512 308 : processExtensionTables(Archive *fout, ExtensionInfo extinfo[],
18513 : int numExtensions)
18514 : {
18515 308 : DumpOptions *dopt = fout->dopt;
18516 : PQExpBuffer query;
18517 : PGresult *res;
18518 : int ntups,
18519 : i;
18520 : int i_conrelid,
18521 : i_confrelid;
18522 :
18523 : /* Nothing to do if no extensions */
18524 308 : if (numExtensions == 0)
18525 0 : return;
18526 :
18527 : /*
18528 : * Identify extension configuration tables and create TableDataInfo
18529 : * objects for them, ensuring their data will be dumped even though the
18530 : * tables themselves won't be.
18531 : *
18532 : * Note that we create TableDataInfo objects even in schemaOnly mode, ie,
18533 : * user data in a configuration table is treated like schema data. This
18534 : * seems appropriate since system data in a config table would get
18535 : * reloaded by CREATE EXTENSION. If the extension is not listed in the
18536 : * list of extensions to be included, none of its data is dumped.
18537 : */
18538 666 : for (i = 0; i < numExtensions; i++)
18539 : {
18540 358 : ExtensionInfo *curext = &(extinfo[i]);
18541 358 : char *extconfig = curext->extconfig;
18542 358 : char *extcondition = curext->extcondition;
18543 358 : char **extconfigarray = NULL;
18544 358 : char **extconditionarray = NULL;
18545 358 : int nconfigitems = 0;
18546 358 : int nconditionitems = 0;
18547 :
18548 : /*
18549 : * Check if this extension is listed as to include in the dump. If
18550 : * not, any table data associated with it is discarded.
18551 : */
18552 358 : if (extension_include_oids.head != NULL &&
18553 16 : !simple_oid_list_member(&extension_include_oids,
18554 : curext->dobj.catId.oid))
18555 12 : continue;
18556 :
18557 : /*
18558 : * Check if this extension is listed as to exclude in the dump. If
18559 : * yes, any table data associated with it is discarded.
18560 : */
18561 358 : if (extension_exclude_oids.head != NULL &&
18562 8 : simple_oid_list_member(&extension_exclude_oids,
18563 : curext->dobj.catId.oid))
18564 4 : continue;
18565 :
18566 346 : if (strlen(extconfig) != 0 || strlen(extcondition) != 0)
18567 : {
18568 : int j;
18569 :
18570 40 : if (!parsePGArray(extconfig, &extconfigarray, &nconfigitems))
18571 0 : pg_fatal("could not parse %s array", "extconfig");
18572 40 : if (!parsePGArray(extcondition, &extconditionarray, &nconditionitems))
18573 0 : pg_fatal("could not parse %s array", "extcondition");
18574 40 : if (nconfigitems != nconditionitems)
18575 0 : pg_fatal("mismatched number of configurations and conditions for extension");
18576 :
18577 120 : for (j = 0; j < nconfigitems; j++)
18578 : {
18579 : TableInfo *configtbl;
18580 80 : Oid configtbloid = atooid(extconfigarray[j]);
18581 80 : bool dumpobj =
18582 80 : curext->dobj.dump & DUMP_COMPONENT_DEFINITION;
18583 :
18584 80 : configtbl = findTableByOid(configtbloid);
18585 80 : if (configtbl == NULL)
18586 0 : continue;
18587 :
18588 : /*
18589 : * Tables of not-to-be-dumped extensions shouldn't be dumped
18590 : * unless the table or its schema is explicitly included
18591 : */
18592 80 : if (!(curext->dobj.dump & DUMP_COMPONENT_DEFINITION))
18593 : {
18594 : /* check table explicitly requested */
18595 4 : if (table_include_oids.head != NULL &&
18596 0 : simple_oid_list_member(&table_include_oids,
18597 : configtbloid))
18598 0 : dumpobj = true;
18599 :
18600 : /* check table's schema explicitly requested */
18601 4 : if (configtbl->dobj.namespace->dobj.dump &
18602 : DUMP_COMPONENT_DATA)
18603 4 : dumpobj = true;
18604 : }
18605 :
18606 : /* check table excluded by an exclusion switch */
18607 88 : if (table_exclude_oids.head != NULL &&
18608 8 : simple_oid_list_member(&table_exclude_oids,
18609 : configtbloid))
18610 2 : dumpobj = false;
18611 :
18612 : /* check schema excluded by an exclusion switch */
18613 80 : if (simple_oid_list_member(&schema_exclude_oids,
18614 80 : configtbl->dobj.namespace->dobj.catId.oid))
18615 0 : dumpobj = false;
18616 :
18617 80 : if (dumpobj)
18618 : {
18619 78 : makeTableDataInfo(dopt, configtbl);
18620 78 : if (configtbl->dataObj != NULL)
18621 : {
18622 78 : if (strlen(extconditionarray[j]) > 0)
18623 0 : configtbl->dataObj->filtercond = pg_strdup(extconditionarray[j]);
18624 : }
18625 : }
18626 : }
18627 : }
18628 346 : if (extconfigarray)
18629 40 : free(extconfigarray);
18630 346 : if (extconditionarray)
18631 40 : free(extconditionarray);
18632 : }
18633 :
18634 : /*
18635 : * Now that all the TableDataInfo objects have been created for all the
18636 : * extensions, check their FK dependencies and register them to try and
18637 : * dump the data out in an order that they can be restored in.
18638 : *
18639 : * Note that this is not a problem for user tables as their FKs are
18640 : * recreated after the data has been loaded.
18641 : */
18642 :
18643 308 : query = createPQExpBuffer();
18644 :
18645 308 : printfPQExpBuffer(query,
18646 : "SELECT conrelid, confrelid "
18647 : "FROM pg_constraint "
18648 : "JOIN pg_depend ON (objid = confrelid) "
18649 : "WHERE contype = 'f' "
18650 : "AND refclassid = 'pg_extension'::regclass "
18651 : "AND classid = 'pg_class'::regclass;");
18652 :
18653 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18654 308 : ntups = PQntuples(res);
18655 :
18656 308 : i_conrelid = PQfnumber(res, "conrelid");
18657 308 : i_confrelid = PQfnumber(res, "confrelid");
18658 :
18659 : /* Now get the dependencies and register them */
18660 308 : for (i = 0; i < ntups; i++)
18661 : {
18662 : Oid conrelid,
18663 : confrelid;
18664 : TableInfo *reftable,
18665 : *contable;
18666 :
18667 0 : conrelid = atooid(PQgetvalue(res, i, i_conrelid));
18668 0 : confrelid = atooid(PQgetvalue(res, i, i_confrelid));
18669 0 : contable = findTableByOid(conrelid);
18670 0 : reftable = findTableByOid(confrelid);
18671 :
18672 0 : if (reftable == NULL ||
18673 0 : reftable->dataObj == NULL ||
18674 0 : contable == NULL ||
18675 0 : contable->dataObj == NULL)
18676 0 : continue;
18677 :
18678 : /*
18679 : * Make referencing TABLE_DATA object depend on the referenced table's
18680 : * TABLE_DATA object.
18681 : */
18682 0 : addObjectDependency(&contable->dataObj->dobj,
18683 0 : reftable->dataObj->dobj.dumpId);
18684 : }
18685 308 : PQclear(res);
18686 308 : destroyPQExpBuffer(query);
18687 : }
18688 :
18689 : /*
18690 : * getDependencies --- obtain available dependency data
18691 : */
18692 : static void
18693 308 : getDependencies(Archive *fout)
18694 : {
18695 : PQExpBuffer query;
18696 : PGresult *res;
18697 : int ntups,
18698 : i;
18699 : int i_classid,
18700 : i_objid,
18701 : i_refclassid,
18702 : i_refobjid,
18703 : i_deptype;
18704 : DumpableObject *dobj,
18705 : *refdobj;
18706 :
18707 308 : pg_log_info("reading dependency data");
18708 :
18709 308 : query = createPQExpBuffer();
18710 :
18711 : /*
18712 : * Messy query to collect the dependency data we need. Note that we
18713 : * ignore the sub-object column, so that dependencies of or on a column
18714 : * look the same as dependencies of or on a whole table.
18715 : *
18716 : * PIN dependencies aren't interesting, and EXTENSION dependencies were
18717 : * already processed by getExtensionMembership.
18718 : */
18719 308 : appendPQExpBufferStr(query, "SELECT "
18720 : "classid, objid, refclassid, refobjid, deptype "
18721 : "FROM pg_depend "
18722 : "WHERE deptype != 'p' AND deptype != 'e'\n");
18723 :
18724 : /*
18725 : * Since we don't treat pg_amop entries as separate DumpableObjects, we
18726 : * have to translate their dependencies into dependencies of their parent
18727 : * opfamily. Ignore internal dependencies though, as those will point to
18728 : * their parent opclass, which we needn't consider here (and if we did,
18729 : * it'd just result in circular dependencies). Also, "loose" opfamily
18730 : * entries will have dependencies on their parent opfamily, which we
18731 : * should drop since they'd likewise become useless self-dependencies.
18732 : * (But be sure to keep deps on *other* opfamilies; see amopsortfamily.)
18733 : */
18734 308 : appendPQExpBufferStr(query, "UNION ALL\n"
18735 : "SELECT 'pg_opfamily'::regclass AS classid, amopfamily AS objid, refclassid, refobjid, deptype "
18736 : "FROM pg_depend d, pg_amop o "
18737 : "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18738 : "classid = 'pg_amop'::regclass AND objid = o.oid "
18739 : "AND NOT (refclassid = 'pg_opfamily'::regclass AND amopfamily = refobjid)\n");
18740 :
18741 : /* Likewise for pg_amproc entries */
18742 308 : appendPQExpBufferStr(query, "UNION ALL\n"
18743 : "SELECT 'pg_opfamily'::regclass AS classid, amprocfamily AS objid, refclassid, refobjid, deptype "
18744 : "FROM pg_depend d, pg_amproc p "
18745 : "WHERE deptype NOT IN ('p', 'e', 'i') AND "
18746 : "classid = 'pg_amproc'::regclass AND objid = p.oid "
18747 : "AND NOT (refclassid = 'pg_opfamily'::regclass AND amprocfamily = refobjid)\n");
18748 :
18749 : /* Sort the output for efficiency below */
18750 308 : appendPQExpBufferStr(query, "ORDER BY 1,2");
18751 :
18752 308 : res = ExecuteSqlQuery(fout, query->data, PGRES_TUPLES_OK);
18753 :
18754 308 : ntups = PQntuples(res);
18755 :
18756 308 : i_classid = PQfnumber(res, "classid");
18757 308 : i_objid = PQfnumber(res, "objid");
18758 308 : i_refclassid = PQfnumber(res, "refclassid");
18759 308 : i_refobjid = PQfnumber(res, "refobjid");
18760 308 : i_deptype = PQfnumber(res, "deptype");
18761 :
18762 : /*
18763 : * Since we ordered the SELECT by referencing ID, we can expect that
18764 : * multiple entries for the same object will appear together; this saves
18765 : * on searches.
18766 : */
18767 308 : dobj = NULL;
18768 :
18769 668370 : for (i = 0; i < ntups; i++)
18770 : {
18771 : CatalogId objId;
18772 : CatalogId refobjId;
18773 : char deptype;
18774 :
18775 668062 : objId.tableoid = atooid(PQgetvalue(res, i, i_classid));
18776 668062 : objId.oid = atooid(PQgetvalue(res, i, i_objid));
18777 668062 : refobjId.tableoid = atooid(PQgetvalue(res, i, i_refclassid));
18778 668062 : refobjId.oid = atooid(PQgetvalue(res, i, i_refobjid));
18779 668062 : deptype = *(PQgetvalue(res, i, i_deptype));
18780 :
18781 668062 : if (dobj == NULL ||
18782 622782 : dobj->catId.tableoid != objId.tableoid ||
18783 619142 : dobj->catId.oid != objId.oid)
18784 295334 : dobj = findObjectByCatalogId(objId);
18785 :
18786 : /*
18787 : * Failure to find objects mentioned in pg_depend is not unexpected,
18788 : * since for example we don't collect info about TOAST tables.
18789 : */
18790 668062 : if (dobj == NULL)
18791 : {
18792 : #ifdef NOT_USED
18793 : pg_log_warning("no referencing object %u %u",
18794 : objId.tableoid, objId.oid);
18795 : #endif
18796 46502 : continue;
18797 : }
18798 :
18799 623074 : refdobj = findObjectByCatalogId(refobjId);
18800 :
18801 623074 : if (refdobj == NULL)
18802 : {
18803 : #ifdef NOT_USED
18804 : pg_log_warning("no referenced object %u %u",
18805 : refobjId.tableoid, refobjId.oid);
18806 : #endif
18807 1514 : continue;
18808 : }
18809 :
18810 : /*
18811 : * For 'x' dependencies, mark the object for later; we still add the
18812 : * normal dependency, for possible ordering purposes. Currently
18813 : * pg_dump_sort.c knows to put extensions ahead of all object types
18814 : * that could possibly depend on them, but this is safer.
18815 : */
18816 621560 : if (deptype == 'x')
18817 88 : dobj->depends_on_ext = true;
18818 :
18819 : /*
18820 : * Ordinarily, table rowtypes have implicit dependencies on their
18821 : * tables. However, for a composite type the implicit dependency goes
18822 : * the other way in pg_depend; which is the right thing for DROP but
18823 : * it doesn't produce the dependency ordering we need. So in that one
18824 : * case, we reverse the direction of the dependency.
18825 : */
18826 621560 : if (deptype == 'i' &&
18827 173374 : dobj->objType == DO_TABLE &&
18828 2322 : refdobj->objType == DO_TYPE)
18829 360 : addObjectDependency(refdobj, dobj->dumpId);
18830 : else
18831 : /* normal case */
18832 621200 : addObjectDependency(dobj, refdobj->dumpId);
18833 : }
18834 :
18835 308 : PQclear(res);
18836 :
18837 308 : destroyPQExpBuffer(query);
18838 308 : }
18839 :
18840 :
18841 : /*
18842 : * createBoundaryObjects - create dummy DumpableObjects to represent
18843 : * dump section boundaries.
18844 : */
18845 : static DumpableObject *
18846 308 : createBoundaryObjects(void)
18847 : {
18848 : DumpableObject *dobjs;
18849 :
18850 308 : dobjs = (DumpableObject *) pg_malloc(2 * sizeof(DumpableObject));
18851 :
18852 308 : dobjs[0].objType = DO_PRE_DATA_BOUNDARY;
18853 308 : dobjs[0].catId = nilCatalogId;
18854 308 : AssignDumpId(dobjs + 0);
18855 308 : dobjs[0].name = pg_strdup("PRE-DATA BOUNDARY");
18856 :
18857 308 : dobjs[1].objType = DO_POST_DATA_BOUNDARY;
18858 308 : dobjs[1].catId = nilCatalogId;
18859 308 : AssignDumpId(dobjs + 1);
18860 308 : dobjs[1].name = pg_strdup("POST-DATA BOUNDARY");
18861 :
18862 308 : return dobjs;
18863 : }
18864 :
18865 : /*
18866 : * addBoundaryDependencies - add dependencies as needed to enforce the dump
18867 : * section boundaries.
18868 : */
18869 : static void
18870 308 : addBoundaryDependencies(DumpableObject **dobjs, int numObjs,
18871 : DumpableObject *boundaryObjs)
18872 : {
18873 308 : DumpableObject *preDataBound = boundaryObjs + 0;
18874 308 : DumpableObject *postDataBound = boundaryObjs + 1;
18875 : int i;
18876 :
18877 1126092 : for (i = 0; i < numObjs; i++)
18878 : {
18879 1125784 : DumpableObject *dobj = dobjs[i];
18880 :
18881 : /*
18882 : * The classification of object types here must match the SECTION_xxx
18883 : * values assigned during subsequent ArchiveEntry calls!
18884 : */
18885 1125784 : switch (dobj->objType)
18886 : {
18887 1055370 : case DO_NAMESPACE:
18888 : case DO_EXTENSION:
18889 : case DO_TYPE:
18890 : case DO_SHELL_TYPE:
18891 : case DO_FUNC:
18892 : case DO_AGG:
18893 : case DO_OPERATOR:
18894 : case DO_ACCESS_METHOD:
18895 : case DO_OPCLASS:
18896 : case DO_OPFAMILY:
18897 : case DO_COLLATION:
18898 : case DO_CONVERSION:
18899 : case DO_TABLE:
18900 : case DO_TABLE_ATTACH:
18901 : case DO_ATTRDEF:
18902 : case DO_PROCLANG:
18903 : case DO_CAST:
18904 : case DO_DUMMY_TYPE:
18905 : case DO_TSPARSER:
18906 : case DO_TSDICT:
18907 : case DO_TSTEMPLATE:
18908 : case DO_TSCONFIG:
18909 : case DO_FDW:
18910 : case DO_FOREIGN_SERVER:
18911 : case DO_TRANSFORM:
18912 : /* Pre-data objects: must come before the pre-data boundary */
18913 1055370 : addObjectDependency(preDataBound, dobj->dumpId);
18914 1055370 : break;
18915 8312 : case DO_TABLE_DATA:
18916 : case DO_SEQUENCE_SET:
18917 : case DO_LARGE_OBJECT:
18918 : case DO_LARGE_OBJECT_DATA:
18919 : /* Data objects: must come between the boundaries */
18920 8312 : addObjectDependency(dobj, preDataBound->dumpId);
18921 8312 : addObjectDependency(postDataBound, dobj->dumpId);
18922 8312 : break;
18923 10244 : case DO_INDEX:
18924 : case DO_INDEX_ATTACH:
18925 : case DO_STATSEXT:
18926 : case DO_REFRESH_MATVIEW:
18927 : case DO_TRIGGER:
18928 : case DO_EVENT_TRIGGER:
18929 : case DO_DEFAULT_ACL:
18930 : case DO_POLICY:
18931 : case DO_PUBLICATION:
18932 : case DO_PUBLICATION_REL:
18933 : case DO_PUBLICATION_TABLE_IN_SCHEMA:
18934 : case DO_SUBSCRIPTION:
18935 : case DO_SUBSCRIPTION_REL:
18936 : /* Post-data objects: must come after the post-data boundary */
18937 10244 : addObjectDependency(dobj, postDataBound->dumpId);
18938 10244 : break;
18939 46850 : case DO_RULE:
18940 : /* Rules are post-data, but only if dumped separately */
18941 46850 : if (((RuleInfo *) dobj)->separate)
18942 1162 : addObjectDependency(dobj, postDataBound->dumpId);
18943 46850 : break;
18944 4392 : case DO_CONSTRAINT:
18945 : case DO_FK_CONSTRAINT:
18946 : /* Constraints are post-data, but only if dumped separately */
18947 4392 : if (((ConstraintInfo *) dobj)->separate)
18948 3164 : addObjectDependency(dobj, postDataBound->dumpId);
18949 4392 : break;
18950 308 : case DO_PRE_DATA_BOUNDARY:
18951 : /* nothing to do */
18952 308 : break;
18953 308 : case DO_POST_DATA_BOUNDARY:
18954 : /* must come after the pre-data boundary */
18955 308 : addObjectDependency(dobj, preDataBound->dumpId);
18956 308 : break;
18957 : }
18958 1125784 : }
18959 308 : }
18960 :
18961 :
18962 : /*
18963 : * BuildArchiveDependencies - create dependency data for archive TOC entries
18964 : *
18965 : * The raw dependency data obtained by getDependencies() is not terribly
18966 : * useful in an archive dump, because in many cases there are dependency
18967 : * chains linking through objects that don't appear explicitly in the dump.
18968 : * For example, a view will depend on its _RETURN rule while the _RETURN rule
18969 : * will depend on other objects --- but the rule will not appear as a separate
18970 : * object in the dump. We need to adjust the view's dependencies to include
18971 : * whatever the rule depends on that is included in the dump.
18972 : *
18973 : * Just to make things more complicated, there are also "special" dependencies
18974 : * such as the dependency of a TABLE DATA item on its TABLE, which we must
18975 : * not rearrange because pg_restore knows that TABLE DATA only depends on
18976 : * its table. In these cases we must leave the dependencies strictly as-is
18977 : * even if they refer to not-to-be-dumped objects.
18978 : *
18979 : * To handle this, the convention is that "special" dependencies are created
18980 : * during ArchiveEntry calls, and an archive TOC item that has any such
18981 : * entries will not be touched here. Otherwise, we recursively search the
18982 : * DumpableObject data structures to build the correct dependencies for each
18983 : * archive TOC item.
18984 : */
18985 : static void
18986 62 : BuildArchiveDependencies(Archive *fout)
18987 : {
18988 62 : ArchiveHandle *AH = (ArchiveHandle *) fout;
18989 : TocEntry *te;
18990 :
18991 : /* Scan all TOC entries in the archive */
18992 9708 : for (te = AH->toc->next; te != AH->toc; te = te->next)
18993 : {
18994 : DumpableObject *dobj;
18995 : DumpId *dependencies;
18996 : int nDeps;
18997 : int allocDeps;
18998 :
18999 : /* No need to process entries that will not be dumped */
19000 9646 : if (te->reqs == 0)
19001 2954 : continue;
19002 : /* Ignore entries that already have "special" dependencies */
19003 9640 : if (te->nDeps > 0)
19004 2420 : continue;
19005 : /* Otherwise, look up the item's original DumpableObject, if any */
19006 7220 : dobj = findObjectByDumpId(te->dumpId);
19007 7220 : if (dobj == NULL)
19008 318 : continue;
19009 : /* No work if it has no dependencies */
19010 6902 : if (dobj->nDeps <= 0)
19011 210 : continue;
19012 : /* Set up work array */
19013 6692 : allocDeps = 64;
19014 6692 : dependencies = (DumpId *) pg_malloc(allocDeps * sizeof(DumpId));
19015 6692 : nDeps = 0;
19016 : /* Recursively find all dumpable dependencies */
19017 6692 : findDumpableDependencies(AH, dobj,
19018 : &dependencies, &nDeps, &allocDeps);
19019 : /* And save 'em ... */
19020 6692 : if (nDeps > 0)
19021 : {
19022 5096 : dependencies = (DumpId *) pg_realloc(dependencies,
19023 : nDeps * sizeof(DumpId));
19024 5096 : te->dependencies = dependencies;
19025 5096 : te->nDeps = nDeps;
19026 : }
19027 : else
19028 1596 : free(dependencies);
19029 : }
19030 62 : }
19031 :
19032 : /* Recursive search subroutine for BuildArchiveDependencies */
19033 : static void
19034 16408 : findDumpableDependencies(ArchiveHandle *AH, const DumpableObject *dobj,
19035 : DumpId **dependencies, int *nDeps, int *allocDeps)
19036 : {
19037 : int i;
19038 :
19039 : /*
19040 : * Ignore section boundary objects: if we search through them, we'll
19041 : * report lots of bogus dependencies.
19042 : */
19043 16408 : if (dobj->objType == DO_PRE_DATA_BOUNDARY ||
19044 16370 : dobj->objType == DO_POST_DATA_BOUNDARY)
19045 2918 : return;
19046 :
19047 34178 : for (i = 0; i < dobj->nDeps; i++)
19048 : {
19049 20688 : DumpId depid = dobj->dependencies[i];
19050 :
19051 20688 : if (TocIDRequired(AH, depid) != 0)
19052 : {
19053 : /* Object will be dumped, so just reference it as a dependency */
19054 10972 : if (*nDeps >= *allocDeps)
19055 : {
19056 0 : *allocDeps *= 2;
19057 0 : *dependencies = (DumpId *) pg_realloc(*dependencies,
19058 0 : *allocDeps * sizeof(DumpId));
19059 : }
19060 10972 : (*dependencies)[*nDeps] = depid;
19061 10972 : (*nDeps)++;
19062 : }
19063 : else
19064 : {
19065 : /*
19066 : * Object will not be dumped, so recursively consider its deps. We
19067 : * rely on the assumption that sortDumpableObjects already broke
19068 : * any dependency loops, else we might recurse infinitely.
19069 : */
19070 9716 : DumpableObject *otherdobj = findObjectByDumpId(depid);
19071 :
19072 9716 : if (otherdobj)
19073 9716 : findDumpableDependencies(AH, otherdobj,
19074 : dependencies, nDeps, allocDeps);
19075 : }
19076 : }
19077 : }
19078 :
19079 :
19080 : /*
19081 : * getFormattedTypeName - retrieve a nicely-formatted type name for the
19082 : * given type OID.
19083 : *
19084 : * This does not guarantee to schema-qualify the output, so it should not
19085 : * be used to create the target object name for CREATE or ALTER commands.
19086 : *
19087 : * Note that the result is cached and must not be freed by the caller.
19088 : */
19089 : static const char *
19090 4624 : getFormattedTypeName(Archive *fout, Oid oid, OidOptions opts)
19091 : {
19092 : TypeInfo *typeInfo;
19093 : char *result;
19094 : PQExpBuffer query;
19095 : PGresult *res;
19096 :
19097 4624 : if (oid == 0)
19098 : {
19099 0 : if ((opts & zeroAsStar) != 0)
19100 0 : return "*";
19101 0 : else if ((opts & zeroAsNone) != 0)
19102 0 : return "NONE";
19103 : }
19104 :
19105 : /* see if we have the result cached in the type's TypeInfo record */
19106 4624 : typeInfo = findTypeByOid(oid);
19107 4624 : if (typeInfo && typeInfo->ftypname)
19108 3676 : return typeInfo->ftypname;
19109 :
19110 948 : query = createPQExpBuffer();
19111 948 : appendPQExpBuffer(query, "SELECT pg_catalog.format_type('%u'::pg_catalog.oid, NULL)",
19112 : oid);
19113 :
19114 948 : res = ExecuteSqlQueryForSingleRow(fout, query->data);
19115 :
19116 : /* result of format_type is already quoted */
19117 948 : result = pg_strdup(PQgetvalue(res, 0, 0));
19118 :
19119 948 : PQclear(res);
19120 948 : destroyPQExpBuffer(query);
19121 :
19122 : /*
19123 : * Cache the result for re-use in later requests, if possible. If we
19124 : * don't have a TypeInfo for the type, the string will be leaked once the
19125 : * caller is done with it ... but that case really should not happen, so
19126 : * leaking if it does seems acceptable.
19127 : */
19128 948 : if (typeInfo)
19129 948 : typeInfo->ftypname = result;
19130 :
19131 948 : return result;
19132 : }
19133 :
19134 : /*
19135 : * Return a column list clause for the given relation.
19136 : *
19137 : * Special case: if there are no undropped columns in the relation, return
19138 : * "", not an invalid "()" column list.
19139 : */
19140 : static const char *
19141 14172 : fmtCopyColumnList(const TableInfo *ti, PQExpBuffer buffer)
19142 : {
19143 14172 : int numatts = ti->numatts;
19144 14172 : char **attnames = ti->attnames;
19145 14172 : bool *attisdropped = ti->attisdropped;
19146 14172 : char *attgenerated = ti->attgenerated;
19147 : bool needComma;
19148 : int i;
19149 :
19150 14172 : appendPQExpBufferChar(buffer, '(');
19151 14172 : needComma = false;
19152 72492 : for (i = 0; i < numatts; i++)
19153 : {
19154 58320 : if (attisdropped[i])
19155 1116 : continue;
19156 57204 : if (attgenerated[i])
19157 1180 : continue;
19158 56024 : if (needComma)
19159 42300 : appendPQExpBufferStr(buffer, ", ");
19160 56024 : appendPQExpBufferStr(buffer, fmtId(attnames[i]));
19161 56024 : needComma = true;
19162 : }
19163 :
19164 14172 : if (!needComma)
19165 448 : return ""; /* no undropped columns */
19166 :
19167 13724 : appendPQExpBufferChar(buffer, ')');
19168 13724 : return buffer->data;
19169 : }
19170 :
19171 : /*
19172 : * Check if a reloptions array is nonempty.
19173 : */
19174 : static bool
19175 24260 : nonemptyReloptions(const char *reloptions)
19176 : {
19177 : /* Don't want to print it if it's just "{}" */
19178 24260 : return (reloptions != NULL && strlen(reloptions) > 2);
19179 : }
19180 :
19181 : /*
19182 : * Format a reloptions array and append it to the given buffer.
19183 : *
19184 : * "prefix" is prepended to the option names; typically it's "" or "toast.".
19185 : */
19186 : static void
19187 420 : appendReloptionsArrayAH(PQExpBuffer buffer, const char *reloptions,
19188 : const char *prefix, Archive *fout)
19189 : {
19190 : bool res;
19191 :
19192 420 : res = appendReloptionsArray(buffer, reloptions, prefix, fout->encoding,
19193 420 : fout->std_strings);
19194 420 : if (!res)
19195 0 : pg_log_warning("could not parse %s array", "reloptions");
19196 420 : }
19197 :
19198 : /*
19199 : * read_dump_filters - retrieve object identifier patterns from file
19200 : *
19201 : * Parse the specified filter file for include and exclude patterns, and add
19202 : * them to the relevant lists. If the filename is "-" then filters will be
19203 : * read from STDIN rather than a file.
19204 : */
19205 : static void
19206 52 : read_dump_filters(const char *filename, DumpOptions *dopt)
19207 : {
19208 : FilterStateData fstate;
19209 : char *objname;
19210 : FilterCommandType comtype;
19211 : FilterObjectType objtype;
19212 :
19213 52 : filter_init(&fstate, filename, exit_nicely);
19214 :
19215 116 : while (filter_read_item(&fstate, &objname, &comtype, &objtype))
19216 : {
19217 66 : if (comtype == FILTER_COMMAND_TYPE_INCLUDE)
19218 : {
19219 34 : switch (objtype)
19220 : {
19221 0 : case FILTER_OBJECT_TYPE_NONE:
19222 0 : break;
19223 0 : case FILTER_OBJECT_TYPE_DATABASE:
19224 : case FILTER_OBJECT_TYPE_FUNCTION:
19225 : case FILTER_OBJECT_TYPE_INDEX:
19226 : case FILTER_OBJECT_TYPE_TABLE_DATA:
19227 : case FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN:
19228 : case FILTER_OBJECT_TYPE_TRIGGER:
19229 0 : pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
19230 : "include",
19231 : filter_object_type_name(objtype));
19232 0 : exit_nicely(1);
19233 : break; /* unreachable */
19234 :
19235 2 : case FILTER_OBJECT_TYPE_EXTENSION:
19236 2 : simple_string_list_append(&extension_include_patterns, objname);
19237 2 : break;
19238 2 : case FILTER_OBJECT_TYPE_FOREIGN_DATA:
19239 2 : simple_string_list_append(&foreign_servers_include_patterns, objname);
19240 2 : break;
19241 2 : case FILTER_OBJECT_TYPE_SCHEMA:
19242 2 : simple_string_list_append(&schema_include_patterns, objname);
19243 2 : dopt->include_everything = false;
19244 2 : break;
19245 26 : case FILTER_OBJECT_TYPE_TABLE:
19246 26 : simple_string_list_append(&table_include_patterns, objname);
19247 26 : dopt->include_everything = false;
19248 26 : break;
19249 2 : case FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN:
19250 2 : simple_string_list_append(&table_include_patterns_and_children,
19251 : objname);
19252 2 : dopt->include_everything = false;
19253 2 : break;
19254 : }
19255 34 : }
19256 32 : else if (comtype == FILTER_COMMAND_TYPE_EXCLUDE)
19257 : {
19258 18 : switch (objtype)
19259 : {
19260 0 : case FILTER_OBJECT_TYPE_NONE:
19261 0 : break;
19262 2 : case FILTER_OBJECT_TYPE_DATABASE:
19263 : case FILTER_OBJECT_TYPE_FUNCTION:
19264 : case FILTER_OBJECT_TYPE_INDEX:
19265 : case FILTER_OBJECT_TYPE_TRIGGER:
19266 : case FILTER_OBJECT_TYPE_FOREIGN_DATA:
19267 2 : pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
19268 : "exclude",
19269 : filter_object_type_name(objtype));
19270 2 : exit_nicely(1);
19271 : break;
19272 :
19273 2 : case FILTER_OBJECT_TYPE_EXTENSION:
19274 2 : simple_string_list_append(&extension_exclude_patterns, objname);
19275 2 : break;
19276 2 : case FILTER_OBJECT_TYPE_TABLE_DATA:
19277 2 : simple_string_list_append(&tabledata_exclude_patterns,
19278 : objname);
19279 2 : break;
19280 2 : case FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN:
19281 2 : simple_string_list_append(&tabledata_exclude_patterns_and_children,
19282 : objname);
19283 2 : break;
19284 4 : case FILTER_OBJECT_TYPE_SCHEMA:
19285 4 : simple_string_list_append(&schema_exclude_patterns, objname);
19286 4 : break;
19287 4 : case FILTER_OBJECT_TYPE_TABLE:
19288 4 : simple_string_list_append(&table_exclude_patterns, objname);
19289 4 : break;
19290 2 : case FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN:
19291 2 : simple_string_list_append(&table_exclude_patterns_and_children,
19292 : objname);
19293 2 : break;
19294 : }
19295 16 : }
19296 : else
19297 : {
19298 : Assert(comtype == FILTER_COMMAND_TYPE_NONE);
19299 : Assert(objtype == FILTER_OBJECT_TYPE_NONE);
19300 : }
19301 :
19302 64 : if (objname)
19303 50 : free(objname);
19304 : }
19305 :
19306 44 : filter_free(&fstate);
19307 44 : }
|