Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * pg_dumpall.c
4 : *
5 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
6 : * Portions Copyright (c) 1994, Regents of the University of California
7 : *
8 : * pg_dumpall forces all pg_dump output to be text, since it also outputs
9 : * text into the same output stream.
10 : *
11 : * src/bin/pg_dump/pg_dumpall.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 :
16 : #include "postgres_fe.h"
17 :
18 : #include <time.h>
19 : #include <unistd.h>
20 :
21 : #include "catalog/pg_authid_d.h"
22 : #include "common/connect.h"
23 : #include "common/file_perm.h"
24 : #include "common/file_utils.h"
25 : #include "common/hashfn_unstable.h"
26 : #include "common/logging.h"
27 : #include "common/string.h"
28 : #include "connectdb.h"
29 : #include "dumputils.h"
30 : #include "fe_utils/string_utils.h"
31 : #include "filter.h"
32 : #include "getopt_long.h"
33 :
34 : /* version string we expect back from pg_dump */
35 : #define PGDUMP_VERSIONSTR "pg_dump (PostgreSQL) " PG_VERSION "\n"
36 :
37 : typedef struct
38 : {
39 : uint32 status;
40 : uint32 hashval;
41 : char *rolename;
42 : } RoleNameEntry;
43 :
44 : #define SH_PREFIX rolename
45 : #define SH_ELEMENT_TYPE RoleNameEntry
46 : #define SH_KEY_TYPE char *
47 : #define SH_KEY rolename
48 : #define SH_HASH_KEY(tb, key) hash_string(key)
49 : #define SH_EQUAL(tb, a, b) (strcmp(a, b) == 0)
50 : #define SH_STORE_HASH
51 : #define SH_GET_HASH(tb, a) (a)->hashval
52 : #define SH_SCOPE static inline
53 : #define SH_RAW_ALLOCATOR pg_malloc0
54 : #define SH_DECLARE
55 : #define SH_DEFINE
56 : #include "lib/simplehash.h"
57 :
58 : static void help(void);
59 :
60 : static void dropRoles(PGconn *conn);
61 : static void dumpRoles(PGconn *conn);
62 : static void dumpRoleMembership(PGconn *conn);
63 : static void dumpRoleGUCPrivs(PGconn *conn);
64 : static void dropTablespaces(PGconn *conn);
65 : static void dumpTablespaces(PGconn *conn);
66 : static void dropDBs(PGconn *conn);
67 : static void dumpUserConfig(PGconn *conn, const char *username);
68 : static void dumpDatabases(PGconn *conn, ArchiveFormat archDumpFormat);
69 : static void dumpTimestamp(const char *msg);
70 : static int runPgDump(const char *dbname, const char *create_opts,
71 : char *dbfile, ArchiveFormat archDumpFormat);
72 : static void buildShSecLabels(PGconn *conn,
73 : const char *catalog_name, Oid objectId,
74 : const char *objtype, const char *objname,
75 : PQExpBuffer buffer);
76 : static void executeCommand(PGconn *conn, const char *query);
77 : static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns,
78 : SimpleStringList *names);
79 : static void read_dumpall_filters(const char *filename, SimpleStringList *pattern);
80 : static ArchiveFormat parseDumpFormat(const char *format);
81 :
82 : static char pg_dump_bin[MAXPGPATH];
83 : static PQExpBuffer pgdumpopts;
84 : static const char *connstr = "";
85 : static bool output_clean = false;
86 : static bool skip_acls = false;
87 : static bool verbose = false;
88 : static bool dosync = true;
89 :
90 : static int binary_upgrade = 0;
91 : static int column_inserts = 0;
92 : static int disable_dollar_quoting = 0;
93 : static int disable_triggers = 0;
94 : static int if_exists = 0;
95 : static int inserts = 0;
96 : static int no_table_access_method = 0;
97 : static int no_tablespaces = 0;
98 : static int use_setsessauth = 0;
99 : static int no_comments = 0;
100 : static int no_policies = 0;
101 : static int no_publications = 0;
102 : static int no_security_labels = 0;
103 : static int no_data = 0;
104 : static int no_schema = 0;
105 : static int no_statistics = 0;
106 : static int no_subscriptions = 0;
107 : static int no_toast_compression = 0;
108 : static int no_unlogged_table_data = 0;
109 : static int no_role_passwords = 0;
110 : static int with_data = 0;
111 : static int with_schema = 0;
112 : static int with_statistics = 0;
113 : static int server_version;
114 : static int load_via_partition_root = 0;
115 : static int on_conflict_do_nothing = 0;
116 : static int statistics_only = 0;
117 :
118 : static char role_catalog[10];
119 : #define PG_AUTHID "pg_authid"
120 : #define PG_ROLES "pg_roles "
121 :
122 : static FILE *OPF;
123 : static char *filename = NULL;
124 :
125 : static SimpleStringList database_exclude_patterns = {NULL, NULL};
126 : static SimpleStringList database_exclude_names = {NULL, NULL};
127 :
128 : int
129 140 : main(int argc, char *argv[])
130 : {
131 : static struct option long_options[] = {
132 : {"data-only", no_argument, NULL, 'a'},
133 : {"clean", no_argument, NULL, 'c'},
134 : {"encoding", required_argument, NULL, 'E'},
135 : {"file", required_argument, NULL, 'f'},
136 : {"globals-only", no_argument, NULL, 'g'},
137 : {"host", required_argument, NULL, 'h'},
138 : {"dbname", required_argument, NULL, 'd'},
139 : {"database", required_argument, NULL, 'l'},
140 : {"no-owner", no_argument, NULL, 'O'},
141 : {"port", required_argument, NULL, 'p'},
142 : {"roles-only", no_argument, NULL, 'r'},
143 : {"schema-only", no_argument, NULL, 's'},
144 : {"superuser", required_argument, NULL, 'S'},
145 : {"tablespaces-only", no_argument, NULL, 't'},
146 : {"username", required_argument, NULL, 'U'},
147 : {"verbose", no_argument, NULL, 'v'},
148 : {"no-password", no_argument, NULL, 'w'},
149 : {"password", no_argument, NULL, 'W'},
150 : {"no-privileges", no_argument, NULL, 'x'},
151 : {"no-acl", no_argument, NULL, 'x'},
152 : {"format", required_argument, NULL, 'F'},
153 :
154 : /*
155 : * the following options don't have an equivalent short option letter
156 : */
157 : {"attribute-inserts", no_argument, &column_inserts, 1},
158 : {"binary-upgrade", no_argument, &binary_upgrade, 1},
159 : {"column-inserts", no_argument, &column_inserts, 1},
160 : {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
161 : {"disable-triggers", no_argument, &disable_triggers, 1},
162 : {"exclude-database", required_argument, NULL, 6},
163 : {"extra-float-digits", required_argument, NULL, 5},
164 : {"if-exists", no_argument, &if_exists, 1},
165 : {"inserts", no_argument, &inserts, 1},
166 : {"lock-wait-timeout", required_argument, NULL, 2},
167 : {"no-table-access-method", no_argument, &no_table_access_method, 1},
168 : {"no-tablespaces", no_argument, &no_tablespaces, 1},
169 : {"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
170 : {"load-via-partition-root", no_argument, &load_via_partition_root, 1},
171 : {"role", required_argument, NULL, 3},
172 : {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
173 : {"no-comments", no_argument, &no_comments, 1},
174 : {"no-data", no_argument, &no_data, 1},
175 : {"no-policies", no_argument, &no_policies, 1},
176 : {"no-publications", no_argument, &no_publications, 1},
177 : {"no-role-passwords", no_argument, &no_role_passwords, 1},
178 : {"no-schema", no_argument, &no_schema, 1},
179 : {"no-security-labels", no_argument, &no_security_labels, 1},
180 : {"no-subscriptions", no_argument, &no_subscriptions, 1},
181 : {"no-statistics", no_argument, &no_statistics, 1},
182 : {"no-sync", no_argument, NULL, 4},
183 : {"no-toast-compression", no_argument, &no_toast_compression, 1},
184 : {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
185 : {"with-data", no_argument, &with_data, 1},
186 : {"with-schema", no_argument, &with_schema, 1},
187 : {"with-statistics", no_argument, &with_statistics, 1},
188 : {"on-conflict-do-nothing", no_argument, &on_conflict_do_nothing, 1},
189 : {"rows-per-insert", required_argument, NULL, 7},
190 : {"statistics-only", no_argument, &statistics_only, 1},
191 : {"filter", required_argument, NULL, 8},
192 :
193 : {NULL, 0, NULL, 0}
194 : };
195 :
196 140 : char *pghost = NULL;
197 140 : char *pgport = NULL;
198 140 : char *pguser = NULL;
199 140 : char *pgdb = NULL;
200 140 : char *use_role = NULL;
201 140 : const char *dumpencoding = NULL;
202 140 : ArchiveFormat archDumpFormat = archNull;
203 140 : const char *formatName = "p";
204 140 : trivalue prompt_password = TRI_DEFAULT;
205 140 : bool data_only = false;
206 140 : bool globals_only = false;
207 140 : bool roles_only = false;
208 140 : bool tablespaces_only = false;
209 : PGconn *conn;
210 : int encoding;
211 : const char *std_strings;
212 : int c,
213 : ret;
214 : int optindex;
215 :
216 140 : pg_logging_init(argv[0]);
217 140 : pg_logging_set_level(PG_LOG_WARNING);
218 140 : set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
219 140 : progname = get_progname(argv[0]);
220 :
221 140 : if (argc > 1)
222 : {
223 140 : if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
224 : {
225 2 : help();
226 2 : exit_nicely(0);
227 : }
228 138 : if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
229 : {
230 34 : puts("pg_dumpall (PostgreSQL) " PG_VERSION);
231 34 : exit_nicely(0);
232 : }
233 : }
234 :
235 104 : if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
236 : pg_dump_bin)) < 0)
237 : {
238 : char full_path[MAXPGPATH];
239 :
240 0 : if (find_my_exec(argv[0], full_path) < 0)
241 0 : strlcpy(full_path, progname, sizeof(full_path));
242 :
243 0 : if (ret == -1)
244 0 : pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
245 : "pg_dump", progname, full_path);
246 : else
247 0 : pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
248 : "pg_dump", full_path, progname);
249 : }
250 :
251 104 : pgdumpopts = createPQExpBuffer();
252 :
253 492 : while ((c = getopt_long(argc, argv, "acd:E:f:F:gh:l:Op:rsS:tU:vwWx", long_options, &optindex)) != -1)
254 : {
255 396 : switch (c)
256 : {
257 0 : case 'a':
258 0 : data_only = true;
259 0 : appendPQExpBufferStr(pgdumpopts, " -a");
260 0 : break;
261 :
262 2 : case 'c':
263 2 : output_clean = true;
264 2 : break;
265 :
266 18 : case 'd':
267 18 : connstr = pg_strdup(optarg);
268 18 : break;
269 :
270 0 : case 'E':
271 0 : dumpencoding = pg_strdup(optarg);
272 0 : appendPQExpBufferStr(pgdumpopts, " -E ");
273 0 : appendShellString(pgdumpopts, optarg);
274 0 : break;
275 :
276 80 : case 'f':
277 80 : filename = pg_strdup(optarg);
278 80 : appendPQExpBufferStr(pgdumpopts, " -f ");
279 80 : appendShellString(pgdumpopts, filename);
280 80 : break;
281 18 : case 'F':
282 18 : formatName = pg_strdup(optarg);
283 18 : break;
284 36 : case 'g':
285 36 : globals_only = true;
286 36 : break;
287 :
288 20 : case 'h':
289 20 : pghost = pg_strdup(optarg);
290 20 : break;
291 :
292 0 : case 'l':
293 0 : pgdb = pg_strdup(optarg);
294 0 : break;
295 :
296 0 : case 'O':
297 0 : appendPQExpBufferStr(pgdumpopts, " -O");
298 0 : break;
299 :
300 36 : case 'p':
301 36 : pgport = pg_strdup(optarg);
302 36 : break;
303 :
304 14 : case 'r':
305 14 : roles_only = true;
306 14 : break;
307 :
308 0 : case 's':
309 0 : appendPQExpBufferStr(pgdumpopts, " -s");
310 0 : break;
311 :
312 0 : case 'S':
313 0 : appendPQExpBufferStr(pgdumpopts, " -S ");
314 0 : appendShellString(pgdumpopts, optarg);
315 0 : break;
316 :
317 4 : case 't':
318 4 : tablespaces_only = true;
319 4 : break;
320 :
321 34 : case 'U':
322 34 : pguser = pg_strdup(optarg);
323 34 : break;
324 :
325 4 : case 'v':
326 4 : verbose = true;
327 4 : pg_logging_increase_verbosity();
328 4 : appendPQExpBufferStr(pgdumpopts, " -v");
329 4 : break;
330 :
331 0 : case 'w':
332 0 : prompt_password = TRI_NO;
333 0 : appendPQExpBufferStr(pgdumpopts, " -w");
334 0 : break;
335 :
336 0 : case 'W':
337 0 : prompt_password = TRI_YES;
338 0 : appendPQExpBufferStr(pgdumpopts, " -W");
339 0 : break;
340 :
341 0 : case 'x':
342 0 : skip_acls = true;
343 0 : appendPQExpBufferStr(pgdumpopts, " -x");
344 0 : break;
345 :
346 52 : case 0:
347 52 : break;
348 :
349 0 : case 2:
350 0 : appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
351 0 : appendShellString(pgdumpopts, optarg);
352 0 : break;
353 :
354 0 : case 3:
355 0 : use_role = pg_strdup(optarg);
356 0 : appendPQExpBufferStr(pgdumpopts, " --role ");
357 0 : appendShellString(pgdumpopts, use_role);
358 0 : break;
359 :
360 54 : case 4:
361 54 : dosync = false;
362 54 : appendPQExpBufferStr(pgdumpopts, " --no-sync");
363 54 : break;
364 :
365 0 : case 5:
366 0 : appendPQExpBufferStr(pgdumpopts, " --extra-float-digits ");
367 0 : appendShellString(pgdumpopts, optarg);
368 0 : break;
369 :
370 12 : case 6:
371 12 : simple_string_list_append(&database_exclude_patterns, optarg);
372 12 : break;
373 :
374 0 : case 7:
375 0 : appendPQExpBufferStr(pgdumpopts, " --rows-per-insert ");
376 0 : appendShellString(pgdumpopts, optarg);
377 0 : break;
378 :
379 10 : case 8:
380 10 : read_dumpall_filters(optarg, &database_exclude_patterns);
381 4 : break;
382 :
383 2 : default:
384 : /* getopt_long already emitted a complaint */
385 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
386 2 : exit_nicely(1);
387 : }
388 : }
389 :
390 : /* Complain if any arguments remain */
391 96 : if (optind < argc)
392 : {
393 2 : pg_log_error("too many command-line arguments (first is \"%s\")",
394 : argv[optind]);
395 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
396 2 : exit_nicely(1);
397 : }
398 :
399 94 : if (database_exclude_patterns.head != NULL &&
400 12 : (globals_only || roles_only || tablespaces_only))
401 : {
402 4 : pg_log_error("option --exclude-database cannot be used together with -g/--globals-only, -r/--roles-only, or -t/--tablespaces-only");
403 4 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
404 4 : exit_nicely(1);
405 : }
406 :
407 : /* Make sure the user hasn't specified a mix of globals-only options */
408 90 : if (globals_only && roles_only)
409 : {
410 2 : pg_log_error("options -g/--globals-only and -r/--roles-only cannot be used together");
411 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
412 2 : exit_nicely(1);
413 : }
414 :
415 88 : if (globals_only && tablespaces_only)
416 : {
417 2 : pg_log_error("options -g/--globals-only and -t/--tablespaces-only cannot be used together");
418 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
419 2 : exit_nicely(1);
420 : }
421 :
422 86 : if (if_exists && !output_clean)
423 2 : pg_fatal("option --if-exists requires option -c/--clean");
424 :
425 84 : if (roles_only && tablespaces_only)
426 : {
427 2 : pg_log_error("options -r/--roles-only and -t/--tablespaces-only cannot be used together");
428 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
429 2 : exit_nicely(1);
430 : }
431 :
432 : /* Get format for dump. */
433 82 : archDumpFormat = parseDumpFormat(formatName);
434 :
435 : /*
436 : * If a non-plain format is specified, a file name is also required as the
437 : * path to the main directory.
438 : */
439 80 : if (archDumpFormat != archNull &&
440 16 : (!filename || strcmp(filename, "") == 0))
441 : {
442 0 : pg_log_error("option -F/--format=d|c|t requires option -f/--file");
443 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
444 0 : exit_nicely(1);
445 : }
446 :
447 : /*
448 : * If password values are not required in the dump, switch to using
449 : * pg_roles which is equally useful, just more likely to have unrestricted
450 : * access than pg_authid.
451 : */
452 80 : if (no_role_passwords)
453 0 : sprintf(role_catalog, "%s", PG_ROLES);
454 : else
455 80 : sprintf(role_catalog, "%s", PG_AUTHID);
456 :
457 : /* Add long options to the pg_dump argument list */
458 80 : if (binary_upgrade)
459 20 : appendPQExpBufferStr(pgdumpopts, " --binary-upgrade");
460 80 : if (column_inserts)
461 0 : appendPQExpBufferStr(pgdumpopts, " --column-inserts");
462 80 : if (disable_dollar_quoting)
463 0 : appendPQExpBufferStr(pgdumpopts, " --disable-dollar-quoting");
464 80 : if (disable_triggers)
465 0 : appendPQExpBufferStr(pgdumpopts, " --disable-triggers");
466 80 : if (inserts)
467 0 : appendPQExpBufferStr(pgdumpopts, " --inserts");
468 80 : if (no_table_access_method)
469 0 : appendPQExpBufferStr(pgdumpopts, " --no-table-access-method");
470 80 : if (no_tablespaces)
471 0 : appendPQExpBufferStr(pgdumpopts, " --no-tablespaces");
472 80 : if (quote_all_identifiers)
473 20 : appendPQExpBufferStr(pgdumpopts, " --quote-all-identifiers");
474 80 : if (load_via_partition_root)
475 0 : appendPQExpBufferStr(pgdumpopts, " --load-via-partition-root");
476 80 : if (use_setsessauth)
477 0 : appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
478 80 : if (no_comments)
479 0 : appendPQExpBufferStr(pgdumpopts, " --no-comments");
480 80 : if (no_data)
481 0 : appendPQExpBufferStr(pgdumpopts, " --no-data");
482 80 : if (no_policies)
483 0 : appendPQExpBufferStr(pgdumpopts, " --no-policies");
484 80 : if (no_publications)
485 0 : appendPQExpBufferStr(pgdumpopts, " --no-publications");
486 80 : if (no_security_labels)
487 0 : appendPQExpBufferStr(pgdumpopts, " --no-security-labels");
488 80 : if (no_schema)
489 0 : appendPQExpBufferStr(pgdumpopts, " --no-schema");
490 80 : if (no_statistics)
491 4 : appendPQExpBufferStr(pgdumpopts, " --no-statistics");
492 80 : if (no_subscriptions)
493 0 : appendPQExpBufferStr(pgdumpopts, " --no-subscriptions");
494 80 : if (no_toast_compression)
495 0 : appendPQExpBufferStr(pgdumpopts, " --no-toast-compression");
496 80 : if (no_unlogged_table_data)
497 6 : appendPQExpBufferStr(pgdumpopts, " --no-unlogged-table-data");
498 80 : if (with_data)
499 0 : appendPQExpBufferStr(pgdumpopts, " --with-data");
500 80 : if (with_schema)
501 0 : appendPQExpBufferStr(pgdumpopts, " --with-schema");
502 80 : if (with_statistics)
503 0 : appendPQExpBufferStr(pgdumpopts, " --with-statistics");
504 80 : if (on_conflict_do_nothing)
505 0 : appendPQExpBufferStr(pgdumpopts, " --on-conflict-do-nothing");
506 80 : if (statistics_only)
507 0 : appendPQExpBufferStr(pgdumpopts, " --statistics-only");
508 :
509 : /*
510 : * Open the output file if required, otherwise use stdout. If required,
511 : * then create new directory and global.dat file.
512 : */
513 80 : if (archDumpFormat != archNull)
514 : {
515 : char global_path[MAXPGPATH];
516 :
517 : /* Create new directory or accept the empty existing directory. */
518 16 : create_or_open_dir(filename);
519 :
520 16 : snprintf(global_path, MAXPGPATH, "%s/global.dat", filename);
521 :
522 16 : OPF = fopen(global_path, PG_BINARY_W);
523 16 : if (!OPF)
524 0 : pg_fatal("could not open \"%s\": %m", global_path);
525 : }
526 64 : else if (filename)
527 : {
528 56 : OPF = fopen(filename, PG_BINARY_W);
529 56 : if (!OPF)
530 0 : pg_fatal("could not open output file \"%s\": %m",
531 : filename);
532 : }
533 : else
534 8 : OPF = stdout;
535 :
536 : /*
537 : * If there was a database specified on the command line, use that,
538 : * otherwise try to connect to database "postgres", and failing that
539 : * "template1".
540 : */
541 80 : if (pgdb)
542 : {
543 0 : conn = ConnectDatabase(pgdb, connstr, pghost, pgport, pguser,
544 : prompt_password, false,
545 : progname, &connstr, &server_version, NULL, NULL);
546 :
547 0 : if (!conn)
548 0 : pg_fatal("could not connect to database \"%s\"", pgdb);
549 : }
550 : else
551 : {
552 80 : conn = ConnectDatabase("postgres", connstr, pghost, pgport, pguser,
553 : prompt_password, false,
554 : progname, &connstr, &server_version, NULL, NULL);
555 80 : if (!conn)
556 0 : conn = ConnectDatabase("template1", connstr, pghost, pgport, pguser,
557 : prompt_password, true,
558 : progname, &connstr, &server_version, NULL, NULL);
559 :
560 80 : if (!conn)
561 : {
562 0 : pg_log_error("could not connect to databases \"postgres\" or \"template1\"\n"
563 : "Please specify an alternative database.");
564 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
565 0 : exit_nicely(1);
566 : }
567 : }
568 :
569 : /*
570 : * Get a list of database names that match the exclude patterns
571 : */
572 80 : expand_dbname_patterns(conn, &database_exclude_patterns,
573 : &database_exclude_names);
574 :
575 : /*
576 : * Set the client encoding if requested.
577 : */
578 76 : if (dumpencoding)
579 : {
580 0 : if (PQsetClientEncoding(conn, dumpencoding) < 0)
581 0 : pg_fatal("invalid client encoding \"%s\" specified",
582 : dumpencoding);
583 : }
584 :
585 : /*
586 : * Get the active encoding and the standard_conforming_strings setting, so
587 : * we know how to escape strings.
588 : */
589 76 : encoding = PQclientEncoding(conn);
590 76 : setFmtEncoding(encoding);
591 76 : std_strings = PQparameterStatus(conn, "standard_conforming_strings");
592 76 : if (!std_strings)
593 0 : std_strings = "off";
594 :
595 : /* Set the role if requested */
596 76 : if (use_role)
597 : {
598 0 : PQExpBuffer query = createPQExpBuffer();
599 :
600 0 : appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
601 0 : executeCommand(conn, query->data);
602 0 : destroyPQExpBuffer(query);
603 : }
604 :
605 : /* Force quoting of all identifiers if requested. */
606 76 : if (quote_all_identifiers)
607 20 : executeCommand(conn, "SET quote_all_identifiers = true");
608 :
609 76 : fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
610 76 : if (verbose)
611 4 : dumpTimestamp("Started on");
612 :
613 : /*
614 : * We used to emit \connect postgres here, but that served no purpose
615 : * other than to break things for installations without a postgres
616 : * database. Everything we're restoring here is a global, so whichever
617 : * database we're connected to at the moment is fine.
618 : */
619 :
620 : /* Restore will need to write to the target cluster */
621 76 : fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
622 :
623 : /* Replicate encoding and std_strings in output */
624 76 : fprintf(OPF, "SET client_encoding = '%s';\n",
625 : pg_encoding_to_char(encoding));
626 76 : fprintf(OPF, "SET standard_conforming_strings = %s;\n", std_strings);
627 76 : if (strcmp(std_strings, "off") == 0)
628 0 : fprintf(OPF, "SET escape_string_warning = off;\n");
629 76 : fprintf(OPF, "\n");
630 :
631 76 : if (!data_only)
632 : {
633 : /*
634 : * If asked to --clean, do that first. We can avoid detailed
635 : * dependency analysis because databases never depend on each other,
636 : * and tablespaces never depend on each other. Roles could have
637 : * grants to each other, but DROP ROLE will clean those up silently.
638 : */
639 76 : if (output_clean)
640 : {
641 2 : if (!globals_only && !roles_only && !tablespaces_only)
642 0 : dropDBs(conn);
643 :
644 2 : if (!roles_only && !no_tablespaces)
645 2 : dropTablespaces(conn);
646 :
647 2 : if (!tablespaces_only)
648 2 : dropRoles(conn);
649 : }
650 :
651 : /*
652 : * Now create objects as requested. Be careful that option logic here
653 : * is the same as for drops above.
654 : */
655 76 : if (!tablespaces_only)
656 : {
657 : /* Dump roles (users) */
658 76 : dumpRoles(conn);
659 :
660 : /* Dump role memberships */
661 76 : dumpRoleMembership(conn);
662 :
663 : /* Dump role GUC privileges */
664 76 : if (server_version >= 150000 && !skip_acls)
665 76 : dumpRoleGUCPrivs(conn);
666 : }
667 :
668 : /* Dump tablespaces */
669 76 : if (!roles_only && !no_tablespaces)
670 66 : dumpTablespaces(conn);
671 : }
672 :
673 76 : if (!globals_only && !roles_only && !tablespaces_only)
674 38 : dumpDatabases(conn, archDumpFormat);
675 :
676 74 : PQfinish(conn);
677 :
678 74 : if (verbose)
679 4 : dumpTimestamp("Completed on");
680 74 : fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
681 :
682 74 : if (filename)
683 : {
684 70 : fclose(OPF);
685 :
686 : /* sync the resulting file, errors are not fatal */
687 70 : if (dosync && (archDumpFormat == archNull))
688 4 : (void) fsync_fname(filename, false);
689 : }
690 :
691 74 : exit_nicely(0);
692 : }
693 :
694 :
695 : static void
696 2 : help(void)
697 : {
698 2 : printf(_("%s extracts a PostgreSQL database cluster based on specified dump format.\n\n"), progname);
699 2 : printf(_("Usage:\n"));
700 2 : printf(_(" %s [OPTION]...\n"), progname);
701 :
702 2 : printf(_("\nGeneral options:\n"));
703 2 : printf(_(" -f, --file=FILENAME output file name\n"));
704 2 : printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
705 : " plain text (default))\n"));
706 2 : printf(_(" -v, --verbose verbose mode\n"));
707 2 : printf(_(" -V, --version output version information, then exit\n"));
708 2 : printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
709 2 : printf(_(" -?, --help show this help, then exit\n"));
710 2 : printf(_("\nOptions controlling the output content:\n"));
711 2 : printf(_(" -a, --data-only dump only the data, not the schema or statistics\n"));
712 2 : printf(_(" -c, --clean clean (drop) databases before recreating\n"));
713 2 : printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
714 2 : printf(_(" -g, --globals-only dump only global objects, no databases\n"));
715 2 : printf(_(" -O, --no-owner skip restoration of object ownership\n"));
716 2 : printf(_(" -r, --roles-only dump only roles, no databases or tablespaces\n"));
717 2 : printf(_(" -s, --schema-only dump only the schema, no data or statistics\n"));
718 2 : printf(_(" -S, --superuser=NAME superuser user name to use in the dump\n"));
719 2 : printf(_(" -t, --tablespaces-only dump only tablespaces, no databases or roles\n"));
720 2 : printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
721 2 : printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
722 2 : printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
723 2 : printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
724 2 : printf(_(" --disable-triggers disable triggers during data-only restore\n"));
725 2 : printf(_(" --exclude-database=PATTERN exclude databases whose name matches PATTERN\n"));
726 2 : printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
727 2 : printf(_(" --filter=FILENAME exclude databases based on expressions in FILENAME\n"));
728 2 : printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
729 2 : printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
730 2 : printf(_(" --load-via-partition-root load partitions via the root table\n"));
731 2 : printf(_(" --no-comments do not dump comment commands\n"));
732 2 : printf(_(" --no-data do not dump data\n"));
733 2 : printf(_(" --no-policies do not dump row security policies\n"));
734 2 : printf(_(" --no-publications do not dump publications\n"));
735 2 : printf(_(" --no-role-passwords do not dump passwords for roles\n"));
736 2 : printf(_(" --no-schema do not dump schema\n"));
737 2 : printf(_(" --no-security-labels do not dump security label assignments\n"));
738 2 : printf(_(" --no-statistics do not dump statistics\n"));
739 2 : printf(_(" --no-subscriptions do not dump subscriptions\n"));
740 2 : printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
741 2 : printf(_(" --no-table-access-method do not dump table access methods\n"));
742 2 : printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
743 2 : printf(_(" --no-toast-compression do not dump TOAST compression methods\n"));
744 2 : printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
745 2 : printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
746 2 : printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
747 2 : printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
748 2 : printf(_(" --statistics-only dump only the statistics, not schema or data\n"));
749 2 : printf(_(" --use-set-session-authorization\n"
750 : " use SET SESSION AUTHORIZATION commands instead of\n"
751 : " ALTER OWNER commands to set ownership\n"));
752 2 : printf(_(" --with-data dump the data\n"));
753 2 : printf(_(" --with-schema dump the schema\n"));
754 2 : printf(_(" --with-statistics dump the statistics\n"));
755 :
756 2 : printf(_("\nConnection options:\n"));
757 2 : printf(_(" -d, --dbname=CONNSTR connect using connection string\n"));
758 2 : printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
759 2 : printf(_(" -l, --database=DBNAME alternative default database\n"));
760 2 : printf(_(" -p, --port=PORT database server port number\n"));
761 2 : printf(_(" -U, --username=NAME connect as specified database user\n"));
762 2 : printf(_(" -w, --no-password never prompt for password\n"));
763 2 : printf(_(" -W, --password force password prompt (should happen automatically)\n"));
764 2 : printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
765 :
766 2 : printf(_("\nIf -f/--file is not used, then the SQL script will be written to the standard\n"
767 : "output.\n\n"));
768 2 : printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
769 2 : printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
770 2 : }
771 :
772 :
773 : /*
774 : * Drop roles
775 : */
776 : static void
777 2 : dropRoles(PGconn *conn)
778 : {
779 2 : PQExpBuffer buf = createPQExpBuffer();
780 : PGresult *res;
781 : int i_rolname;
782 : int i;
783 :
784 2 : if (server_version >= 90600)
785 2 : printfPQExpBuffer(buf,
786 : "SELECT rolname "
787 : "FROM %s "
788 : "WHERE rolname !~ '^pg_' "
789 : "ORDER BY 1", role_catalog);
790 : else
791 0 : printfPQExpBuffer(buf,
792 : "SELECT rolname "
793 : "FROM %s "
794 : "ORDER BY 1", role_catalog);
795 :
796 2 : res = executeQuery(conn, buf->data);
797 :
798 2 : i_rolname = PQfnumber(res, "rolname");
799 :
800 2 : if (PQntuples(res) > 0)
801 2 : fprintf(OPF, "--\n-- Drop roles\n--\n\n");
802 :
803 8 : for (i = 0; i < PQntuples(res); i++)
804 : {
805 : const char *rolename;
806 :
807 6 : rolename = PQgetvalue(res, i, i_rolname);
808 :
809 12 : fprintf(OPF, "DROP ROLE %s%s;\n",
810 6 : if_exists ? "IF EXISTS " : "",
811 : fmtId(rolename));
812 : }
813 :
814 2 : PQclear(res);
815 2 : destroyPQExpBuffer(buf);
816 :
817 2 : fprintf(OPF, "\n\n");
818 2 : }
819 :
820 : /*
821 : * Dump roles
822 : */
823 : static void
824 76 : dumpRoles(PGconn *conn)
825 : {
826 76 : PQExpBuffer buf = createPQExpBuffer();
827 : PGresult *res;
828 : int i_oid,
829 : i_rolname,
830 : i_rolsuper,
831 : i_rolinherit,
832 : i_rolcreaterole,
833 : i_rolcreatedb,
834 : i_rolcanlogin,
835 : i_rolconnlimit,
836 : i_rolpassword,
837 : i_rolvaliduntil,
838 : i_rolreplication,
839 : i_rolbypassrls,
840 : i_rolcomment,
841 : i_is_current_user;
842 : int i;
843 :
844 : /*
845 : * Notes: rolconfig is dumped later, and pg_authid must be used for
846 : * extracting rolcomment regardless of role_catalog.
847 : */
848 76 : if (server_version >= 90600)
849 76 : printfPQExpBuffer(buf,
850 : "SELECT oid, rolname, rolsuper, rolinherit, "
851 : "rolcreaterole, rolcreatedb, "
852 : "rolcanlogin, rolconnlimit, rolpassword, "
853 : "rolvaliduntil, rolreplication, rolbypassrls, "
854 : "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
855 : "rolname = current_user AS is_current_user "
856 : "FROM %s "
857 : "WHERE rolname !~ '^pg_' "
858 : "ORDER BY 2", role_catalog);
859 0 : else if (server_version >= 90500)
860 0 : printfPQExpBuffer(buf,
861 : "SELECT oid, rolname, rolsuper, rolinherit, "
862 : "rolcreaterole, rolcreatedb, "
863 : "rolcanlogin, rolconnlimit, rolpassword, "
864 : "rolvaliduntil, rolreplication, rolbypassrls, "
865 : "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
866 : "rolname = current_user AS is_current_user "
867 : "FROM %s "
868 : "ORDER BY 2", role_catalog);
869 : else
870 0 : printfPQExpBuffer(buf,
871 : "SELECT oid, rolname, rolsuper, rolinherit, "
872 : "rolcreaterole, rolcreatedb, "
873 : "rolcanlogin, rolconnlimit, rolpassword, "
874 : "rolvaliduntil, rolreplication, "
875 : "false as rolbypassrls, "
876 : "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
877 : "rolname = current_user AS is_current_user "
878 : "FROM %s "
879 : "ORDER BY 2", role_catalog);
880 :
881 76 : res = executeQuery(conn, buf->data);
882 :
883 76 : i_oid = PQfnumber(res, "oid");
884 76 : i_rolname = PQfnumber(res, "rolname");
885 76 : i_rolsuper = PQfnumber(res, "rolsuper");
886 76 : i_rolinherit = PQfnumber(res, "rolinherit");
887 76 : i_rolcreaterole = PQfnumber(res, "rolcreaterole");
888 76 : i_rolcreatedb = PQfnumber(res, "rolcreatedb");
889 76 : i_rolcanlogin = PQfnumber(res, "rolcanlogin");
890 76 : i_rolconnlimit = PQfnumber(res, "rolconnlimit");
891 76 : i_rolpassword = PQfnumber(res, "rolpassword");
892 76 : i_rolvaliduntil = PQfnumber(res, "rolvaliduntil");
893 76 : i_rolreplication = PQfnumber(res, "rolreplication");
894 76 : i_rolbypassrls = PQfnumber(res, "rolbypassrls");
895 76 : i_rolcomment = PQfnumber(res, "rolcomment");
896 76 : i_is_current_user = PQfnumber(res, "is_current_user");
897 :
898 76 : if (PQntuples(res) > 0)
899 76 : fprintf(OPF, "--\n-- Roles\n--\n\n");
900 :
901 424 : for (i = 0; i < PQntuples(res); i++)
902 : {
903 : const char *rolename;
904 : Oid auth_oid;
905 :
906 348 : auth_oid = atooid(PQgetvalue(res, i, i_oid));
907 348 : rolename = PQgetvalue(res, i, i_rolname);
908 :
909 348 : if (strncmp(rolename, "pg_", 3) == 0)
910 : {
911 0 : pg_log_warning("role name starting with \"pg_\" skipped (%s)",
912 : rolename);
913 0 : continue;
914 : }
915 :
916 348 : resetPQExpBuffer(buf);
917 :
918 348 : if (binary_upgrade)
919 : {
920 20 : appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_authid.oid\n");
921 20 : appendPQExpBuffer(buf,
922 : "SELECT pg_catalog.binary_upgrade_set_next_pg_authid_oid('%u'::pg_catalog.oid);\n\n",
923 : auth_oid);
924 : }
925 :
926 : /*
927 : * We dump CREATE ROLE followed by ALTER ROLE to ensure that the role
928 : * will acquire the right properties even if it already exists (ie, it
929 : * won't hurt for the CREATE to fail). This is particularly important
930 : * for the role we are connected as, since even with --clean we will
931 : * have failed to drop it. binary_upgrade cannot generate any errors,
932 : * so we assume the current role is already created.
933 : */
934 348 : if (!binary_upgrade ||
935 20 : strcmp(PQgetvalue(res, i, i_is_current_user), "f") == 0)
936 328 : appendPQExpBuffer(buf, "CREATE ROLE %s;\n", fmtId(rolename));
937 348 : appendPQExpBuffer(buf, "ALTER ROLE %s WITH", fmtId(rolename));
938 :
939 348 : if (strcmp(PQgetvalue(res, i, i_rolsuper), "t") == 0)
940 148 : appendPQExpBufferStr(buf, " SUPERUSER");
941 : else
942 200 : appendPQExpBufferStr(buf, " NOSUPERUSER");
943 :
944 348 : if (strcmp(PQgetvalue(res, i, i_rolinherit), "t") == 0)
945 348 : appendPQExpBufferStr(buf, " INHERIT");
946 : else
947 0 : appendPQExpBufferStr(buf, " NOINHERIT");
948 :
949 348 : if (strcmp(PQgetvalue(res, i, i_rolcreaterole), "t") == 0)
950 132 : appendPQExpBufferStr(buf, " CREATEROLE");
951 : else
952 216 : appendPQExpBufferStr(buf, " NOCREATEROLE");
953 :
954 348 : if (strcmp(PQgetvalue(res, i, i_rolcreatedb), "t") == 0)
955 132 : appendPQExpBufferStr(buf, " CREATEDB");
956 : else
957 216 : appendPQExpBufferStr(buf, " NOCREATEDB");
958 :
959 348 : if (strcmp(PQgetvalue(res, i, i_rolcanlogin), "t") == 0)
960 134 : appendPQExpBufferStr(buf, " LOGIN");
961 : else
962 214 : appendPQExpBufferStr(buf, " NOLOGIN");
963 :
964 348 : if (strcmp(PQgetvalue(res, i, i_rolreplication), "t") == 0)
965 92 : appendPQExpBufferStr(buf, " REPLICATION");
966 : else
967 256 : appendPQExpBufferStr(buf, " NOREPLICATION");
968 :
969 348 : if (strcmp(PQgetvalue(res, i, i_rolbypassrls), "t") == 0)
970 76 : appendPQExpBufferStr(buf, " BYPASSRLS");
971 : else
972 272 : appendPQExpBufferStr(buf, " NOBYPASSRLS");
973 :
974 348 : if (strcmp(PQgetvalue(res, i, i_rolconnlimit), "-1") != 0)
975 16 : appendPQExpBuffer(buf, " CONNECTION LIMIT %s",
976 : PQgetvalue(res, i, i_rolconnlimit));
977 :
978 :
979 348 : if (!PQgetisnull(res, i, i_rolpassword) && !no_role_passwords)
980 : {
981 16 : appendPQExpBufferStr(buf, " PASSWORD ");
982 16 : appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolpassword), conn);
983 : }
984 :
985 348 : if (!PQgetisnull(res, i, i_rolvaliduntil))
986 0 : appendPQExpBuffer(buf, " VALID UNTIL '%s'",
987 : PQgetvalue(res, i, i_rolvaliduntil));
988 :
989 348 : appendPQExpBufferStr(buf, ";\n");
990 :
991 348 : if (!no_comments && !PQgetisnull(res, i, i_rolcomment))
992 : {
993 0 : appendPQExpBuffer(buf, "COMMENT ON ROLE %s IS ", fmtId(rolename));
994 0 : appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolcomment), conn);
995 0 : appendPQExpBufferStr(buf, ";\n");
996 : }
997 :
998 348 : if (!no_security_labels)
999 348 : buildShSecLabels(conn, "pg_authid", auth_oid,
1000 : "ROLE", rolename,
1001 : buf);
1002 :
1003 348 : fprintf(OPF, "%s", buf->data);
1004 : }
1005 :
1006 : /*
1007 : * Dump configuration settings for roles after all roles have been dumped.
1008 : * We do it this way because config settings for roles could mention the
1009 : * names of other roles.
1010 : */
1011 424 : for (i = 0; i < PQntuples(res); i++)
1012 348 : dumpUserConfig(conn, PQgetvalue(res, i, i_rolname));
1013 :
1014 76 : PQclear(res);
1015 :
1016 76 : fprintf(OPF, "\n\n");
1017 :
1018 76 : destroyPQExpBuffer(buf);
1019 76 : }
1020 :
1021 :
1022 : /*
1023 : * Dump role memberships.
1024 : *
1025 : * Note: we expect dumpRoles already created all the roles, but there is
1026 : * no membership yet.
1027 : */
1028 : static void
1029 76 : dumpRoleMembership(PGconn *conn)
1030 : {
1031 76 : PQExpBuffer buf = createPQExpBuffer();
1032 76 : PQExpBuffer optbuf = createPQExpBuffer();
1033 : PGresult *res;
1034 76 : int start = 0,
1035 : end,
1036 : total;
1037 : bool dump_grantors;
1038 : bool dump_grant_options;
1039 : int i_role;
1040 : int i_member;
1041 : int i_grantor;
1042 : int i_roleid;
1043 : int i_memberid;
1044 : int i_grantorid;
1045 : int i_admin_option;
1046 : int i_inherit_option;
1047 : int i_set_option;
1048 :
1049 : /*
1050 : * Previous versions of PostgreSQL didn't used to track the grantor very
1051 : * carefully in the backend, and the grantor could be any user even if
1052 : * they didn't have ADMIN OPTION on the role, or a user that no longer
1053 : * existed. To avoid dump and restore failures, don't dump the grantor
1054 : * when talking to an old server version.
1055 : *
1056 : * Also, in older versions the roleid and/or member could be role OIDs
1057 : * that no longer exist. If we find such cases, print a warning and skip
1058 : * the entry.
1059 : */
1060 76 : dump_grantors = (PQserverVersion(conn) >= 160000);
1061 :
1062 : /*
1063 : * Previous versions of PostgreSQL also did not have grant-level options.
1064 : */
1065 76 : dump_grant_options = (server_version >= 160000);
1066 :
1067 : /* Generate and execute query. */
1068 76 : printfPQExpBuffer(buf, "SELECT ur.rolname AS role, "
1069 : "um.rolname AS member, "
1070 : "ug.rolname AS grantor, "
1071 : "a.roleid AS roleid, "
1072 : "a.member AS memberid, "
1073 : "a.grantor AS grantorid, "
1074 : "a.admin_option");
1075 76 : if (dump_grant_options)
1076 76 : appendPQExpBufferStr(buf, ", a.inherit_option, a.set_option");
1077 76 : appendPQExpBuffer(buf, " FROM pg_auth_members a "
1078 : "LEFT JOIN %s ur on ur.oid = a.roleid "
1079 : "LEFT JOIN %s um on um.oid = a.member "
1080 : "LEFT JOIN %s ug on ug.oid = a.grantor "
1081 : "WHERE NOT (ur.rolname ~ '^pg_' AND um.rolname ~ '^pg_')"
1082 : "ORDER BY 1,2,3", role_catalog, role_catalog, role_catalog);
1083 76 : res = executeQuery(conn, buf->data);
1084 76 : i_role = PQfnumber(res, "role");
1085 76 : i_member = PQfnumber(res, "member");
1086 76 : i_grantor = PQfnumber(res, "grantor");
1087 76 : i_roleid = PQfnumber(res, "roleid");
1088 76 : i_memberid = PQfnumber(res, "memberid");
1089 76 : i_grantorid = PQfnumber(res, "grantorid");
1090 76 : i_admin_option = PQfnumber(res, "admin_option");
1091 76 : i_inherit_option = PQfnumber(res, "inherit_option");
1092 76 : i_set_option = PQfnumber(res, "set_option");
1093 :
1094 76 : if (PQntuples(res) > 0)
1095 16 : fprintf(OPF, "--\n-- Role memberships\n--\n\n");
1096 :
1097 : /*
1098 : * We can't dump these GRANT commands in arbitrary order, because a role
1099 : * that is named as a grantor must already have ADMIN OPTION on the role
1100 : * for which it is granting permissions, except for the bootstrap
1101 : * superuser, who can always be named as the grantor.
1102 : *
1103 : * We handle this by considering these grants role by role. For each role,
1104 : * we initially consider the only allowable grantor to be the bootstrap
1105 : * superuser. Every time we grant ADMIN OPTION on the role to some user,
1106 : * that user also becomes an allowable grantor. We make repeated passes
1107 : * over the grants for the role, each time dumping those whose grantors
1108 : * are allowable and which we haven't done yet. Eventually this should let
1109 : * us dump all the grants.
1110 : */
1111 76 : total = PQntuples(res);
1112 92 : while (start < total)
1113 : {
1114 16 : char *role = PQgetvalue(res, start, i_role);
1115 : int i;
1116 : bool *done;
1117 : int remaining;
1118 16 : int prev_remaining = 0;
1119 : rolename_hash *ht;
1120 :
1121 : /* If we hit a null roleid, we're done (nulls sort to the end). */
1122 16 : if (PQgetisnull(res, start, i_role))
1123 : {
1124 : /* translator: %s represents a numeric role OID */
1125 0 : pg_log_warning("found orphaned pg_auth_members entry for role %s",
1126 : PQgetvalue(res, start, i_roleid));
1127 0 : break;
1128 : }
1129 :
1130 : /* All memberships for a single role should be adjacent. */
1131 32 : for (end = start; end < total; ++end)
1132 : {
1133 : char *otherrole;
1134 :
1135 16 : otherrole = PQgetvalue(res, end, i_role);
1136 16 : if (strcmp(role, otherrole) != 0)
1137 0 : break;
1138 : }
1139 :
1140 16 : remaining = end - start;
1141 16 : done = pg_malloc0(remaining * sizeof(bool));
1142 16 : ht = rolename_create(remaining, NULL);
1143 :
1144 : /*
1145 : * Make repeated passes over the grants for this role until all have
1146 : * been dumped.
1147 : */
1148 32 : while (remaining > 0)
1149 : {
1150 : /*
1151 : * We should make progress on every iteration, because a notional
1152 : * graph whose vertices are grants and whose edges point from
1153 : * grantors to members should be connected and acyclic. If we fail
1154 : * to make progress, either we or the server have messed up.
1155 : */
1156 16 : if (remaining == prev_remaining)
1157 : {
1158 0 : pg_log_error("could not find a legal dump ordering for memberships in role \"%s\"",
1159 : role);
1160 0 : PQfinish(conn);
1161 0 : exit_nicely(1);
1162 : }
1163 16 : prev_remaining = remaining;
1164 :
1165 : /* Make one pass over the grants for this role. */
1166 32 : for (i = start; i < end; ++i)
1167 : {
1168 : char *member;
1169 : char *admin_option;
1170 : char *grantorid;
1171 : char *grantor;
1172 16 : char *set_option = "true";
1173 : bool found;
1174 :
1175 : /* If we already did this grant, don't do it again. */
1176 16 : if (done[i - start])
1177 0 : continue;
1178 :
1179 : /* Complain about, then ignore, entries with orphaned OIDs. */
1180 16 : if (PQgetisnull(res, i, i_member))
1181 : {
1182 : /* translator: %s represents a numeric role OID */
1183 0 : pg_log_warning("found orphaned pg_auth_members entry for role %s",
1184 : PQgetvalue(res, i, i_memberid));
1185 0 : done[i - start] = true;
1186 0 : --remaining;
1187 0 : continue;
1188 : }
1189 16 : if (PQgetisnull(res, i, i_grantor))
1190 : {
1191 : /* translator: %s represents a numeric role OID */
1192 0 : pg_log_warning("found orphaned pg_auth_members entry for role %s",
1193 : PQgetvalue(res, i, i_grantorid));
1194 0 : done[i - start] = true;
1195 0 : --remaining;
1196 0 : continue;
1197 : }
1198 :
1199 16 : member = PQgetvalue(res, i, i_member);
1200 16 : grantor = PQgetvalue(res, i, i_grantor);
1201 16 : grantorid = PQgetvalue(res, i, i_grantorid);
1202 16 : admin_option = PQgetvalue(res, i, i_admin_option);
1203 16 : if (dump_grant_options)
1204 16 : set_option = PQgetvalue(res, i, i_set_option);
1205 :
1206 : /*
1207 : * If we're not dumping grantors or if the grantor is the
1208 : * bootstrap superuser, it's fine to dump this now. Otherwise,
1209 : * it's got to be someone who has already been granted ADMIN
1210 : * OPTION.
1211 : */
1212 16 : if (dump_grantors &&
1213 16 : atooid(grantorid) != BOOTSTRAP_SUPERUSERID &&
1214 0 : rolename_lookup(ht, grantor) == NULL)
1215 0 : continue;
1216 :
1217 : /* Remember that we did this so that we don't do it again. */
1218 16 : done[i - start] = true;
1219 16 : --remaining;
1220 :
1221 : /*
1222 : * If ADMIN OPTION is being granted, remember that grants
1223 : * listing this member as the grantor can now be dumped.
1224 : */
1225 16 : if (*admin_option == 't')
1226 0 : rolename_insert(ht, member, &found);
1227 :
1228 : /* Generate the actual GRANT statement. */
1229 16 : resetPQExpBuffer(optbuf);
1230 16 : fprintf(OPF, "GRANT %s", fmtId(role));
1231 16 : fprintf(OPF, " TO %s", fmtId(member));
1232 16 : if (*admin_option == 't')
1233 0 : appendPQExpBufferStr(optbuf, "ADMIN OPTION");
1234 16 : if (dump_grant_options)
1235 : {
1236 : char *inherit_option;
1237 :
1238 16 : if (optbuf->data[0] != '\0')
1239 0 : appendPQExpBufferStr(optbuf, ", ");
1240 16 : inherit_option = PQgetvalue(res, i, i_inherit_option);
1241 16 : appendPQExpBuffer(optbuf, "INHERIT %s",
1242 16 : *inherit_option == 't' ?
1243 : "TRUE" : "FALSE");
1244 : }
1245 16 : if (*set_option != 't')
1246 : {
1247 0 : if (optbuf->data[0] != '\0')
1248 0 : appendPQExpBufferStr(optbuf, ", ");
1249 0 : appendPQExpBufferStr(optbuf, "SET FALSE");
1250 : }
1251 16 : if (optbuf->data[0] != '\0')
1252 16 : fprintf(OPF, " WITH %s", optbuf->data);
1253 16 : if (dump_grantors)
1254 16 : fprintf(OPF, " GRANTED BY %s", fmtId(grantor));
1255 16 : fprintf(OPF, ";\n");
1256 : }
1257 : }
1258 :
1259 16 : rolename_destroy(ht);
1260 16 : pg_free(done);
1261 16 : start = end;
1262 : }
1263 :
1264 76 : PQclear(res);
1265 76 : destroyPQExpBuffer(buf);
1266 :
1267 76 : fprintf(OPF, "\n\n");
1268 76 : }
1269 :
1270 :
1271 : /*
1272 : * Dump role configuration parameter privileges. This code is used for 15.0
1273 : * and later servers.
1274 : *
1275 : * Note: we expect dumpRoles already created all the roles, but there are
1276 : * no per-role configuration parameter privileges yet.
1277 : */
1278 : static void
1279 76 : dumpRoleGUCPrivs(PGconn *conn)
1280 : {
1281 : PGresult *res;
1282 : int i;
1283 :
1284 : /*
1285 : * Get all parameters that have non-default acls defined.
1286 : */
1287 76 : res = executeQuery(conn, "SELECT parname, "
1288 : "pg_catalog.pg_get_userbyid(" CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS parowner, "
1289 : "paracl, "
1290 : "pg_catalog.acldefault('p', " CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS acldefault "
1291 : "FROM pg_catalog.pg_parameter_acl "
1292 : "ORDER BY 1");
1293 :
1294 76 : if (PQntuples(res) > 0)
1295 2 : fprintf(OPF, "--\n-- Role privileges on configuration parameters\n--\n\n");
1296 :
1297 82 : for (i = 0; i < PQntuples(res); i++)
1298 : {
1299 6 : PQExpBuffer buf = createPQExpBuffer();
1300 6 : char *parname = PQgetvalue(res, i, 0);
1301 6 : char *parowner = PQgetvalue(res, i, 1);
1302 6 : char *paracl = PQgetvalue(res, i, 2);
1303 6 : char *acldefault = PQgetvalue(res, i, 3);
1304 : char *fparname;
1305 :
1306 : /* needed for buildACLCommands() */
1307 6 : fparname = pg_strdup(fmtId(parname));
1308 :
1309 6 : if (!buildACLCommands(fparname, NULL, NULL, "PARAMETER",
1310 : paracl, acldefault,
1311 : parowner, "", server_version, buf))
1312 : {
1313 0 : pg_log_error("could not parse ACL list (%s) for parameter \"%s\"",
1314 : paracl, parname);
1315 0 : PQfinish(conn);
1316 0 : exit_nicely(1);
1317 : }
1318 :
1319 6 : fprintf(OPF, "%s", buf->data);
1320 :
1321 6 : free(fparname);
1322 6 : destroyPQExpBuffer(buf);
1323 : }
1324 :
1325 76 : PQclear(res);
1326 76 : fprintf(OPF, "\n\n");
1327 76 : }
1328 :
1329 :
1330 : /*
1331 : * Drop tablespaces.
1332 : */
1333 : static void
1334 2 : dropTablespaces(PGconn *conn)
1335 : {
1336 : PGresult *res;
1337 : int i;
1338 :
1339 : /*
1340 : * Get all tablespaces except built-in ones (which we assume are named
1341 : * pg_xxx)
1342 : */
1343 2 : res = executeQuery(conn, "SELECT spcname "
1344 : "FROM pg_catalog.pg_tablespace "
1345 : "WHERE spcname !~ '^pg_' "
1346 : "ORDER BY 1");
1347 :
1348 2 : if (PQntuples(res) > 0)
1349 2 : fprintf(OPF, "--\n-- Drop tablespaces\n--\n\n");
1350 :
1351 4 : for (i = 0; i < PQntuples(res); i++)
1352 : {
1353 2 : char *spcname = PQgetvalue(res, i, 0);
1354 :
1355 4 : fprintf(OPF, "DROP TABLESPACE %s%s;\n",
1356 2 : if_exists ? "IF EXISTS " : "",
1357 : fmtId(spcname));
1358 : }
1359 :
1360 2 : PQclear(res);
1361 :
1362 2 : fprintf(OPF, "\n\n");
1363 2 : }
1364 :
1365 : /*
1366 : * Dump tablespaces.
1367 : */
1368 : static void
1369 66 : dumpTablespaces(PGconn *conn)
1370 : {
1371 : PGresult *res;
1372 : int i;
1373 :
1374 : /*
1375 : * Get all tablespaces except built-in ones (which we assume are named
1376 : * pg_xxx)
1377 : */
1378 66 : res = executeQuery(conn, "SELECT oid, spcname, "
1379 : "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1380 : "pg_catalog.pg_tablespace_location(oid), "
1381 : "spcacl, acldefault('t', spcowner) AS acldefault, "
1382 : "array_to_string(spcoptions, ', '),"
1383 : "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1384 : "FROM pg_catalog.pg_tablespace "
1385 : "WHERE spcname !~ '^pg_' "
1386 : "ORDER BY 1");
1387 :
1388 66 : if (PQntuples(res) > 0)
1389 30 : fprintf(OPF, "--\n-- Tablespaces\n--\n\n");
1390 :
1391 112 : for (i = 0; i < PQntuples(res); i++)
1392 : {
1393 46 : PQExpBuffer buf = createPQExpBuffer();
1394 46 : Oid spcoid = atooid(PQgetvalue(res, i, 0));
1395 46 : char *spcname = PQgetvalue(res, i, 1);
1396 46 : char *spcowner = PQgetvalue(res, i, 2);
1397 46 : char *spclocation = PQgetvalue(res, i, 3);
1398 46 : char *spcacl = PQgetvalue(res, i, 4);
1399 46 : char *acldefault = PQgetvalue(res, i, 5);
1400 46 : char *spcoptions = PQgetvalue(res, i, 6);
1401 46 : char *spccomment = PQgetvalue(res, i, 7);
1402 : char *fspcname;
1403 :
1404 : /* needed for buildACLCommands() */
1405 46 : fspcname = pg_strdup(fmtId(spcname));
1406 :
1407 46 : if (binary_upgrade)
1408 : {
1409 0 : appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_tablespace oid\n");
1410 0 : appendPQExpBuffer(buf, "SELECT pg_catalog.binary_upgrade_set_next_pg_tablespace_oid('%u'::pg_catalog.oid);\n", spcoid);
1411 : }
1412 :
1413 46 : appendPQExpBuffer(buf, "CREATE TABLESPACE %s", fspcname);
1414 46 : appendPQExpBuffer(buf, " OWNER %s", fmtId(spcowner));
1415 :
1416 46 : appendPQExpBufferStr(buf, " LOCATION ");
1417 :
1418 : /*
1419 : * In-place tablespaces use a relative path, and need to be dumped
1420 : * with an empty string as location.
1421 : */
1422 46 : if (is_absolute_path(spclocation))
1423 36 : appendStringLiteralConn(buf, spclocation, conn);
1424 : else
1425 10 : appendStringLiteralConn(buf, "", conn);
1426 :
1427 46 : appendPQExpBufferStr(buf, ";\n");
1428 :
1429 46 : if (spcoptions && spcoptions[0] != '\0')
1430 16 : appendPQExpBuffer(buf, "ALTER TABLESPACE %s SET (%s);\n",
1431 : fspcname, spcoptions);
1432 :
1433 : /* tablespaces can't have initprivs */
1434 :
1435 46 : if (!skip_acls &&
1436 46 : !buildACLCommands(fspcname, NULL, NULL, "TABLESPACE",
1437 : spcacl, acldefault,
1438 : spcowner, "", server_version, buf))
1439 : {
1440 0 : pg_log_error("could not parse ACL list (%s) for tablespace \"%s\"",
1441 : spcacl, spcname);
1442 0 : PQfinish(conn);
1443 0 : exit_nicely(1);
1444 : }
1445 :
1446 46 : if (!no_comments && spccomment && spccomment[0] != '\0')
1447 : {
1448 0 : appendPQExpBuffer(buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
1449 0 : appendStringLiteralConn(buf, spccomment, conn);
1450 0 : appendPQExpBufferStr(buf, ";\n");
1451 : }
1452 :
1453 46 : if (!no_security_labels)
1454 46 : buildShSecLabels(conn, "pg_tablespace", spcoid,
1455 : "TABLESPACE", spcname,
1456 : buf);
1457 :
1458 46 : fprintf(OPF, "%s", buf->data);
1459 :
1460 46 : free(fspcname);
1461 46 : destroyPQExpBuffer(buf);
1462 : }
1463 :
1464 66 : PQclear(res);
1465 66 : fprintf(OPF, "\n\n");
1466 66 : }
1467 :
1468 :
1469 : /*
1470 : * Dump commands to drop each database.
1471 : */
1472 : static void
1473 0 : dropDBs(PGconn *conn)
1474 : {
1475 : PGresult *res;
1476 : int i;
1477 :
1478 : /*
1479 : * Skip databases marked not datallowconn, since we'd be unable to connect
1480 : * to them anyway. This must agree with dumpDatabases().
1481 : */
1482 0 : res = executeQuery(conn,
1483 : "SELECT datname "
1484 : "FROM pg_database d "
1485 : "WHERE datallowconn AND datconnlimit != -2 "
1486 : "ORDER BY datname");
1487 :
1488 0 : if (PQntuples(res) > 0)
1489 0 : fprintf(OPF, "--\n-- Drop databases (except postgres and template1)\n--\n\n");
1490 :
1491 0 : for (i = 0; i < PQntuples(res); i++)
1492 : {
1493 0 : char *dbname = PQgetvalue(res, i, 0);
1494 :
1495 : /*
1496 : * Skip "postgres" and "template1"; dumpDatabases() will deal with
1497 : * them specially. Also, be sure to skip "template0", even if for
1498 : * some reason it's not marked !datallowconn.
1499 : */
1500 0 : if (strcmp(dbname, "template1") != 0 &&
1501 0 : strcmp(dbname, "template0") != 0 &&
1502 0 : strcmp(dbname, "postgres") != 0)
1503 : {
1504 0 : fprintf(OPF, "DROP DATABASE %s%s;\n",
1505 0 : if_exists ? "IF EXISTS " : "",
1506 : fmtId(dbname));
1507 : }
1508 : }
1509 :
1510 0 : PQclear(res);
1511 :
1512 0 : fprintf(OPF, "\n\n");
1513 0 : }
1514 :
1515 :
1516 : /*
1517 : * Dump user-specific configuration
1518 : */
1519 : static void
1520 348 : dumpUserConfig(PGconn *conn, const char *username)
1521 : {
1522 348 : PQExpBuffer buf = createPQExpBuffer();
1523 : PGresult *res;
1524 : static bool header_done = false;
1525 :
1526 348 : printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1527 : "WHERE setdatabase = 0 AND setrole = "
1528 : "(SELECT oid FROM %s WHERE rolname = ",
1529 : role_catalog);
1530 348 : appendStringLiteralConn(buf, username, conn);
1531 348 : appendPQExpBufferChar(buf, ')');
1532 :
1533 348 : res = executeQuery(conn, buf->data);
1534 :
1535 348 : if (PQntuples(res) > 0)
1536 : {
1537 0 : if (!header_done)
1538 0 : fprintf(OPF, "\n--\n-- User Configurations\n--\n");
1539 0 : header_done = true;
1540 :
1541 0 : fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", username);
1542 : }
1543 :
1544 348 : for (int i = 0; i < PQntuples(res); i++)
1545 : {
1546 0 : resetPQExpBuffer(buf);
1547 0 : makeAlterConfigCommand(conn, PQgetvalue(res, i, 0),
1548 : "ROLE", username, NULL, NULL,
1549 : buf);
1550 0 : fprintf(OPF, "%s", buf->data);
1551 : }
1552 :
1553 348 : PQclear(res);
1554 :
1555 348 : destroyPQExpBuffer(buf);
1556 348 : }
1557 :
1558 : /*
1559 : * Find a list of database names that match the given patterns.
1560 : * See also expand_table_name_patterns() in pg_dump.c
1561 : */
1562 : static void
1563 80 : expand_dbname_patterns(PGconn *conn,
1564 : SimpleStringList *patterns,
1565 : SimpleStringList *names)
1566 : {
1567 : PQExpBuffer query;
1568 : PGresult *res;
1569 :
1570 80 : if (patterns->head == NULL)
1571 68 : return; /* nothing to do */
1572 :
1573 12 : query = createPQExpBuffer();
1574 :
1575 : /*
1576 : * The loop below runs multiple SELECTs, which might sometimes result in
1577 : * duplicate entries in the name list, but we don't care, since all we're
1578 : * going to do is test membership of the list.
1579 : */
1580 :
1581 20 : for (SimpleStringListCell *cell = patterns->head; cell; cell = cell->next)
1582 : {
1583 : int dotcnt;
1584 :
1585 12 : appendPQExpBufferStr(query,
1586 : "SELECT datname FROM pg_catalog.pg_database n\n");
1587 12 : processSQLNamePattern(conn, query, cell->val, false,
1588 : false, NULL, "datname", NULL, NULL, NULL,
1589 : &dotcnt);
1590 :
1591 12 : if (dotcnt > 0)
1592 : {
1593 4 : pg_log_error("improper qualified name (too many dotted names): %s",
1594 : cell->val);
1595 4 : PQfinish(conn);
1596 4 : exit_nicely(1);
1597 : }
1598 :
1599 8 : res = executeQuery(conn, query->data);
1600 20 : for (int i = 0; i < PQntuples(res); i++)
1601 : {
1602 12 : simple_string_list_append(names, PQgetvalue(res, i, 0));
1603 : }
1604 :
1605 8 : PQclear(res);
1606 8 : resetPQExpBuffer(query);
1607 : }
1608 :
1609 8 : destroyPQExpBuffer(query);
1610 : }
1611 :
1612 : /*
1613 : * Dump contents of databases.
1614 : */
1615 : static void
1616 38 : dumpDatabases(PGconn *conn, ArchiveFormat archDumpFormat)
1617 : {
1618 : PGresult *res;
1619 : int i;
1620 : char db_subdir[MAXPGPATH];
1621 : char dbfilepath[MAXPGPATH];
1622 38 : FILE *map_file = NULL;
1623 :
1624 : /*
1625 : * Skip databases marked not datallowconn, since we'd be unable to connect
1626 : * to them anyway. This must agree with dropDBs().
1627 : *
1628 : * We arrange for template1 to be processed first, then we process other
1629 : * DBs in alphabetical order. If we just did them all alphabetically, we
1630 : * might find ourselves trying to drop the "postgres" database while still
1631 : * connected to it. This makes trying to run the restore script while
1632 : * connected to "template1" a bad idea, but there's no fixed order that
1633 : * doesn't have some failure mode with --clean.
1634 : */
1635 38 : res = executeQuery(conn,
1636 : "SELECT datname, oid "
1637 : "FROM pg_database d "
1638 : "WHERE datallowconn AND datconnlimit != -2 "
1639 : "ORDER BY (datname <> 'template1'), datname");
1640 :
1641 38 : if (archDumpFormat == archNull && PQntuples(res) > 0)
1642 24 : fprintf(OPF, "--\n-- Databases\n--\n\n");
1643 :
1644 : /*
1645 : * If directory/tar/custom format is specified, create a subdirectory
1646 : * under the main directory and each database dump file or subdirectory
1647 : * will be created in that subdirectory by pg_dump.
1648 : */
1649 38 : if (archDumpFormat != archNull)
1650 : {
1651 : char map_file_path[MAXPGPATH];
1652 :
1653 14 : snprintf(db_subdir, MAXPGPATH, "%s/databases", filename);
1654 :
1655 : /* Create a subdirectory with 'databases' name under main directory. */
1656 14 : if (mkdir(db_subdir, pg_dir_create_mode) != 0)
1657 0 : pg_fatal("could not create subdirectory \"%s\": %m", db_subdir);
1658 :
1659 14 : snprintf(map_file_path, MAXPGPATH, "%s/map.dat", filename);
1660 :
1661 : /* Create a map file (to store dboid and dbname) */
1662 14 : map_file = fopen(map_file_path, PG_BINARY_W);
1663 14 : if (!map_file)
1664 0 : pg_fatal("could not open map file: %s", strerror(errno));
1665 : }
1666 :
1667 256 : for (i = 0; i < PQntuples(res); i++)
1668 : {
1669 220 : char *dbname = PQgetvalue(res, i, 0);
1670 220 : char *oid = PQgetvalue(res, i, 1);
1671 220 : const char *create_opts = "";
1672 : int ret;
1673 :
1674 : /* Skip template0, even if it's not marked !datallowconn. */
1675 220 : if (strcmp(dbname, "template0") == 0)
1676 0 : continue;
1677 :
1678 : /* Skip any explicitly excluded database */
1679 220 : if (simple_string_list_member(&database_exclude_names, dbname))
1680 : {
1681 12 : pg_log_info("excluding database \"%s\"", dbname);
1682 12 : continue;
1683 : }
1684 :
1685 : /*
1686 : * If this is not a plain format dump, then append dboid and dbname to
1687 : * the map.dat file.
1688 : */
1689 208 : if (archDumpFormat != archNull)
1690 : {
1691 108 : if (archDumpFormat == archCustom)
1692 16 : snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\".dmp", db_subdir, oid);
1693 92 : else if (archDumpFormat == archTar)
1694 16 : snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\".tar", db_subdir, oid);
1695 : else
1696 76 : snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\"", db_subdir, oid);
1697 :
1698 : /* Put one line entry for dboid and dbname in map file. */
1699 108 : fprintf(map_file, "%s %s\n", oid, dbname);
1700 : }
1701 :
1702 208 : pg_log_info("dumping database \"%s\"", dbname);
1703 :
1704 208 : if (archDumpFormat == archNull)
1705 100 : fprintf(OPF, "--\n-- Database \"%s\" dump\n--\n\n", dbname);
1706 :
1707 : /*
1708 : * We assume that "template1" and "postgres" already exist in the
1709 : * target installation. dropDBs() won't have removed them, for fear
1710 : * of removing the DB the restore script is initially connected to. If
1711 : * --clean was specified, tell pg_dump to drop and recreate them;
1712 : * otherwise we'll merely restore their contents. Other databases
1713 : * should simply be created.
1714 : */
1715 208 : if (strcmp(dbname, "template1") == 0 || strcmp(dbname, "postgres") == 0)
1716 : {
1717 72 : if (output_clean)
1718 0 : create_opts = "--clean --create";
1719 : /* Since pg_dump won't emit a \connect command, we must */
1720 72 : else if (archDumpFormat == archNull)
1721 44 : fprintf(OPF, "\\connect %s\n\n", dbname);
1722 : }
1723 : else
1724 136 : create_opts = "--create";
1725 :
1726 208 : if (filename)
1727 196 : fclose(OPF);
1728 :
1729 208 : ret = runPgDump(dbname, create_opts, dbfilepath, archDumpFormat);
1730 206 : if (ret != 0)
1731 0 : pg_fatal("pg_dump failed on database \"%s\", exiting", dbname);
1732 :
1733 206 : if (filename)
1734 : {
1735 : char global_path[MAXPGPATH];
1736 :
1737 194 : if (archDumpFormat != archNull)
1738 108 : snprintf(global_path, MAXPGPATH, "%s/global.dat", filename);
1739 : else
1740 86 : snprintf(global_path, MAXPGPATH, "%s", filename);
1741 :
1742 194 : OPF = fopen(global_path, PG_BINARY_A);
1743 194 : if (!OPF)
1744 0 : pg_fatal("could not re-open the output file \"%s\": %m",
1745 : global_path);
1746 : }
1747 : }
1748 :
1749 : /* Close map file */
1750 36 : if (archDumpFormat != archNull)
1751 14 : fclose(map_file);
1752 :
1753 36 : PQclear(res);
1754 36 : }
1755 :
1756 :
1757 :
1758 : /*
1759 : * Run pg_dump on dbname, with specified options.
1760 : */
1761 : static int
1762 208 : runPgDump(const char *dbname, const char *create_opts, char *dbfile,
1763 : ArchiveFormat archDumpFormat)
1764 : {
1765 : PQExpBufferData connstrbuf;
1766 : PQExpBufferData cmd;
1767 : int ret;
1768 :
1769 208 : initPQExpBuffer(&connstrbuf);
1770 208 : initPQExpBuffer(&cmd);
1771 :
1772 : /*
1773 : * If this is not a plain format dump, then append file name and dump
1774 : * format to the pg_dump command to get archive dump.
1775 : */
1776 208 : if (archDumpFormat != archNull)
1777 : {
1778 108 : printfPQExpBuffer(&cmd, "\"%s\" -f %s %s", pg_dump_bin,
1779 : dbfile, create_opts);
1780 :
1781 108 : if (archDumpFormat == archDirectory)
1782 76 : appendPQExpBufferStr(&cmd, " --format=directory ");
1783 32 : else if (archDumpFormat == archCustom)
1784 16 : appendPQExpBufferStr(&cmd, " --format=custom ");
1785 16 : else if (archDumpFormat == archTar)
1786 16 : appendPQExpBufferStr(&cmd, " --format=tar ");
1787 : }
1788 : else
1789 : {
1790 100 : printfPQExpBuffer(&cmd, "\"%s\" %s %s", pg_dump_bin,
1791 100 : pgdumpopts->data, create_opts);
1792 :
1793 : /*
1794 : * If we have a filename, use the undocumented plain-append pg_dump
1795 : * format.
1796 : */
1797 100 : if (filename)
1798 88 : appendPQExpBufferStr(&cmd, " -Fa ");
1799 : else
1800 12 : appendPQExpBufferStr(&cmd, " -Fp ");
1801 : }
1802 :
1803 : /*
1804 : * Append the database name to the already-constructed stem of connection
1805 : * string.
1806 : */
1807 208 : appendPQExpBuffer(&connstrbuf, "%s dbname=", connstr);
1808 208 : appendConnStrVal(&connstrbuf, dbname);
1809 :
1810 208 : appendShellString(&cmd, connstrbuf.data);
1811 :
1812 206 : pg_log_info("running \"%s\"", cmd.data);
1813 :
1814 206 : fflush(NULL);
1815 :
1816 206 : ret = system(cmd.data);
1817 :
1818 206 : termPQExpBuffer(&cmd);
1819 206 : termPQExpBuffer(&connstrbuf);
1820 :
1821 206 : return ret;
1822 : }
1823 :
1824 : /*
1825 : * buildShSecLabels
1826 : *
1827 : * Build SECURITY LABEL command(s) for a shared object
1828 : *
1829 : * The caller has to provide object type and identity in two separate formats:
1830 : * catalog_name (e.g., "pg_database") and object OID, as well as
1831 : * type name (e.g., "DATABASE") and object name (not pre-quoted).
1832 : *
1833 : * The command(s) are appended to "buffer".
1834 : */
1835 : static void
1836 394 : buildShSecLabels(PGconn *conn, const char *catalog_name, Oid objectId,
1837 : const char *objtype, const char *objname,
1838 : PQExpBuffer buffer)
1839 : {
1840 394 : PQExpBuffer sql = createPQExpBuffer();
1841 : PGresult *res;
1842 :
1843 394 : buildShSecLabelQuery(catalog_name, objectId, sql);
1844 394 : res = executeQuery(conn, sql->data);
1845 394 : emitShSecLabels(conn, res, buffer, objtype, objname);
1846 :
1847 394 : PQclear(res);
1848 394 : destroyPQExpBuffer(sql);
1849 394 : }
1850 :
1851 : /*
1852 : * As above for a SQL command (which returns nothing).
1853 : */
1854 : static void
1855 20 : executeCommand(PGconn *conn, const char *query)
1856 : {
1857 : PGresult *res;
1858 :
1859 20 : pg_log_info("executing %s", query);
1860 :
1861 20 : res = PQexec(conn, query);
1862 40 : if (!res ||
1863 20 : PQresultStatus(res) != PGRES_COMMAND_OK)
1864 : {
1865 0 : pg_log_error("query failed: %s", PQerrorMessage(conn));
1866 0 : pg_log_error_detail("Query was: %s", query);
1867 0 : PQfinish(conn);
1868 0 : exit_nicely(1);
1869 : }
1870 :
1871 20 : PQclear(res);
1872 20 : }
1873 :
1874 :
1875 : /*
1876 : * dumpTimestamp
1877 : */
1878 : static void
1879 8 : dumpTimestamp(const char *msg)
1880 : {
1881 : char buf[64];
1882 8 : time_t now = time(NULL);
1883 :
1884 8 : if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
1885 8 : fprintf(OPF, "-- %s %s\n\n", msg, buf);
1886 8 : }
1887 :
1888 : /*
1889 : * read_dumpall_filters - retrieve database identifier patterns from file
1890 : *
1891 : * Parse the specified filter file for include and exclude patterns, and add
1892 : * them to the relevant lists. If the filename is "-" then filters will be
1893 : * read from STDIN rather than a file.
1894 : *
1895 : * At the moment, the only allowed filter is for database exclusion.
1896 : */
1897 : static void
1898 10 : read_dumpall_filters(const char *filename, SimpleStringList *pattern)
1899 : {
1900 : FilterStateData fstate;
1901 : char *objname;
1902 : FilterCommandType comtype;
1903 : FilterObjectType objtype;
1904 :
1905 10 : filter_init(&fstate, filename, exit);
1906 :
1907 14 : while (filter_read_item(&fstate, &objname, &comtype, &objtype))
1908 : {
1909 6 : if (comtype == FILTER_COMMAND_TYPE_INCLUDE)
1910 : {
1911 0 : pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
1912 : "include",
1913 : filter_object_type_name(objtype));
1914 0 : exit_nicely(1);
1915 : }
1916 :
1917 6 : switch (objtype)
1918 : {
1919 0 : case FILTER_OBJECT_TYPE_NONE:
1920 0 : break;
1921 2 : case FILTER_OBJECT_TYPE_FUNCTION:
1922 : case FILTER_OBJECT_TYPE_INDEX:
1923 : case FILTER_OBJECT_TYPE_TABLE_DATA:
1924 : case FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN:
1925 : case FILTER_OBJECT_TYPE_TRIGGER:
1926 : case FILTER_OBJECT_TYPE_EXTENSION:
1927 : case FILTER_OBJECT_TYPE_FOREIGN_DATA:
1928 : case FILTER_OBJECT_TYPE_SCHEMA:
1929 : case FILTER_OBJECT_TYPE_TABLE:
1930 : case FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN:
1931 2 : pg_log_filter_error(&fstate, _("unsupported filter object"));
1932 2 : exit_nicely(1);
1933 : break;
1934 :
1935 4 : case FILTER_OBJECT_TYPE_DATABASE:
1936 4 : simple_string_list_append(pattern, objname);
1937 4 : break;
1938 : }
1939 :
1940 4 : if (objname)
1941 4 : free(objname);
1942 : }
1943 :
1944 4 : filter_free(&fstate);
1945 4 : }
1946 :
1947 : /*
1948 : * parseDumpFormat
1949 : *
1950 : * This will validate dump formats.
1951 : */
1952 : static ArchiveFormat
1953 82 : parseDumpFormat(const char *format)
1954 : {
1955 : ArchiveFormat archDumpFormat;
1956 :
1957 82 : if (pg_strcasecmp(format, "c") == 0)
1958 0 : archDumpFormat = archCustom;
1959 82 : else if (pg_strcasecmp(format, "custom") == 0)
1960 2 : archDumpFormat = archCustom;
1961 80 : else if (pg_strcasecmp(format, "d") == 0)
1962 0 : archDumpFormat = archDirectory;
1963 80 : else if (pg_strcasecmp(format, "directory") == 0)
1964 12 : archDumpFormat = archDirectory;
1965 68 : else if (pg_strcasecmp(format, "p") == 0)
1966 64 : archDumpFormat = archNull;
1967 4 : else if (pg_strcasecmp(format, "plain") == 0)
1968 0 : archDumpFormat = archNull;
1969 4 : else if (pg_strcasecmp(format, "t") == 0)
1970 0 : archDumpFormat = archTar;
1971 4 : else if (pg_strcasecmp(format, "tar") == 0)
1972 2 : archDumpFormat = archTar;
1973 : else
1974 2 : pg_fatal("unrecognized archive format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
1975 : format);
1976 :
1977 80 : return archDumpFormat;
1978 : }
|