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