PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
pg_dumpall.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_dumpall.c
4  *
5  * Portions Copyright (c) 1996-2017, 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 "getopt_long.h"
22 
23 #include "dumputils.h"
24 #include "pg_backup.h"
25 #include "common/file_utils.h"
26 #include "fe_utils/string_utils.h"
27 
28 /* version string we expect back from pg_dump */
29 #define PGDUMP_VERSIONSTR "pg_dump (PostgreSQL) " PG_VERSION "\n"
30 
31 
32 static void help(void);
33 
34 static void dropRoles(PGconn *conn);
35 static void dumpRoles(PGconn *conn);
36 static void dumpRoleMembership(PGconn *conn);
37 static void dumpGroups(PGconn *conn);
38 static void dropTablespaces(PGconn *conn);
39 static void dumpTablespaces(PGconn *conn);
40 static void dropDBs(PGconn *conn);
41 static void dumpCreateDB(PGconn *conn);
42 static void dumpDatabaseConfig(PGconn *conn, const char *dbname);
43 static void dumpUserConfig(PGconn *conn, const char *username);
44 static void dumpDbRoleConfig(PGconn *conn);
45 static void makeAlterConfigCommand(PGconn *conn, const char *arrayitem,
46  const char *type, const char *name, const char *type2,
47  const char *name2);
48 static void dumpDatabases(PGconn *conn);
49 static void dumpTimestamp(const char *msg);
50 
51 static int runPgDump(const char *dbname);
52 static void buildShSecLabels(PGconn *conn, const char *catalog_name,
53  uint32 objectId, PQExpBuffer buffer,
54  const char *target, const char *objname);
55 static PGconn *connectDatabase(const char *dbname, const char *connstr, const char *pghost, const char *pgport,
56  const char *pguser, trivalue prompt_password, bool fail_on_error);
57 static char *constructConnStr(const char **keywords, const char **values);
58 static PGresult *executeQuery(PGconn *conn, const char *query);
59 static void executeCommand(PGconn *conn, const char *query);
60 
61 static char pg_dump_bin[MAXPGPATH];
62 static const char *progname;
64 static char *connstr = "";
65 static bool skip_acls = false;
66 static bool verbose = false;
67 static bool dosync = true;
68 
69 static int binary_upgrade = 0;
70 static int column_inserts = 0;
71 static int disable_dollar_quoting = 0;
72 static int disable_triggers = 0;
73 static int if_exists = 0;
74 static int inserts = 0;
75 static int no_tablespaces = 0;
76 static int use_setsessauth = 0;
77 static int no_security_labels = 0;
78 static int no_unlogged_table_data = 0;
79 static int no_role_passwords = 0;
80 static int server_version;
81 
82 static char role_catalog[10];
83 #define PG_AUTHID "pg_authid"
84 #define PG_ROLES "pg_roles "
85 
86 static FILE *OPF;
87 static char *filename = NULL;
88 
89 #define exit_nicely(code) exit(code)
90 
91 int
92 main(int argc, char *argv[])
93 {
94  static struct option long_options[] = {
95  {"data-only", no_argument, NULL, 'a'},
96  {"clean", no_argument, NULL, 'c'},
97  {"file", required_argument, NULL, 'f'},
98  {"globals-only", no_argument, NULL, 'g'},
99  {"host", required_argument, NULL, 'h'},
100  {"dbname", required_argument, NULL, 'd'},
101  {"database", required_argument, NULL, 'l'},
102  {"oids", no_argument, NULL, 'o'},
103  {"no-owner", no_argument, NULL, 'O'},
104  {"port", required_argument, NULL, 'p'},
105  {"roles-only", no_argument, NULL, 'r'},
106  {"schema-only", no_argument, NULL, 's'},
107  {"superuser", required_argument, NULL, 'S'},
108  {"tablespaces-only", no_argument, NULL, 't'},
109  {"username", required_argument, NULL, 'U'},
110  {"verbose", no_argument, NULL, 'v'},
111  {"no-password", no_argument, NULL, 'w'},
112  {"password", no_argument, NULL, 'W'},
113  {"no-privileges", no_argument, NULL, 'x'},
114  {"no-acl", no_argument, NULL, 'x'},
115 
116  /*
117  * the following options don't have an equivalent short option letter
118  */
119  {"attribute-inserts", no_argument, &column_inserts, 1},
120  {"binary-upgrade", no_argument, &binary_upgrade, 1},
121  {"column-inserts", no_argument, &column_inserts, 1},
122  {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
123  {"disable-triggers", no_argument, &disable_triggers, 1},
124  {"if-exists", no_argument, &if_exists, 1},
125  {"inserts", no_argument, &inserts, 1},
126  {"lock-wait-timeout", required_argument, NULL, 2},
127  {"no-tablespaces", no_argument, &no_tablespaces, 1},
128  {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
129  {"role", required_argument, NULL, 3},
130  {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
131  {"no-security-labels", no_argument, &no_security_labels, 1},
132  {"no-sync", no_argument, NULL, 4},
133  {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
134  {"no-role-passwords", no_argument, &no_role_passwords, 1},
135 
136  {NULL, 0, NULL, 0}
137  };
138 
139  char *pghost = NULL;
140  char *pgport = NULL;
141  char *pguser = NULL;
142  char *pgdb = NULL;
143  char *use_role = NULL;
144  trivalue prompt_password = TRI_DEFAULT;
145  bool data_only = false;
146  bool globals_only = false;
147  bool output_clean = false;
148  bool roles_only = false;
149  bool tablespaces_only = false;
150  PGconn *conn;
151  int encoding;
152  const char *std_strings;
153  int c,
154  ret;
155  int optindex;
156 
157  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
158 
159  progname = get_progname(argv[0]);
160 
161  if (argc > 1)
162  {
163  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
164  {
165  help();
166  exit_nicely(0);
167  }
168  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
169  {
170  puts("pg_dumpall (PostgreSQL) " PG_VERSION);
171  exit_nicely(0);
172  }
173  }
174 
175  if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
176  pg_dump_bin)) < 0)
177  {
178  char full_path[MAXPGPATH];
179 
180  if (find_my_exec(argv[0], full_path) < 0)
181  strlcpy(full_path, progname, sizeof(full_path));
182 
183  if (ret == -1)
184  fprintf(stderr,
185  _("The program \"pg_dump\" is needed by %s "
186  "but was not found in the\n"
187  "same directory as \"%s\".\n"
188  "Check your installation.\n"),
189  progname, full_path);
190  else
191  fprintf(stderr,
192  _("The program \"pg_dump\" was found by \"%s\"\n"
193  "but was not the same version as %s.\n"
194  "Check your installation.\n"),
195  full_path, progname);
196  exit_nicely(1);
197  }
198 
199  pgdumpopts = createPQExpBuffer();
200 
201  while ((c = getopt_long(argc, argv, "acd:f:gh:l:oOp:rsS:tU:vwWx", long_options, &optindex)) != -1)
202  {
203  switch (c)
204  {
205  case 'a':
206  data_only = true;
207  appendPQExpBufferStr(pgdumpopts, " -a");
208  break;
209 
210  case 'c':
211  output_clean = true;
212  break;
213 
214  case 'd':
216  break;
217 
218  case 'f':
220  appendPQExpBufferStr(pgdumpopts, " -f ");
221  appendShellString(pgdumpopts, filename);
222  break;
223 
224  case 'g':
225  globals_only = true;
226  break;
227 
228  case 'h':
229  pghost = pg_strdup(optarg);
230  break;
231 
232  case 'l':
233  pgdb = pg_strdup(optarg);
234  break;
235 
236  case 'o':
237  appendPQExpBufferStr(pgdumpopts, " -o");
238  break;
239 
240  case 'O':
241  appendPQExpBufferStr(pgdumpopts, " -O");
242  break;
243 
244  case 'p':
245  pgport = pg_strdup(optarg);
246  break;
247 
248  case 'r':
249  roles_only = true;
250  break;
251 
252  case 's':
253  appendPQExpBufferStr(pgdumpopts, " -s");
254  break;
255 
256  case 'S':
257  appendPQExpBufferStr(pgdumpopts, " -S ");
258  appendShellString(pgdumpopts, optarg);
259  break;
260 
261  case 't':
262  tablespaces_only = true;
263  break;
264 
265  case 'U':
266  pguser = pg_strdup(optarg);
267  break;
268 
269  case 'v':
270  verbose = true;
271  appendPQExpBufferStr(pgdumpopts, " -v");
272  break;
273 
274  case 'w':
275  prompt_password = TRI_NO;
276  appendPQExpBufferStr(pgdumpopts, " -w");
277  break;
278 
279  case 'W':
280  prompt_password = TRI_YES;
281  appendPQExpBufferStr(pgdumpopts, " -W");
282  break;
283 
284  case 'x':
285  skip_acls = true;
286  appendPQExpBufferStr(pgdumpopts, " -x");
287  break;
288 
289  case 0:
290  break;
291 
292  case 2:
293  appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
294  appendShellString(pgdumpopts, optarg);
295  break;
296 
297  case 3:
298  use_role = pg_strdup(optarg);
299  appendPQExpBufferStr(pgdumpopts, " --role ");
300  appendShellString(pgdumpopts, use_role);
301  break;
302 
303  case 4:
304  dosync = false;
305  appendPQExpBufferStr(pgdumpopts, " --no-sync");
306  break;
307 
308  default:
309  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
310  exit_nicely(1);
311  }
312  }
313 
314  /* Complain if any arguments remain */
315  if (optind < argc)
316  {
317  fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
318  progname, argv[optind]);
319  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
320  progname);
321  exit_nicely(1);
322  }
323 
324  /* Make sure the user hasn't specified a mix of globals-only options */
325  if (globals_only && roles_only)
326  {
327  fprintf(stderr, _("%s: options -g/--globals-only and -r/--roles-only cannot be used together\n"),
328  progname);
329  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
330  progname);
331  exit_nicely(1);
332  }
333 
334  if (globals_only && tablespaces_only)
335  {
336  fprintf(stderr, _("%s: options -g/--globals-only and -t/--tablespaces-only cannot be used together\n"),
337  progname);
338  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
339  progname);
340  exit_nicely(1);
341  }
342 
343  if (if_exists && !output_clean)
344  {
345  fprintf(stderr, _("%s: option --if-exists requires option -c/--clean\n"),
346  progname);
347  exit_nicely(1);
348  }
349 
350  if (roles_only && tablespaces_only)
351  {
352  fprintf(stderr, _("%s: options -r/--roles-only and -t/--tablespaces-only cannot be used together\n"),
353  progname);
354  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
355  progname);
356  exit_nicely(1);
357  }
358 
360  {
361  fprintf(stderr, _("%s: options --no-role-passwords and --binary-upgrade cannot be used together\n"),
362  progname);
363  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
364  progname);
365  exit_nicely(1);
366  }
367 
368  /*
369  * If password values are not required in the dump, switch to
370  * using pg_roles which is equally useful, just more likely
371  * to have unrestricted access than pg_authid.
372  */
373  if (no_role_passwords)
374  sprintf(role_catalog, "%s", PG_ROLES);
375  else
376  sprintf(role_catalog, "%s", PG_AUTHID);
377 
378  /* Add long options to the pg_dump argument list */
379  if (binary_upgrade)
380  appendPQExpBufferStr(pgdumpopts, " --binary-upgrade");
381  if (column_inserts)
382  appendPQExpBufferStr(pgdumpopts, " --column-inserts");
384  appendPQExpBufferStr(pgdumpopts, " --disable-dollar-quoting");
385  if (disable_triggers)
386  appendPQExpBufferStr(pgdumpopts, " --disable-triggers");
387  if (inserts)
388  appendPQExpBufferStr(pgdumpopts, " --inserts");
389  if (no_tablespaces)
390  appendPQExpBufferStr(pgdumpopts, " --no-tablespaces");
392  appendPQExpBufferStr(pgdumpopts, " --quote-all-identifiers");
393  if (use_setsessauth)
394  appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
395  if (no_security_labels)
396  appendPQExpBufferStr(pgdumpopts, " --no-security-labels");
398  appendPQExpBufferStr(pgdumpopts, " --no-unlogged-table-data");
399 
400  /*
401  * If there was a database specified on the command line, use that,
402  * otherwise try to connect to database "postgres", and failing that
403  * "template1". "postgres" is the preferred choice for 8.1 and later
404  * servers, but it usually will not exist on older ones.
405  */
406  if (pgdb)
407  {
408  conn = connectDatabase(pgdb, connstr, pghost, pgport, pguser,
409  prompt_password, false);
410 
411  if (!conn)
412  {
413  fprintf(stderr, _("%s: could not connect to database \"%s\"\n"),
414  progname, pgdb);
415  exit_nicely(1);
416  }
417  }
418  else
419  {
420  conn = connectDatabase("postgres", connstr, pghost, pgport, pguser,
421  prompt_password, false);
422  if (!conn)
423  conn = connectDatabase("template1", connstr, pghost, pgport, pguser,
424  prompt_password, true);
425 
426  if (!conn)
427  {
428  fprintf(stderr, _("%s: could not connect to databases \"postgres\" or \"template1\"\n"
429  "Please specify an alternative database.\n"),
430  progname);
431  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
432  progname);
433  exit_nicely(1);
434  }
435  }
436 
437  /*
438  * Open the output file if required, otherwise use stdout
439  */
440  if (filename)
441  {
442  OPF = fopen(filename, PG_BINARY_W);
443  if (!OPF)
444  {
445  fprintf(stderr, _("%s: could not open the output file \"%s\": %s\n"),
446  progname, filename, strerror(errno));
447  exit_nicely(1);
448  }
449  }
450  else
451  OPF = stdout;
452 
453  /*
454  * Get the active encoding and the standard_conforming_strings setting, so
455  * we know how to escape strings.
456  */
457  encoding = PQclientEncoding(conn);
458  std_strings = PQparameterStatus(conn, "standard_conforming_strings");
459  if (!std_strings)
460  std_strings = "off";
461 
462  /* Set the role if requested */
463  if (use_role && server_version >= 80100)
464  {
465  PQExpBuffer query = createPQExpBuffer();
466 
467  appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
468  executeCommand(conn, query->data);
469  destroyPQExpBuffer(query);
470  }
471 
472  /* Force quoting of all identifiers if requested. */
473  if (quote_all_identifiers && server_version >= 90100)
474  executeCommand(conn, "SET quote_all_identifiers = true");
475 
476  fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
477  if (verbose)
478  dumpTimestamp("Started on");
479 
480  /*
481  * We used to emit \connect postgres here, but that served no purpose
482  * other than to break things for installations without a postgres
483  * database. Everything we're restoring here is a global, so whichever
484  * database we're connected to at the moment is fine.
485  */
486 
487  /* Restore will need to write to the target cluster */
488  fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
489 
490  /* Replicate encoding and std_strings in output */
491  fprintf(OPF, "SET client_encoding = '%s';\n",
492  pg_encoding_to_char(encoding));
493  fprintf(OPF, "SET standard_conforming_strings = %s;\n", std_strings);
494  if (strcmp(std_strings, "off") == 0)
495  fprintf(OPF, "SET escape_string_warning = off;\n");
496  fprintf(OPF, "\n");
497 
498  if (!data_only)
499  {
500  /*
501  * If asked to --clean, do that first. We can avoid detailed
502  * dependency analysis because databases never depend on each other,
503  * and tablespaces never depend on each other. Roles could have
504  * grants to each other, but DROP ROLE will clean those up silently.
505  */
506  if (output_clean)
507  {
508  if (!globals_only && !roles_only && !tablespaces_only)
509  dropDBs(conn);
510 
511  if (!roles_only && !no_tablespaces)
512  dropTablespaces(conn);
513 
514  if (!tablespaces_only)
515  dropRoles(conn);
516  }
517 
518  /*
519  * Now create objects as requested. Be careful that option logic here
520  * is the same as for drops above.
521  */
522  if (!tablespaces_only)
523  {
524  /* Dump roles (users) */
525  dumpRoles(conn);
526 
527  /* Dump role memberships --- need different method for pre-8.1 */
528  if (server_version >= 80100)
529  dumpRoleMembership(conn);
530  else
531  dumpGroups(conn);
532  }
533 
534  /* Dump tablespaces */
535  if (!roles_only && !no_tablespaces)
536  dumpTablespaces(conn);
537 
538  /* Dump CREATE DATABASE commands */
539  if (binary_upgrade || (!globals_only && !roles_only && !tablespaces_only))
540  dumpCreateDB(conn);
541 
542  /* Dump role/database settings */
543  if (!tablespaces_only && !roles_only)
544  {
545  if (server_version >= 90000)
546  dumpDbRoleConfig(conn);
547  }
548  }
549 
550  if (!globals_only && !roles_only && !tablespaces_only)
551  dumpDatabases(conn);
552 
553  PQfinish(conn);
554 
555  if (verbose)
556  dumpTimestamp("Completed on");
557  fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
558 
559  if (filename)
560  {
561  fclose(OPF);
562 
563  /* sync the resulting file, errors are not fatal */
564  if (dosync)
565  (void) fsync_fname(filename, false, progname);
566  }
567 
568  exit_nicely(0);
569 }
570 
571 
572 static void
573 help(void)
574 {
575  printf(_("%s extracts a PostgreSQL database cluster into an SQL script file.\n\n"), progname);
576  printf(_("Usage:\n"));
577  printf(_(" %s [OPTION]...\n"), progname);
578 
579  printf(_("\nGeneral options:\n"));
580  printf(_(" -f, --file=FILENAME output file name\n"));
581  printf(_(" -v, --verbose verbose mode\n"));
582  printf(_(" -V, --version output version information, then exit\n"));
583  printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
584  printf(_(" -?, --help show this help, then exit\n"));
585  printf(_("\nOptions controlling the output content:\n"));
586  printf(_(" -a, --data-only dump only the data, not the schema\n"));
587  printf(_(" -c, --clean clean (drop) databases before recreating\n"));
588  printf(_(" -g, --globals-only dump only global objects, no databases\n"));
589  printf(_(" -o, --oids include OIDs in dump\n"));
590  printf(_(" -O, --no-owner skip restoration of object ownership\n"));
591  printf(_(" -r, --roles-only dump only roles, no databases or tablespaces\n"));
592  printf(_(" -s, --schema-only dump only the schema, no data\n"));
593  printf(_(" -S, --superuser=NAME superuser user name to use in the dump\n"));
594  printf(_(" -t, --tablespaces-only dump only tablespaces, no databases or roles\n"));
595  printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
596  printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
597  printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
598  printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
599  printf(_(" --disable-triggers disable triggers during data-only restore\n"));
600  printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
601  printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
602  printf(_(" --no-security-labels do not dump security label assignments\n"));
603  printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
604  printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
605  printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
606  printf(_(" --no-role-passwords do not dump passwords for roles\n"));
607  printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
608  printf(_(" --use-set-session-authorization\n"
609  " use SET SESSION AUTHORIZATION commands instead of\n"
610  " ALTER OWNER commands to set ownership\n"));
611 
612  printf(_("\nConnection options:\n"));
613  printf(_(" -d, --dbname=CONNSTR connect using connection string\n"));
614  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
615  printf(_(" -l, --database=DBNAME alternative default database\n"));
616  printf(_(" -p, --port=PORT database server port number\n"));
617  printf(_(" -U, --username=NAME connect as specified database user\n"));
618  printf(_(" -w, --no-password never prompt for password\n"));
619  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
620  printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
621 
622  printf(_("\nIf -f/--file is not used, then the SQL script will be written to the standard\n"
623  "output.\n\n"));
624  printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
625 }
626 
627 
628 /*
629  * Drop roles
630  */
631 static void
633 {
635  PGresult *res;
636  int i_rolname;
637  int i;
638 
639  if (server_version >= 90600)
640  printfPQExpBuffer(buf,
641  "SELECT rolname "
642  "FROM %s "
643  "WHERE rolname !~ '^pg_' "
644  "ORDER BY 1", role_catalog);
645  else if (server_version >= 80100)
646  printfPQExpBuffer(buf,
647  "SELECT rolname "
648  "FROM %s "
649  "ORDER BY 1", role_catalog);
650  else
651  printfPQExpBuffer(buf,
652  "SELECT usename as rolname "
653  "FROM pg_shadow "
654  "UNION "
655  "SELECT groname as rolname "
656  "FROM pg_group "
657  "ORDER BY 1");
658 
659  res = executeQuery(conn, buf->data);
660 
661  i_rolname = PQfnumber(res, "rolname");
662 
663  if (PQntuples(res) > 0)
664  fprintf(OPF, "--\n-- Drop roles\n--\n\n");
665 
666  for (i = 0; i < PQntuples(res); i++)
667  {
668  const char *rolename;
669 
670  rolename = PQgetvalue(res, i, i_rolname);
671 
672  fprintf(OPF, "DROP ROLE %s%s;\n",
673  if_exists ? "IF EXISTS " : "",
674  fmtId(rolename));
675  }
676 
677  PQclear(res);
678  destroyPQExpBuffer(buf);
679 
680  fprintf(OPF, "\n\n");
681 }
682 
683 /*
684  * Dump roles
685  */
686 static void
688 {
690  PGresult *res;
691  int i_oid,
692  i_rolname,
693  i_rolsuper,
694  i_rolinherit,
695  i_rolcreaterole,
696  i_rolcreatedb,
697  i_rolcanlogin,
698  i_rolconnlimit,
699  i_rolpassword,
700  i_rolvaliduntil,
701  i_rolreplication,
702  i_rolbypassrls,
703  i_rolcomment,
704  i_is_current_user;
705  int i;
706 
707  /* note: rolconfig is dumped later */
708  if (server_version >= 90600)
709  printfPQExpBuffer(buf,
710  "SELECT oid, rolname, rolsuper, rolinherit, "
711  "rolcreaterole, rolcreatedb, "
712  "rolcanlogin, rolconnlimit, rolpassword, "
713  "rolvaliduntil, rolreplication, rolbypassrls, "
714  "pg_catalog.shobj_description(oid, '%s') as rolcomment, "
715  "rolname = current_user AS is_current_user "
716  "FROM %s "
717  "WHERE rolname !~ '^pg_' "
718  "ORDER BY 2", role_catalog, role_catalog);
719  else if (server_version >= 90500)
720  printfPQExpBuffer(buf,
721  "SELECT oid, rolname, rolsuper, rolinherit, "
722  "rolcreaterole, rolcreatedb, "
723  "rolcanlogin, rolconnlimit, rolpassword, "
724  "rolvaliduntil, rolreplication, rolbypassrls, "
725  "pg_catalog.shobj_description(oid, '%s') as rolcomment, "
726  "rolname = current_user AS is_current_user "
727  "FROM %s "
728  "ORDER BY 2", role_catalog, role_catalog);
729  else if (server_version >= 90100)
730  printfPQExpBuffer(buf,
731  "SELECT oid, rolname, rolsuper, rolinherit, "
732  "rolcreaterole, rolcreatedb, "
733  "rolcanlogin, rolconnlimit, rolpassword, "
734  "rolvaliduntil, rolreplication, "
735  "false as rolbypassrls, "
736  "pg_catalog.shobj_description(oid, '%s') as rolcomment, "
737  "rolname = current_user AS is_current_user "
738  "FROM %s "
739  "ORDER BY 2", role_catalog, role_catalog);
740  else if (server_version >= 80200)
741  printfPQExpBuffer(buf,
742  "SELECT oid, rolname, rolsuper, rolinherit, "
743  "rolcreaterole, rolcreatedb, "
744  "rolcanlogin, rolconnlimit, rolpassword, "
745  "rolvaliduntil, false as rolreplication, "
746  "false as rolbypassrls, "
747  "pg_catalog.shobj_description(oid, '%s') as rolcomment, "
748  "rolname = current_user AS is_current_user "
749  "FROM %s "
750  "ORDER BY 2", role_catalog, role_catalog);
751  else if (server_version >= 80100)
752  printfPQExpBuffer(buf,
753  "SELECT oid, rolname, rolsuper, rolinherit, "
754  "rolcreaterole, rolcreatedb, "
755  "rolcanlogin, rolconnlimit, rolpassword, "
756  "rolvaliduntil, false as rolreplication, "
757  "false as rolbypassrls, "
758  "null as rolcomment, "
759  "rolname = current_user AS is_current_user "
760  "FROM %s "
761  "ORDER BY 2", role_catalog);
762  else
763  printfPQExpBuffer(buf,
764  "SELECT 0 as oid, usename as rolname, "
765  "usesuper as rolsuper, "
766  "true as rolinherit, "
767  "usesuper as rolcreaterole, "
768  "usecreatedb as rolcreatedb, "
769  "true as rolcanlogin, "
770  "-1 as rolconnlimit, "
771  "passwd as rolpassword, "
772  "valuntil as rolvaliduntil, "
773  "false as rolreplication, "
774  "false as rolbypassrls, "
775  "null as rolcomment, "
776  "usename = current_user AS is_current_user "
777  "FROM pg_shadow "
778  "UNION ALL "
779  "SELECT 0 as oid, groname as rolname, "
780  "false as rolsuper, "
781  "true as rolinherit, "
782  "false as rolcreaterole, "
783  "false as rolcreatedb, "
784  "false as rolcanlogin, "
785  "-1 as rolconnlimit, "
786  "null::text as rolpassword, "
787  "null::abstime as rolvaliduntil, "
788  "false as rolreplication, "
789  "false as rolbypassrls, "
790  "null as rolcomment, "
791  "false AS is_current_user "
792  "FROM pg_group "
793  "WHERE NOT EXISTS (SELECT 1 FROM pg_shadow "
794  " WHERE usename = groname) "
795  "ORDER BY 2");
796 
797  res = executeQuery(conn, buf->data);
798 
799  i_oid = PQfnumber(res, "oid");
800  i_rolname = PQfnumber(res, "rolname");
801  i_rolsuper = PQfnumber(res, "rolsuper");
802  i_rolinherit = PQfnumber(res, "rolinherit");
803  i_rolcreaterole = PQfnumber(res, "rolcreaterole");
804  i_rolcreatedb = PQfnumber(res, "rolcreatedb");
805  i_rolcanlogin = PQfnumber(res, "rolcanlogin");
806  i_rolconnlimit = PQfnumber(res, "rolconnlimit");
807  i_rolpassword = PQfnumber(res, "rolpassword");
808  i_rolvaliduntil = PQfnumber(res, "rolvaliduntil");
809  i_rolreplication = PQfnumber(res, "rolreplication");
810  i_rolbypassrls = PQfnumber(res, "rolbypassrls");
811  i_rolcomment = PQfnumber(res, "rolcomment");
812  i_is_current_user = PQfnumber(res, "is_current_user");
813 
814  if (PQntuples(res) > 0)
815  fprintf(OPF, "--\n-- Roles\n--\n\n");
816 
817  for (i = 0; i < PQntuples(res); i++)
818  {
819  const char *rolename;
820  Oid auth_oid;
821 
822  auth_oid = atooid(PQgetvalue(res, i, i_oid));
823  rolename = PQgetvalue(res, i, i_rolname);
824 
825  if (strncmp(rolename, "pg_", 3) == 0)
826  {
827  fprintf(stderr, _("%s: role name starting with \"pg_\" skipped (%s)\n"),
828  progname, rolename);
829  continue;
830  }
831 
832  resetPQExpBuffer(buf);
833 
834  if (binary_upgrade)
835  {
836  appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_authid.oid\n");
837  appendPQExpBuffer(buf,
838  "SELECT pg_catalog.binary_upgrade_set_next_pg_authid_oid('%u'::pg_catalog.oid);\n\n",
839  auth_oid);
840  }
841 
842  /*
843  * We dump CREATE ROLE followed by ALTER ROLE to ensure that the role
844  * will acquire the right properties even if it already exists (ie, it
845  * won't hurt for the CREATE to fail). This is particularly important
846  * for the role we are connected as, since even with --clean we will
847  * have failed to drop it. binary_upgrade cannot generate any errors,
848  * so we assume the current role is already created.
849  */
850  if (!binary_upgrade ||
851  strcmp(PQgetvalue(res, i, i_is_current_user), "f") == 0)
852  appendPQExpBuffer(buf, "CREATE ROLE %s;\n", fmtId(rolename));
853  appendPQExpBuffer(buf, "ALTER ROLE %s WITH", fmtId(rolename));
854 
855  if (strcmp(PQgetvalue(res, i, i_rolsuper), "t") == 0)
856  appendPQExpBufferStr(buf, " SUPERUSER");
857  else
858  appendPQExpBufferStr(buf, " NOSUPERUSER");
859 
860  if (strcmp(PQgetvalue(res, i, i_rolinherit), "t") == 0)
861  appendPQExpBufferStr(buf, " INHERIT");
862  else
863  appendPQExpBufferStr(buf, " NOINHERIT");
864 
865  if (strcmp(PQgetvalue(res, i, i_rolcreaterole), "t") == 0)
866  appendPQExpBufferStr(buf, " CREATEROLE");
867  else
868  appendPQExpBufferStr(buf, " NOCREATEROLE");
869 
870  if (strcmp(PQgetvalue(res, i, i_rolcreatedb), "t") == 0)
871  appendPQExpBufferStr(buf, " CREATEDB");
872  else
873  appendPQExpBufferStr(buf, " NOCREATEDB");
874 
875  if (strcmp(PQgetvalue(res, i, i_rolcanlogin), "t") == 0)
876  appendPQExpBufferStr(buf, " LOGIN");
877  else
878  appendPQExpBufferStr(buf, " NOLOGIN");
879 
880  if (strcmp(PQgetvalue(res, i, i_rolreplication), "t") == 0)
881  appendPQExpBufferStr(buf, " REPLICATION");
882  else
883  appendPQExpBufferStr(buf, " NOREPLICATION");
884 
885  if (strcmp(PQgetvalue(res, i, i_rolbypassrls), "t") == 0)
886  appendPQExpBufferStr(buf, " BYPASSRLS");
887  else
888  appendPQExpBufferStr(buf, " NOBYPASSRLS");
889 
890  if (strcmp(PQgetvalue(res, i, i_rolconnlimit), "-1") != 0)
891  appendPQExpBuffer(buf, " CONNECTION LIMIT %s",
892  PQgetvalue(res, i, i_rolconnlimit));
893 
894 
895  if (!PQgetisnull(res, i, i_rolpassword) && !no_role_passwords)
896  {
897  appendPQExpBufferStr(buf, " PASSWORD ");
898  appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolpassword), conn);
899  }
900 
901  if (!PQgetisnull(res, i, i_rolvaliduntil))
902  appendPQExpBuffer(buf, " VALID UNTIL '%s'",
903  PQgetvalue(res, i, i_rolvaliduntil));
904 
905  appendPQExpBufferStr(buf, ";\n");
906 
907  if (!PQgetisnull(res, i, i_rolcomment))
908  {
909  appendPQExpBuffer(buf, "COMMENT ON ROLE %s IS ", fmtId(rolename));
910  appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolcomment), conn);
911  appendPQExpBufferStr(buf, ";\n");
912  }
913 
914  if (!no_security_labels && server_version >= 90200)
915  buildShSecLabels(conn, "pg_authid", auth_oid,
916  buf, "ROLE", rolename);
917 
918  fprintf(OPF, "%s", buf->data);
919  }
920 
921  /*
922  * Dump configuration settings for roles after all roles have been dumped.
923  * We do it this way because config settings for roles could mention the
924  * names of other roles.
925  */
926  for (i = 0; i < PQntuples(res); i++)
927  dumpUserConfig(conn, PQgetvalue(res, i, i_rolname));
928 
929  PQclear(res);
930 
931  fprintf(OPF, "\n\n");
932 
933  destroyPQExpBuffer(buf);
934 }
935 
936 
937 /*
938  * Dump role memberships. This code is used for 8.1 and later servers.
939  *
940  * Note: we expect dumpRoles already created all the roles, but there is
941  * no membership yet.
942  */
943 static void
945 {
947  PGresult *res;
948  int i;
949 
950  printfPQExpBuffer(buf, "SELECT ur.rolname AS roleid, "
951  "um.rolname AS member, "
952  "a.admin_option, "
953  "ug.rolname AS grantor "
954  "FROM pg_auth_members a "
955  "LEFT JOIN %s ur on ur.oid = a.roleid "
956  "LEFT JOIN %s um on um.oid = a.member "
957  "LEFT JOIN %s ug on ug.oid = a.grantor "
958  "WHERE NOT (ur.rolname ~ '^pg_' AND um.rolname ~ '^pg_')"
959  "ORDER BY 1,2,3", role_catalog, role_catalog, role_catalog);
960  res = executeQuery(conn, buf->data);
961 
962  if (PQntuples(res) > 0)
963  fprintf(OPF, "--\n-- Role memberships\n--\n\n");
964 
965  for (i = 0; i < PQntuples(res); i++)
966  {
967  char *roleid = PQgetvalue(res, i, 0);
968  char *member = PQgetvalue(res, i, 1);
969  char *option = PQgetvalue(res, i, 2);
970 
971  fprintf(OPF, "GRANT %s", fmtId(roleid));
972  fprintf(OPF, " TO %s", fmtId(member));
973  if (*option == 't')
974  fprintf(OPF, " WITH ADMIN OPTION");
975 
976  /*
977  * We don't track the grantor very carefully in the backend, so cope
978  * with the possibility that it has been dropped.
979  */
980  if (!PQgetisnull(res, i, 3))
981  {
982  char *grantor = PQgetvalue(res, i, 3);
983 
984  fprintf(OPF, " GRANTED BY %s", fmtId(grantor));
985  }
986  fprintf(OPF, ";\n");
987  }
988 
989  PQclear(res);
990  destroyPQExpBuffer(buf);
991 
992  fprintf(OPF, "\n\n");
993 }
994 
995 /*
996  * Dump group memberships from a pre-8.1 server. It's annoying that we
997  * can't share any useful amount of code with the post-8.1 case, but
998  * the catalog representations are too different.
999  *
1000  * Note: we expect dumpRoles already created all the roles, but there is
1001  * no membership yet.
1002  */
1003 static void
1005 {
1007  PGresult *res;
1008  int i;
1009 
1010  res = executeQuery(conn,
1011  "SELECT groname, grolist FROM pg_group ORDER BY 1");
1012 
1013  if (PQntuples(res) > 0)
1014  fprintf(OPF, "--\n-- Role memberships\n--\n\n");
1015 
1016  for (i = 0; i < PQntuples(res); i++)
1017  {
1018  char *groname = PQgetvalue(res, i, 0);
1019  char *grolist = PQgetvalue(res, i, 1);
1020  PGresult *res2;
1021  int j;
1022 
1023  /*
1024  * Array representation is {1,2,3} ... convert to (1,2,3)
1025  */
1026  if (strlen(grolist) < 3)
1027  continue;
1028 
1029  grolist = pg_strdup(grolist);
1030  grolist[0] = '(';
1031  grolist[strlen(grolist) - 1] = ')';
1032  printfPQExpBuffer(buf,
1033  "SELECT usename FROM pg_shadow "
1034  "WHERE usesysid IN %s ORDER BY 1",
1035  grolist);
1036  free(grolist);
1037 
1038  res2 = executeQuery(conn, buf->data);
1039 
1040  for (j = 0; j < PQntuples(res2); j++)
1041  {
1042  char *usename = PQgetvalue(res2, j, 0);
1043 
1044  /*
1045  * Don't try to grant a role to itself; can happen if old
1046  * installation has identically named user and group.
1047  */
1048  if (strcmp(groname, usename) == 0)
1049  continue;
1050 
1051  fprintf(OPF, "GRANT %s", fmtId(groname));
1052  fprintf(OPF, " TO %s;\n", fmtId(usename));
1053  }
1054 
1055  PQclear(res2);
1056  }
1057 
1058  PQclear(res);
1059  destroyPQExpBuffer(buf);
1060 
1061  fprintf(OPF, "\n\n");
1062 }
1063 
1064 
1065 /*
1066  * Drop tablespaces.
1067  */
1068 static void
1070 {
1071  PGresult *res;
1072  int i;
1073 
1074  /*
1075  * Get all tablespaces except built-in ones (which we assume are named
1076  * pg_xxx)
1077  */
1078  res = executeQuery(conn, "SELECT spcname "
1079  "FROM pg_catalog.pg_tablespace "
1080  "WHERE spcname !~ '^pg_' "
1081  "ORDER BY 1");
1082 
1083  if (PQntuples(res) > 0)
1084  fprintf(OPF, "--\n-- Drop tablespaces\n--\n\n");
1085 
1086  for (i = 0; i < PQntuples(res); i++)
1087  {
1088  char *spcname = PQgetvalue(res, i, 0);
1089 
1090  fprintf(OPF, "DROP TABLESPACE %s%s;\n",
1091  if_exists ? "IF EXISTS " : "",
1092  fmtId(spcname));
1093  }
1094 
1095  PQclear(res);
1096 
1097  fprintf(OPF, "\n\n");
1098 }
1099 
1100 /*
1101  * Dump tablespaces.
1102  */
1103 static void
1105 {
1106  PGresult *res;
1107  int i;
1108 
1109  /*
1110  * Get all tablespaces except built-in ones (which we assume are named
1111  * pg_xxx)
1112  *
1113  * For the tablespace ACLs, as of 9.6, we extract both the positive (as
1114  * spcacl) and negative (as rspcacl) ACLs, relative to the default ACL for
1115  * tablespaces, which are then passed to buildACLCommands() below.
1116  *
1117  * See buildACLQueries() and buildACLCommands().
1118  *
1119  * Note that we do not support initial privileges (pg_init_privs) on
1120  * tablespaces.
1121  */
1122  if (server_version >= 90600)
1123  res = executeQuery(conn, "SELECT oid, spcname, "
1124  "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1125  "pg_catalog.pg_tablespace_location(oid), "
1126  "(SELECT pg_catalog.array_agg(acl) FROM (SELECT pg_catalog.unnest(coalesce(spcacl,pg_catalog.acldefault('t',spcowner))) AS acl "
1127  "EXCEPT SELECT pg_catalog.unnest(pg_catalog.acldefault('t',spcowner))) as foo)"
1128  "AS spcacl,"
1129  "(SELECT pg_catalog.array_agg(acl) FROM (SELECT pg_catalog.unnest(pg_catalog.acldefault('t',spcowner)) AS acl "
1130  "EXCEPT SELECT pg_catalog.unnest(coalesce(spcacl,pg_catalog.acldefault('t',spcowner)))) as foo)"
1131  "AS rspcacl,"
1132  "array_to_string(spcoptions, ', '),"
1133  "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1134  "FROM pg_catalog.pg_tablespace "
1135  "WHERE spcname !~ '^pg_' "
1136  "ORDER BY 1");
1137  else if (server_version >= 90200)
1138  res = executeQuery(conn, "SELECT oid, spcname, "
1139  "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1140  "pg_catalog.pg_tablespace_location(oid), "
1141  "spcacl, '' as rspcacl, "
1142  "array_to_string(spcoptions, ', '),"
1143  "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1144  "FROM pg_catalog.pg_tablespace "
1145  "WHERE spcname !~ '^pg_' "
1146  "ORDER BY 1");
1147  else if (server_version >= 90000)
1148  res = executeQuery(conn, "SELECT oid, spcname, "
1149  "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1150  "spclocation, spcacl, '' as rspcacl, "
1151  "array_to_string(spcoptions, ', '),"
1152  "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1153  "FROM pg_catalog.pg_tablespace "
1154  "WHERE spcname !~ '^pg_' "
1155  "ORDER BY 1");
1156  else if (server_version >= 80200)
1157  res = executeQuery(conn, "SELECT oid, spcname, "
1158  "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1159  "spclocation, spcacl, '' as rspcacl, null, "
1160  "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1161  "FROM pg_catalog.pg_tablespace "
1162  "WHERE spcname !~ '^pg_' "
1163  "ORDER BY 1");
1164  else
1165  res = executeQuery(conn, "SELECT oid, spcname, "
1166  "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1167  "spclocation, spcacl, '' as rspcacl, "
1168  "null, null "
1169  "FROM pg_catalog.pg_tablespace "
1170  "WHERE spcname !~ '^pg_' "
1171  "ORDER BY 1");
1172 
1173  if (PQntuples(res) > 0)
1174  fprintf(OPF, "--\n-- Tablespaces\n--\n\n");
1175 
1176  for (i = 0; i < PQntuples(res); i++)
1177  {
1179  uint32 spcoid = atooid(PQgetvalue(res, i, 0));
1180  char *spcname = PQgetvalue(res, i, 1);
1181  char *spcowner = PQgetvalue(res, i, 2);
1182  char *spclocation = PQgetvalue(res, i, 3);
1183  char *spcacl = PQgetvalue(res, i, 4);
1184  char *rspcacl = PQgetvalue(res, i, 5);
1185  char *spcoptions = PQgetvalue(res, i, 6);
1186  char *spccomment = PQgetvalue(res, i, 7);
1187  char *fspcname;
1188 
1189  /* needed for buildACLCommands() */
1190  fspcname = pg_strdup(fmtId(spcname));
1191 
1192  appendPQExpBuffer(buf, "CREATE TABLESPACE %s", fspcname);
1193  appendPQExpBuffer(buf, " OWNER %s", fmtId(spcowner));
1194 
1195  appendPQExpBufferStr(buf, " LOCATION ");
1196  appendStringLiteralConn(buf, spclocation, conn);
1197  appendPQExpBufferStr(buf, ";\n");
1198 
1199  if (spcoptions && spcoptions[0] != '\0')
1200  appendPQExpBuffer(buf, "ALTER TABLESPACE %s SET (%s);\n",
1201  fspcname, spcoptions);
1202 
1203  if (!skip_acls &&
1204  !buildACLCommands(fspcname, NULL, "TABLESPACE", spcacl, rspcacl,
1205  spcowner, "", server_version, buf))
1206  {
1207  fprintf(stderr, _("%s: could not parse ACL list (%s) for tablespace \"%s\"\n"),
1208  progname, spcacl, fspcname);
1209  PQfinish(conn);
1210  exit_nicely(1);
1211  }
1212 
1213  if (spccomment && strlen(spccomment))
1214  {
1215  appendPQExpBuffer(buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
1216  appendStringLiteralConn(buf, spccomment, conn);
1217  appendPQExpBufferStr(buf, ";\n");
1218  }
1219 
1220  if (!no_security_labels && server_version >= 90200)
1221  buildShSecLabels(conn, "pg_tablespace", spcoid,
1222  buf, "TABLESPACE", fspcname);
1223 
1224  fprintf(OPF, "%s", buf->data);
1225 
1226  free(fspcname);
1227  destroyPQExpBuffer(buf);
1228  }
1229 
1230  PQclear(res);
1231  fprintf(OPF, "\n\n");
1232 }
1233 
1234 
1235 /*
1236  * Dump commands to drop each database.
1237  *
1238  * This should match the set of databases targeted by dumpCreateDB().
1239  */
1240 static void
1242 {
1243  PGresult *res;
1244  int i;
1245 
1246  res = executeQuery(conn,
1247  "SELECT datname "
1248  "FROM pg_database d "
1249  "WHERE datallowconn ORDER BY 1");
1250 
1251  if (PQntuples(res) > 0)
1252  fprintf(OPF, "--\n-- Drop databases\n--\n\n");
1253 
1254  for (i = 0; i < PQntuples(res); i++)
1255  {
1256  char *dbname = PQgetvalue(res, i, 0);
1257 
1258  /*
1259  * Skip "template1" and "postgres"; the restore script is almost
1260  * certainly going to be run in one or the other, and we don't know
1261  * which. This must agree with dumpCreateDB's choices!
1262  */
1263  if (strcmp(dbname, "template1") != 0 &&
1264  strcmp(dbname, "postgres") != 0)
1265  {
1266  fprintf(OPF, "DROP DATABASE %s%s;\n",
1267  if_exists ? "IF EXISTS " : "",
1268  fmtId(dbname));
1269  }
1270  }
1271 
1272  PQclear(res);
1273 
1274  fprintf(OPF, "\n\n");
1275 }
1276 
1277 /*
1278  * Dump commands to create each database.
1279  *
1280  * To minimize the number of reconnections (and possibly ensuing
1281  * password prompts) required by the output script, we emit all CREATE
1282  * DATABASE commands during the initial phase of the script, and then
1283  * run pg_dump for each database to dump the contents of that
1284  * database. We skip databases marked not datallowconn, since we'd be
1285  * unable to connect to them anyway (and besides, we don't want to
1286  * dump template0).
1287  */
1288 static void
1290 {
1292  char *default_encoding = NULL;
1293  char *default_collate = NULL;
1294  char *default_ctype = NULL;
1295  PGresult *res;
1296  int i;
1297 
1298  fprintf(OPF, "--\n-- Database creation\n--\n\n");
1299 
1300  /*
1301  * First, get the installation's default encoding and locale information.
1302  * We will dump encoding and locale specifications in the CREATE DATABASE
1303  * commands for just those databases with values different from defaults.
1304  *
1305  * We consider template0's encoding and locale to define the installation
1306  * default. Pre-8.4 installations do not have per-database locale
1307  * settings; for them, every database must necessarily be using the
1308  * installation default, so there's no need to do anything.
1309  */
1310  if (server_version >= 80400)
1311  res = executeQuery(conn,
1312  "SELECT pg_encoding_to_char(encoding), "
1313  "datcollate, datctype "
1314  "FROM pg_database "
1315  "WHERE datname = 'template0'");
1316  else
1317  res = executeQuery(conn,
1318  "SELECT pg_encoding_to_char(encoding), "
1319  "null::text AS datcollate, null::text AS datctype "
1320  "FROM pg_database "
1321  "WHERE datname = 'template0'");
1322 
1323  /* If for some reason the template DB isn't there, treat as unknown */
1324  if (PQntuples(res) > 0)
1325  {
1326  if (!PQgetisnull(res, 0, 0))
1327  default_encoding = pg_strdup(PQgetvalue(res, 0, 0));
1328  if (!PQgetisnull(res, 0, 1))
1329  default_collate = pg_strdup(PQgetvalue(res, 0, 1));
1330  if (!PQgetisnull(res, 0, 2))
1331  default_ctype = pg_strdup(PQgetvalue(res, 0, 2));
1332  }
1333 
1334  PQclear(res);
1335 
1336 
1337  /*
1338  * Now collect all the information about databases to dump.
1339  *
1340  * For the database ACLs, as of 9.6, we extract both the positive (as
1341  * datacl) and negative (as rdatacl) ACLs, relative to the default ACL for
1342  * databases, which are then passed to buildACLCommands() below.
1343  *
1344  * See buildACLQueries() and buildACLCommands().
1345  *
1346  * Note that we do not support initial privileges (pg_init_privs) on
1347  * databases.
1348  */
1349  if (server_version >= 90600)
1350  printfPQExpBuffer(buf,
1351  "SELECT datname, "
1352  "coalesce(rolname, (select rolname from %s where oid=(select datdba from pg_database where datname='template0'))), "
1353  "pg_encoding_to_char(d.encoding), "
1354  "datcollate, datctype, datfrozenxid, datminmxid, "
1355  "datistemplate, "
1356  "(SELECT pg_catalog.array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
1357  " SELECT pg_catalog.unnest(coalesce(datacl,pg_catalog.acldefault('d',datdba))) AS acl "
1358  " EXCEPT SELECT pg_catalog.unnest(pg_catalog.acldefault('d',datdba))) as datacls)"
1359  "AS datacl, "
1360  "(SELECT pg_catalog.array_agg(acl ORDER BY acl::text COLLATE \"C\") FROM ( "
1361  " SELECT pg_catalog.unnest(pg_catalog.acldefault('d',datdba)) AS acl "
1362  " EXCEPT SELECT pg_catalog.unnest(coalesce(datacl,pg_catalog.acldefault('d',datdba)))) as rdatacls)"
1363  "AS rdatacl, "
1364  "datconnlimit, "
1365  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1366  "FROM pg_database d LEFT JOIN %s u ON (datdba = u.oid) "
1367  "WHERE datallowconn ORDER BY 1", role_catalog, role_catalog);
1368  else if (server_version >= 90300)
1369  printfPQExpBuffer(buf,
1370  "SELECT datname, "
1371  "coalesce(rolname, (select rolname from %s where oid=(select datdba from pg_database where datname='template0'))), "
1372  "pg_encoding_to_char(d.encoding), "
1373  "datcollate, datctype, datfrozenxid, datminmxid, "
1374  "datistemplate, datacl, '' as rdatacl, "
1375  "datconnlimit, "
1376  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1377  "FROM pg_database d LEFT JOIN %s u ON (datdba = u.oid) "
1378  "WHERE datallowconn ORDER BY 1", role_catalog, role_catalog);
1379  else if (server_version >= 80400)
1380  printfPQExpBuffer(buf,
1381  "SELECT datname, "
1382  "coalesce(rolname, (select rolname from %s where oid=(select datdba from pg_database where datname='template0'))), "
1383  "pg_encoding_to_char(d.encoding), "
1384  "datcollate, datctype, datfrozenxid, 0 AS datminmxid, "
1385  "datistemplate, datacl, '' as rdatacl, "
1386  "datconnlimit, "
1387  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1388  "FROM pg_database d LEFT JOIN %s u ON (datdba = u.oid) "
1389  "WHERE datallowconn ORDER BY 1", role_catalog, role_catalog);
1390  else if (server_version >= 80100)
1391  printfPQExpBuffer(buf,
1392  "SELECT datname, "
1393  "coalesce(rolname, (select rolname from %s where oid=(select datdba from pg_database where datname='template0'))), "
1394  "pg_encoding_to_char(d.encoding), "
1395  "null::text AS datcollate, null::text AS datctype, datfrozenxid, 0 AS datminmxid, "
1396  "datistemplate, datacl, '' as rdatacl, "
1397  "datconnlimit, "
1398  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1399  "FROM pg_database d LEFT JOIN %s u ON (datdba = u.oid) "
1400  "WHERE datallowconn ORDER BY 1", role_catalog, role_catalog);
1401  else
1402  printfPQExpBuffer(buf,
1403  "SELECT datname, "
1404  "coalesce(usename, (select usename from pg_shadow where usesysid=(select datdba from pg_database where datname='template0'))), "
1405  "pg_encoding_to_char(d.encoding), "
1406  "null::text AS datcollate, null::text AS datctype, datfrozenxid, 0 AS datminmxid, "
1407  "datistemplate, datacl, '' as rdatacl, "
1408  "-1 as datconnlimit, "
1409  "(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1410  "FROM pg_database d LEFT JOIN pg_shadow u ON (datdba = usesysid) "
1411  "WHERE datallowconn ORDER BY 1");
1412 
1413  res = executeQuery(conn, buf->data);
1414 
1415  for (i = 0; i < PQntuples(res); i++)
1416  {
1417  char *dbname = PQgetvalue(res, i, 0);
1418  char *dbowner = PQgetvalue(res, i, 1);
1419  char *dbencoding = PQgetvalue(res, i, 2);
1420  char *dbcollate = PQgetvalue(res, i, 3);
1421  char *dbctype = PQgetvalue(res, i, 4);
1422  uint32 dbfrozenxid = atooid(PQgetvalue(res, i, 5));
1423  uint32 dbminmxid = atooid(PQgetvalue(res, i, 6));
1424  char *dbistemplate = PQgetvalue(res, i, 7);
1425  char *dbacl = PQgetvalue(res, i, 8);
1426  char *rdbacl = PQgetvalue(res, i, 9);
1427  char *dbconnlimit = PQgetvalue(res, i, 10);
1428  char *dbtablespace = PQgetvalue(res, i, 11);
1429  char *fdbname;
1430 
1431  fdbname = pg_strdup(fmtId(dbname));
1432 
1433  resetPQExpBuffer(buf);
1434 
1435  /*
1436  * Skip the CREATE DATABASE commands for "template1" and "postgres",
1437  * since they are presumably already there in the destination cluster.
1438  * We do want to emit their ACLs and config options if any, however.
1439  */
1440  if (strcmp(dbname, "template1") != 0 &&
1441  strcmp(dbname, "postgres") != 0)
1442  {
1443  appendPQExpBuffer(buf, "CREATE DATABASE %s", fdbname);
1444 
1445  appendPQExpBufferStr(buf, " WITH TEMPLATE = template0");
1446 
1447  if (strlen(dbowner) != 0)
1448  appendPQExpBuffer(buf, " OWNER = %s", fmtId(dbowner));
1449 
1450  if (default_encoding && strcmp(dbencoding, default_encoding) != 0)
1451  {
1452  appendPQExpBufferStr(buf, " ENCODING = ");
1453  appendStringLiteralConn(buf, dbencoding, conn);
1454  }
1455 
1456  if (default_collate && strcmp(dbcollate, default_collate) != 0)
1457  {
1458  appendPQExpBufferStr(buf, " LC_COLLATE = ");
1459  appendStringLiteralConn(buf, dbcollate, conn);
1460  }
1461 
1462  if (default_ctype && strcmp(dbctype, default_ctype) != 0)
1463  {
1464  appendPQExpBufferStr(buf, " LC_CTYPE = ");
1465  appendStringLiteralConn(buf, dbctype, conn);
1466  }
1467 
1468  /*
1469  * Output tablespace if it isn't the default. For default, it
1470  * uses the default from the template database. If tablespace is
1471  * specified and tablespace creation failed earlier, (e.g. no such
1472  * directory), the database creation will fail too. One solution
1473  * would be to use 'SET default_tablespace' like we do in pg_dump
1474  * for setting non-default database locations.
1475  */
1476  if (strcmp(dbtablespace, "pg_default") != 0 && !no_tablespaces)
1477  appendPQExpBuffer(buf, " TABLESPACE = %s",
1478  fmtId(dbtablespace));
1479 
1480  if (strcmp(dbistemplate, "t") == 0)
1481  appendPQExpBuffer(buf, " IS_TEMPLATE = true");
1482 
1483  if (strcmp(dbconnlimit, "-1") != 0)
1484  appendPQExpBuffer(buf, " CONNECTION LIMIT = %s",
1485  dbconnlimit);
1486 
1487  appendPQExpBufferStr(buf, ";\n");
1488  }
1489  else if (strcmp(dbtablespace, "pg_default") != 0 && !no_tablespaces)
1490  {
1491  /*
1492  * Cannot change tablespace of the database we're connected to, so
1493  * to move "postgres" to another tablespace, we connect to
1494  * "template1", and vice versa.
1495  */
1496  if (strcmp(dbname, "postgres") == 0)
1497  appendPQExpBuffer(buf, "\\connect template1\n");
1498  else
1499  appendPQExpBuffer(buf, "\\connect postgres\n");
1500 
1501  appendPQExpBuffer(buf, "ALTER DATABASE %s SET TABLESPACE %s;\n",
1502  fdbname, fmtId(dbtablespace));
1503 
1504  /* connect to original database */
1505  appendPsqlMetaConnect(buf, dbname);
1506  }
1507 
1508  if (binary_upgrade)
1509  {
1510  appendPQExpBufferStr(buf, "-- For binary upgrade, set datfrozenxid and datminmxid.\n");
1511  appendPQExpBuffer(buf, "UPDATE pg_catalog.pg_database "
1512  "SET datfrozenxid = '%u', datminmxid = '%u' "
1513  "WHERE datname = ",
1514  dbfrozenxid, dbminmxid);
1515  appendStringLiteralConn(buf, dbname, conn);
1516  appendPQExpBufferStr(buf, ";\n");
1517  }
1518 
1519  if (!skip_acls &&
1520  !buildACLCommands(fdbname, NULL, "DATABASE",
1521  dbacl, rdbacl, dbowner,
1522  "", server_version, buf))
1523  {
1524  fprintf(stderr, _("%s: could not parse ACL list (%s) for database \"%s\"\n"),
1525  progname, dbacl, fdbname);
1526  PQfinish(conn);
1527  exit_nicely(1);
1528  }
1529 
1530  fprintf(OPF, "%s", buf->data);
1531 
1532  dumpDatabaseConfig(conn, dbname);
1533 
1534  free(fdbname);
1535  }
1536 
1537  if (default_encoding)
1538  free(default_encoding);
1539  if (default_collate)
1540  free(default_collate);
1541  if (default_ctype)
1542  free(default_ctype);
1543 
1544  PQclear(res);
1545  destroyPQExpBuffer(buf);
1546 
1547  fprintf(OPF, "\n\n");
1548 }
1549 
1550 
1551 /*
1552  * Dump database-specific configuration
1553  */
1554 static void
1556 {
1558  int count = 1;
1559 
1560  for (;;)
1561  {
1562  PGresult *res;
1563 
1564  if (server_version >= 90000)
1565  printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting WHERE "
1566  "setrole = 0 AND setdatabase = (SELECT oid FROM pg_database WHERE datname = ", count);
1567  else
1568  printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE datname = ", count);
1569  appendStringLiteralConn(buf, dbname, conn);
1570 
1571  if (server_version >= 90000)
1572  appendPQExpBuffer(buf, ")");
1573 
1574  res = executeQuery(conn, buf->data);
1575  if (PQntuples(res) == 1 &&
1576  !PQgetisnull(res, 0, 0))
1577  {
1578  makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
1579  "DATABASE", dbname, NULL, NULL);
1580  PQclear(res);
1581  count++;
1582  }
1583  else
1584  {
1585  PQclear(res);
1586  break;
1587  }
1588  }
1589 
1590  destroyPQExpBuffer(buf);
1591 }
1592 
1593 
1594 
1595 /*
1596  * Dump user-specific configuration
1597  */
1598 static void
1600 {
1602  int count = 1;
1603 
1604  for (;;)
1605  {
1606  PGresult *res;
1607 
1608  if (server_version >= 90000)
1609  printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting WHERE "
1610  "setdatabase = 0 AND setrole = "
1611  "(SELECT oid FROM %s WHERE rolname = ", count, role_catalog);
1612  else if (server_version >= 80100)
1613  printfPQExpBuffer(buf, "SELECT rolconfig[%d] FROM %s WHERE rolname = ", count, role_catalog);
1614  else
1615  printfPQExpBuffer(buf, "SELECT useconfig[%d] FROM pg_shadow WHERE usename = ", count);
1616  appendStringLiteralConn(buf, username, conn);
1617  if (server_version >= 90000)
1618  appendPQExpBufferChar(buf, ')');
1619 
1620  res = executeQuery(conn, buf->data);
1621  if (PQntuples(res) == 1 &&
1622  !PQgetisnull(res, 0, 0))
1623  {
1624  makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
1625  "ROLE", username, NULL, NULL);
1626  PQclear(res);
1627  count++;
1628  }
1629  else
1630  {
1631  PQclear(res);
1632  break;
1633  }
1634  }
1635 
1636  destroyPQExpBuffer(buf);
1637 }
1638 
1639 
1640 /*
1641  * Dump user-and-database-specific configuration
1642  */
1643 static void
1645 {
1647  PGresult *res;
1648  int i;
1649 
1650  printfPQExpBuffer(buf, "SELECT rolname, datname, unnest(setconfig) "
1651  "FROM pg_db_role_setting, %s u, pg_database "
1652  "WHERE setrole = u.oid AND setdatabase = pg_database.oid", role_catalog);
1653  res = executeQuery(conn, buf->data);
1654 
1655  if (PQntuples(res) > 0)
1656  {
1657  fprintf(OPF, "--\n-- Per-Database Role Settings \n--\n\n");
1658 
1659  for (i = 0; i < PQntuples(res); i++)
1660  {
1661  makeAlterConfigCommand(conn, PQgetvalue(res, i, 2),
1662  "ROLE", PQgetvalue(res, i, 0),
1663  "DATABASE", PQgetvalue(res, i, 1));
1664  }
1665 
1666  fprintf(OPF, "\n\n");
1667  }
1668 
1669  PQclear(res);
1670  destroyPQExpBuffer(buf);
1671 }
1672 
1673 
1674 /*
1675  * Helper function for dumpXXXConfig().
1676  */
1677 static void
1678 makeAlterConfigCommand(PGconn *conn, const char *arrayitem,
1679  const char *type, const char *name,
1680  const char *type2, const char *name2)
1681 {
1682  char *pos;
1683  char *mine;
1684  PQExpBuffer buf;
1685 
1686  mine = pg_strdup(arrayitem);
1687  pos = strchr(mine, '=');
1688  if (pos == NULL)
1689  {
1690  free(mine);
1691  return;
1692  }
1693 
1694  buf = createPQExpBuffer();
1695 
1696  *pos = 0;
1697  appendPQExpBuffer(buf, "ALTER %s %s ", type, fmtId(name));
1698  if (type2 != NULL && name2 != NULL)
1699  appendPQExpBuffer(buf, "IN %s %s ", type2, fmtId(name2));
1700  appendPQExpBuffer(buf, "SET %s TO ", fmtId(mine));
1701 
1702  /*
1703  * Some GUC variable names are 'LIST' type and hence must not be quoted.
1704  */
1705  if (pg_strcasecmp(mine, "DateStyle") == 0
1706  || pg_strcasecmp(mine, "search_path") == 0)
1707  appendPQExpBufferStr(buf, pos + 1);
1708  else
1709  appendStringLiteralConn(buf, pos + 1, conn);
1710  appendPQExpBufferStr(buf, ";\n");
1711 
1712  fprintf(OPF, "%s", buf->data);
1713  destroyPQExpBuffer(buf);
1714  free(mine);
1715 }
1716 
1717 
1718 
1719 /*
1720  * Dump contents of databases.
1721  */
1722 static void
1724 {
1725  PGresult *res;
1726  int i;
1727 
1728  res = executeQuery(conn, "SELECT datname FROM pg_database WHERE datallowconn ORDER BY 1");
1729 
1730  for (i = 0; i < PQntuples(res); i++)
1731  {
1732  int ret;
1733 
1734  char *dbname = PQgetvalue(res, i, 0);
1735  PQExpBufferData connectbuf;
1736 
1737  if (verbose)
1738  fprintf(stderr, _("%s: dumping database \"%s\"...\n"), progname, dbname);
1739 
1740  initPQExpBuffer(&connectbuf);
1741  appendPsqlMetaConnect(&connectbuf, dbname);
1742  fprintf(OPF, "%s\n", connectbuf.data);
1743  termPQExpBuffer(&connectbuf);
1744 
1745  /*
1746  * Restore will need to write to the target cluster. This connection
1747  * setting is emitted for pg_dumpall rather than in the code also used
1748  * by pg_dump, so that a cluster with databases or users which have
1749  * this flag turned on can still be replicated through pg_dumpall
1750  * without editing the file or stream. With pg_dump there are many
1751  * other ways to allow the file to be used, and leaving it out allows
1752  * users to protect databases from being accidental restore targets.
1753  */
1754  fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
1755 
1756  if (filename)
1757  fclose(OPF);
1758 
1759  ret = runPgDump(dbname);
1760  if (ret != 0)
1761  {
1762  fprintf(stderr, _("%s: pg_dump failed on database \"%s\", exiting\n"), progname, dbname);
1763  exit_nicely(1);
1764  }
1765 
1766  if (filename)
1767  {
1768  OPF = fopen(filename, PG_BINARY_A);
1769  if (!OPF)
1770  {
1771  fprintf(stderr, _("%s: could not re-open the output file \"%s\": %s\n"),
1772  progname, filename, strerror(errno));
1773  exit_nicely(1);
1774  }
1775  }
1776 
1777  }
1778 
1779  PQclear(res);
1780 }
1781 
1782 
1783 
1784 /*
1785  * Run pg_dump on dbname.
1786  */
1787 static int
1788 runPgDump(const char *dbname)
1789 {
1790  PQExpBuffer connstrbuf = createPQExpBuffer();
1792  int ret;
1793 
1794  appendPQExpBuffer(cmd, "\"%s\" %s", pg_dump_bin,
1795  pgdumpopts->data);
1796 
1797  /*
1798  * If we have a filename, use the undocumented plain-append pg_dump
1799  * format.
1800  */
1801  if (filename)
1802  appendPQExpBufferStr(cmd, " -Fa ");
1803  else
1804  appendPQExpBufferStr(cmd, " -Fp ");
1805 
1806  /*
1807  * Append the database name to the already-constructed stem of connection
1808  * string.
1809  */
1810  appendPQExpBuffer(connstrbuf, "%s dbname=", connstr);
1811  appendConnStrVal(connstrbuf, dbname);
1812 
1813  appendShellString(cmd, connstrbuf->data);
1814 
1815  if (verbose)
1816  fprintf(stderr, _("%s: running \"%s\"\n"), progname, cmd->data);
1817 
1818  fflush(stdout);
1819  fflush(stderr);
1820 
1821  ret = system(cmd->data);
1822 
1823  destroyPQExpBuffer(cmd);
1824  destroyPQExpBuffer(connstrbuf);
1825 
1826  return ret;
1827 }
1828 
1829 /*
1830  * buildShSecLabels
1831  *
1832  * Build SECURITY LABEL command(s) for a shared object
1833  *
1834  * The caller has to provide object type and identifier to select security
1835  * labels from pg_seclabels system view.
1836  */
1837 static void
1838 buildShSecLabels(PGconn *conn, const char *catalog_name, uint32 objectId,
1839  PQExpBuffer buffer, const char *target, const char *objname)
1840 {
1842  PGresult *res;
1843 
1844  buildShSecLabelQuery(conn, catalog_name, objectId, sql);
1845  res = executeQuery(conn, sql->data);
1846  emitShSecLabels(conn, res, buffer, target, objname);
1847 
1848  PQclear(res);
1849  destroyPQExpBuffer(sql);
1850 }
1851 
1852 /*
1853  * Make a database connection with the given parameters. An
1854  * interactive password prompt is automatically issued if required.
1855  *
1856  * If fail_on_error is false, we return NULL without printing any message
1857  * on failure, but preserve any prompted password for the next try.
1858  *
1859  * On success, the global variable 'connstr' is set to a connection string
1860  * containing the options used.
1861  */
1862 static PGconn *
1863 connectDatabase(const char *dbname, const char *connection_string,
1864  const char *pghost, const char *pgport, const char *pguser,
1865  trivalue prompt_password, bool fail_on_error)
1866 {
1867  PGconn *conn;
1868  bool new_pass;
1869  const char *remoteversion_str;
1870  int my_version;
1871  const char **keywords = NULL;
1872  const char **values = NULL;
1873  PQconninfoOption *conn_opts = NULL;
1874  static bool have_password = false;
1875  static char password[100];
1876 
1877  if (prompt_password == TRI_YES && !have_password)
1878  {
1879  simple_prompt("Password: ", password, sizeof(password), false);
1880  have_password = true;
1881  }
1882 
1883  /*
1884  * Start the connection. Loop until we have a password if requested by
1885  * backend.
1886  */
1887  do
1888  {
1889  int argcount = 6;
1890  PQconninfoOption *conn_opt;
1891  char *err_msg = NULL;
1892  int i = 0;
1893 
1894  if (keywords)
1895  free(keywords);
1896  if (values)
1897  free(values);
1898  if (conn_opts)
1899  PQconninfoFree(conn_opts);
1900 
1901  /*
1902  * Merge the connection info inputs given in form of connection string
1903  * and other options. Explicitly discard any dbname value in the
1904  * connection string; otherwise, PQconnectdbParams() would interpret
1905  * that value as being itself a connection string.
1906  */
1907  if (connection_string)
1908  {
1909  conn_opts = PQconninfoParse(connection_string, &err_msg);
1910  if (conn_opts == NULL)
1911  {
1912  fprintf(stderr, "%s: %s", progname, err_msg);
1913  exit_nicely(1);
1914  }
1915 
1916  for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1917  {
1918  if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1919  strcmp(conn_opt->keyword, "dbname") != 0)
1920  argcount++;
1921  }
1922 
1923  keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1924  values = pg_malloc0((argcount + 1) * sizeof(*values));
1925 
1926  for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1927  {
1928  if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1929  strcmp(conn_opt->keyword, "dbname") != 0)
1930  {
1931  keywords[i] = conn_opt->keyword;
1932  values[i] = conn_opt->val;
1933  i++;
1934  }
1935  }
1936  }
1937  else
1938  {
1939  keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1940  values = pg_malloc0((argcount + 1) * sizeof(*values));
1941  }
1942 
1943  if (pghost)
1944  {
1945  keywords[i] = "host";
1946  values[i] = pghost;
1947  i++;
1948  }
1949  if (pgport)
1950  {
1951  keywords[i] = "port";
1952  values[i] = pgport;
1953  i++;
1954  }
1955  if (pguser)
1956  {
1957  keywords[i] = "user";
1958  values[i] = pguser;
1959  i++;
1960  }
1961  if (have_password)
1962  {
1963  keywords[i] = "password";
1964  values[i] = password;
1965  i++;
1966  }
1967  if (dbname)
1968  {
1969  keywords[i] = "dbname";
1970  values[i] = dbname;
1971  i++;
1972  }
1973  keywords[i] = "fallback_application_name";
1974  values[i] = progname;
1975  i++;
1976 
1977  new_pass = false;
1978  conn = PQconnectdbParams(keywords, values, true);
1979 
1980  if (!conn)
1981  {
1982  fprintf(stderr, _("%s: could not connect to database \"%s\"\n"),
1983  progname, dbname);
1984  exit_nicely(1);
1985  }
1986 
1987  if (PQstatus(conn) == CONNECTION_BAD &&
1988  PQconnectionNeedsPassword(conn) &&
1989  !have_password &&
1990  prompt_password != TRI_NO)
1991  {
1992  PQfinish(conn);
1993  simple_prompt("Password: ", password, sizeof(password), false);
1994  have_password = true;
1995  new_pass = true;
1996  }
1997  } while (new_pass);
1998 
1999  /* check to see that the backend connection was successfully made */
2000  if (PQstatus(conn) == CONNECTION_BAD)
2001  {
2002  if (fail_on_error)
2003  {
2004  fprintf(stderr,
2005  _("%s: could not connect to database \"%s\": %s\n"),
2006  progname, dbname, PQerrorMessage(conn));
2007  exit_nicely(1);
2008  }
2009  else
2010  {
2011  PQfinish(conn);
2012 
2013  free(keywords);
2014  free(values);
2015  PQconninfoFree(conn_opts);
2016 
2017  return NULL;
2018  }
2019  }
2020 
2021  /*
2022  * Ok, connected successfully. Remember the options used, in the form of a
2023  * connection string.
2024  */
2025  connstr = constructConnStr(keywords, values);
2026 
2027  free(keywords);
2028  free(values);
2029  PQconninfoFree(conn_opts);
2030 
2031  /* Check version */
2032  remoteversion_str = PQparameterStatus(conn, "server_version");
2033  if (!remoteversion_str)
2034  {
2035  fprintf(stderr, _("%s: could not get server version\n"), progname);
2036  exit_nicely(1);
2037  }
2039  if (server_version == 0)
2040  {
2041  fprintf(stderr, _("%s: could not parse server version \"%s\"\n"),
2042  progname, remoteversion_str);
2043  exit_nicely(1);
2044  }
2045 
2046  my_version = PG_VERSION_NUM;
2047 
2048  /*
2049  * We allow the server to be back to 8.0, and up to any minor release of
2050  * our own major version. (See also version check in pg_dump.c.)
2051  */
2052  if (my_version != server_version
2053  && (server_version < 80000 ||
2054  (server_version / 100) > (my_version / 100)))
2055  {
2056  fprintf(stderr, _("server version: %s; %s version: %s\n"),
2057  remoteversion_str, progname, PG_VERSION);
2058  fprintf(stderr, _("aborting because of server version mismatch\n"));
2059  exit_nicely(1);
2060  }
2061 
2062  /*
2063  * Make sure we are not fooled by non-system schemas in the search path.
2064  */
2065  executeCommand(conn, "SET search_path = pg_catalog");
2066 
2067  return conn;
2068 }
2069 
2070 /* ----------
2071  * Construct a connection string from the given keyword/value pairs. It is
2072  * used to pass the connection options to the pg_dump subprocess.
2073  *
2074  * The following parameters are excluded:
2075  * dbname - varies in each pg_dump invocation
2076  * password - it's not secure to pass a password on the command line
2077  * fallback_application_name - we'll let pg_dump set it
2078  * ----------
2079  */
2080 static char *
2081 constructConnStr(const char **keywords, const char **values)
2082 {
2084  char *connstr;
2085  int i;
2086  bool firstkeyword = true;
2087 
2088  /* Construct a new connection string in key='value' format. */
2089  for (i = 0; keywords[i] != NULL; i++)
2090  {
2091  if (strcmp(keywords[i], "dbname") == 0 ||
2092  strcmp(keywords[i], "password") == 0 ||
2093  strcmp(keywords[i], "fallback_application_name") == 0)
2094  continue;
2095 
2096  if (!firstkeyword)
2097  appendPQExpBufferChar(buf, ' ');
2098  firstkeyword = false;
2099  appendPQExpBuffer(buf, "%s=", keywords[i]);
2100  appendConnStrVal(buf, values[i]);
2101  }
2102 
2103  connstr = pg_strdup(buf->data);
2104  destroyPQExpBuffer(buf);
2105  return connstr;
2106 }
2107 
2108 /*
2109  * Run a query, return the results, exit program on failure.
2110  */
2111 static PGresult *
2112 executeQuery(PGconn *conn, const char *query)
2113 {
2114  PGresult *res;
2115 
2116  if (verbose)
2117  fprintf(stderr, _("%s: executing %s\n"), progname, query);
2118 
2119  res = PQexec(conn, query);
2120  if (!res ||
2122  {
2123  fprintf(stderr, _("%s: query failed: %s"),
2124  progname, PQerrorMessage(conn));
2125  fprintf(stderr, _("%s: query was: %s\n"),
2126  progname, query);
2127  PQfinish(conn);
2128  exit_nicely(1);
2129  }
2130 
2131  return res;
2132 }
2133 
2134 /*
2135  * As above for a SQL command (which returns nothing).
2136  */
2137 static void
2138 executeCommand(PGconn *conn, const char *query)
2139 {
2140  PGresult *res;
2141 
2142  if (verbose)
2143  fprintf(stderr, _("%s: executing %s\n"), progname, query);
2144 
2145  res = PQexec(conn, query);
2146  if (!res ||
2148  {
2149  fprintf(stderr, _("%s: query failed: %s"),
2150  progname, PQerrorMessage(conn));
2151  fprintf(stderr, _("%s: query was: %s\n"),
2152  progname, query);
2153  PQfinish(conn);
2154  exit_nicely(1);
2155  }
2156 
2157  PQclear(res);
2158 }
2159 
2160 
2161 /*
2162  * dumpTimestamp
2163  */
2164 static void
2165 dumpTimestamp(const char *msg)
2166 {
2167  char buf[64];
2168  time_t now = time(NULL);
2169 
2170  if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
2171  fprintf(OPF, "-- %s %s\n\n", msg, buf);
2172 }
static void dumpTimestamp(const char *msg)
Definition: pg_dumpall.c:2165
static char password[100]
Definition: streamutil.c:41
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:307
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:2112
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
int main(int argc, char *argv[])
Definition: pg_dumpall.c:92
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static int column_inserts
Definition: pg_dumpall.c:70
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:5976
static int disable_dollar_quoting
Definition: pg_dumpall.c:71
#define PGDUMP_VERSIONSTR
Definition: pg_dumpall.c:29
const char * fmtId(const char *rawid)
Definition: string_utils.c:66
const char * get_progname(const char *argv0)
Definition: path.c:453
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
static FILE * OPF
Definition: pg_dumpall.c:86
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
static void dumpDbRoleConfig(PGconn *conn)
Definition: pg_dumpall.c:1644
void buildShSecLabelQuery(PGconn *conn, const char *catalog_name, uint32 objectId, PQExpBuffer sql)
Definition: dumputils.c:636
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:567
static void dropRoles(PGconn *conn)
Definition: pg_dumpall.c:632
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:536
static char * constructConnStr(const char **keywords, const char **values)
Definition: pg_dumpall.c:2081
static const char * progname
Definition: pg_dumpall.c:62
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
#define PG_BINARY_W
Definition: c.h:1041
static void dumpTablespaces(PGconn *conn)
Definition: pg_dumpall.c:1104
static int inserts
Definition: pg_dumpall.c:74
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
unsigned int Oid
Definition: postgres_ext.h:31
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6001
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6071
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:470
#define PG_AUTHID
Definition: pg_dumpall.c:83
static bool verbose
Definition: pg_dumpall.c:66
void appendPsqlMetaConnect(PQExpBuffer buf, const char *dbname)
Definition: string_utils.c:581
static void dropDBs(PGconn *conn)
Definition: pg_dumpall.c:1241
static void buildShSecLabels(PGconn *conn, const char *catalog_name, uint32 objectId, PQExpBuffer buffer, const char *target, const char *objname)
Definition: pg_dumpall.c:1838
static int disable_triggers
Definition: pg_dumpall.c:72
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
#define required_argument
Definition: getopt_long.h:25
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:4655
int optind
Definition: getopt.c:51
static int no_tablespaces
Definition: pg_dumpall.c:75
char * connection_string
Definition: streamutil.c:34
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
PGconn * conn
Definition: streamutil.c:42
#define MAXPGPATH
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
static void executeCommand(PGconn *conn, const char *query)
Definition: pg_dumpall.c:2138
static int no_unlogged_table_data
Definition: pg_dumpall.c:78
char * c
static char * buf
Definition: pg_test_fsync.c:65
static PQExpBuffer pgdumpopts
Definition: pg_dumpall.c:63
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
static void dumpRoleMembership(PGconn *conn)
Definition: pg_dumpall.c:944
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5861
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static void dumpUserConfig(PGconn *conn, const char *username)
Definition: pg_dumpall.c:1599
unsigned int uint32
Definition: c.h:268
static void dumpGroups(PGconn *conn)
Definition: pg_dumpall.c:1004
static void makeAlterConfigCommand(PGconn *conn, const char *arrayitem, const char *type, const char *name, const char *type2, const char *name2)
Definition: pg_dumpall.c:1678
#define atooid(x)
Definition: postgres_ext.h:42
static bool dosync
Definition: pg_dumpall.c:67
char * pghost
Definition: pgbench.c:180
trivalue
Definition: vacuumlo.c:31
#define no_argument
Definition: getopt_long.h:24
#define exit_nicely(code)
Definition: pg_dumpall.c:89
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1012
static int runPgDump(const char *dbname)
Definition: pg_dumpall.c:1788
static void dumpDatabases(PGconn *conn)
Definition: pg_dumpall.c:1723
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:2781
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
static void help(void)
Definition: pg_dumpall.c:573
static char * username
Definition: initdb.c:130
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:430
bool quote_all_identifiers
Definition: ruleutils.c:296
static char * encoding
Definition: initdb.c:121
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:531
static bool have_password
Definition: streamutil.c:40
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *target, const char *objname)
Definition: dumputils.c:652
#define NULL
Definition: c.h:229
static int use_setsessauth
Definition: pg_dumpall.c:76
static PGconn * connectDatabase(const char *dbname, const char *connstr, const char *pghost, const char *pgport, const char *pguser, trivalue prompt_password, bool fail_on_error)
Definition: pg_dumpall.c:1863
#define PG_BINARY_A
Definition: c.h:1039
static int if_exists
Definition: pg_dumpall.c:73
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
bool buildACLCommands(const char *name, const char *subname, const char *type, const char *acls, const char *racls, const char *owner, const char *prefix, int remoteVersion, PQExpBuffer sql)
Definition: dumputils.c:55
static int server_version
Definition: pg_dumpall.c:80
static char pg_dump_bin[MAXPGPATH]
Definition: pg_dumpall.c:61
static bool skip_acls
Definition: pg_dumpall.c:65
char * dbname
Definition: streamutil.c:38
#define PGDUMP_STRFTIME_FMT
Definition: dumputils.h:33
const char * name
Definition: encode.c:521
static int binary_upgrade
Definition: pg_dumpall.c:69
static Datum values[MAXATTR]
Definition: bootstrap.c:162
#define PG_ROLES
Definition: pg_dumpall.c:84
static char * filename
Definition: pg_dumpall.c:87
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:298
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6045
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:550
char * optarg
Definition: getopt.c:53
static int no_role_passwords
Definition: pg_dumpall.c:79
int i
const char * strerror(int errnum)
Definition: strerror.c:19
static void dumpDatabaseConfig(PGconn *conn, const char *dbname)
Definition: pg_dumpall.c:1555
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
static int no_security_labels
Definition: pg_dumpall.c:77
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3092
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:5958
static void dumpCreateDB(PGconn *conn)
Definition: pg_dumpall.c:1289
#define _(x)
Definition: elog.c:84
char * pgport
Definition: pgbench.c:181
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
static void dumpRoles(PGconn *conn)
Definition: pg_dumpall.c:687
static char * connstr
Definition: pg_dumpall.c:64
static void dropTablespaces(PGconn *conn)
Definition: pg_dumpall.c:1069
static char role_catalog[10]
Definition: pg_dumpall.c:82