1
/*-------------------------------------------------------------------------
5
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
6
* Portions Copyright (c) 1994, Regents of the University of California
9
* src/bin/pg_dump/pg_dumpall.c
11
*-------------------------------------------------------------------------
14
#include "postgres_fe.h"
23
#include "getopt_long.h"
25
#include "dumputils.h"
26
#include "pg_backup.h"
28
/* version string we expect back from pg_dump */
29
#define PGDUMP_VERSIONSTR "pg_dump (PostgreSQL) " PG_VERSION "\n"
32
static const char *progname;
34
static void help(void);
36
static void dropRoles(PGconn *conn);
37
static void dumpRoles(PGconn *conn);
38
static void dumpRoleMembership(PGconn *conn);
39
static void dumpGroups(PGconn *conn);
40
static void dropTablespaces(PGconn *conn);
41
static void dumpTablespaces(PGconn *conn);
42
static void dropDBs(PGconn *conn);
43
static void dumpCreateDB(PGconn *conn);
44
static void dumpDatabaseConfig(PGconn *conn, const char *dbname);
45
static void dumpUserConfig(PGconn *conn, const char *username);
46
static void dumpDbRoleConfig(PGconn *conn);
47
static void makeAlterConfigCommand(PGconn *conn, const char *arrayitem,
48
const char *type, const char *name, const char *type2,
50
static void dumpDatabases(PGconn *conn);
51
static void dumpTimestamp(char *msg);
52
static void doShellQuoting(PQExpBuffer buf, const char *str);
54
static int runPgDump(const char *dbname);
55
static PGconn *connectDatabase(const char *dbname, const char *pghost, const char *pgport,
56
const char *pguser, enum trivalue prompt_password, bool fail_on_error);
57
static PGresult *executeQuery(PGconn *conn, const char *query);
58
static void executeCommand(PGconn *conn, const char *query);
60
static char pg_dump_bin[MAXPGPATH];
61
static PQExpBuffer pgdumpopts;
62
static bool skip_acls = false;
63
static bool verbose = false;
65
static int binary_upgrade = 0;
66
static int column_inserts = 0;
67
static int disable_dollar_quoting = 0;
68
static int disable_triggers = 0;
69
static int inserts = 0;
70
static int no_tablespaces = 0;
71
static int use_setsessauth = 0;
72
static int no_security_label = 0;
73
static int no_unlogged_table_data = 0;
74
static int server_version;
77
static char *filename = NULL;
81
main(int argc, char *argv[])
87
char *use_role = NULL;
88
enum trivalue prompt_password = TRI_DEFAULT;
89
bool data_only = false;
90
bool globals_only = false;
91
bool output_clean = false;
92
bool roles_only = false;
93
bool tablespaces_only = false;
96
const char *std_strings;
101
static struct option long_options[] = {
102
{"data-only", no_argument, NULL, 'a'},
103
{"clean", no_argument, NULL, 'c'},
104
{"file", required_argument, NULL, 'f'},
105
{"globals-only", no_argument, NULL, 'g'},
106
{"host", required_argument, NULL, 'h'},
107
{"ignore-version", no_argument, NULL, 'i'},
108
{"database", required_argument, NULL, 'l'},
109
{"oids", no_argument, NULL, 'o'},
110
{"no-owner", no_argument, NULL, 'O'},
111
{"port", required_argument, NULL, 'p'},
112
{"roles-only", no_argument, NULL, 'r'},
113
{"schema-only", no_argument, NULL, 's'},
114
{"superuser", required_argument, NULL, 'S'},
115
{"tablespaces-only", no_argument, NULL, 't'},
116
{"username", required_argument, NULL, 'U'},
117
{"verbose", no_argument, NULL, 'v'},
118
{"no-password", no_argument, NULL, 'w'},
119
{"password", no_argument, NULL, 'W'},
120
{"no-privileges", no_argument, NULL, 'x'},
121
{"no-acl", no_argument, NULL, 'x'},
124
* the following options don't have an equivalent short option letter
126
{"attribute-inserts", no_argument, &column_inserts, 1},
127
{"binary-upgrade", no_argument, &binary_upgrade, 1},
128
{"column-inserts", no_argument, &column_inserts, 1},
129
{"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
130
{"disable-triggers", no_argument, &disable_triggers, 1},
131
{"inserts", no_argument, &inserts, 1},
132
{"lock-wait-timeout", required_argument, NULL, 2},
133
{"no-tablespaces", no_argument, &no_tablespaces, 1},
134
{"quote-all-identifiers", no_argument, "e_all_identifiers, 1},
135
{"role", required_argument, NULL, 3},
136
{"use-set-session-authorization", no_argument, &use_setsessauth, 1},
137
{"no-security-label", no_argument, &no_security_label, 1},
138
{"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
143
set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
145
progname = get_progname(argv[0]);
149
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
154
if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
156
puts("pg_dumpall (PostgreSQL) " PG_VERSION);
161
if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
164
char full_path[MAXPGPATH];
166
if (find_my_exec(argv[0], full_path) < 0)
167
strlcpy(full_path, progname, sizeof(full_path));
171
_("The program \"pg_dump\" is needed by %s "
172
"but was not found in the\n"
173
"same directory as \"%s\".\n"
174
"Check your installation.\n"),
175
progname, full_path);
178
_("The program \"pg_dump\" was found by \"%s\"\n"
179
"but was not the same version as %s.\n"
180
"Check your installation.\n"),
181
full_path, progname);
185
pgdumpopts = createPQExpBuffer();
187
while ((c = getopt_long(argc, argv, "acf:gh:il:oOp:rsS:tU:vwWx", long_options, &optindex)) != -1)
193
appendPQExpBuffer(pgdumpopts, " -a");
202
appendPQExpBuffer(pgdumpopts, " -f ");
203
doShellQuoting(pgdumpopts, filename);
212
appendPQExpBuffer(pgdumpopts, " -h ");
213
doShellQuoting(pgdumpopts, pghost);
217
/* ignored, deprecated option */
225
appendPQExpBuffer(pgdumpopts, " -o");
229
appendPQExpBuffer(pgdumpopts, " -O");
234
appendPQExpBuffer(pgdumpopts, " -p ");
235
doShellQuoting(pgdumpopts, pgport);
243
appendPQExpBuffer(pgdumpopts, " -s");
247
appendPQExpBuffer(pgdumpopts, " -S ");
248
doShellQuoting(pgdumpopts, optarg);
252
tablespaces_only = true;
257
appendPQExpBuffer(pgdumpopts, " -U ");
258
doShellQuoting(pgdumpopts, pguser);
263
appendPQExpBuffer(pgdumpopts, " -v");
267
prompt_password = TRI_NO;
268
appendPQExpBuffer(pgdumpopts, " -w");
272
prompt_password = TRI_YES;
273
appendPQExpBuffer(pgdumpopts, " -W");
278
appendPQExpBuffer(pgdumpopts, " -x");
285
appendPQExpBuffer(pgdumpopts, " --lock-wait-timeout ");
286
doShellQuoting(pgdumpopts, optarg);
291
appendPQExpBuffer(pgdumpopts, " --role ");
292
doShellQuoting(pgdumpopts, use_role);
296
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
301
/* Complain if any arguments remain */
304
fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
305
progname, argv[optind]);
306
fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
311
/* Make sure the user hasn't specified a mix of globals-only options */
312
if (globals_only && roles_only)
314
fprintf(stderr, _("%s: options -g/--globals-only and -r/--roles-only cannot be used together\n"),
316
fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
321
if (globals_only && tablespaces_only)
323
fprintf(stderr, _("%s: options -g/--globals-only and -t/--tablespaces-only cannot be used together\n"),
325
fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
330
if (roles_only && tablespaces_only)
332
fprintf(stderr, _("%s: options -r/--roles-only and -t/--tablespaces-only cannot be used together\n"),
334
fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
339
/* Add long options to the pg_dump argument list */
341
appendPQExpBuffer(pgdumpopts, " --binary-upgrade");
343
appendPQExpBuffer(pgdumpopts, " --column-inserts");
344
if (disable_dollar_quoting)
345
appendPQExpBuffer(pgdumpopts, " --disable-dollar-quoting");
346
if (disable_triggers)
347
appendPQExpBuffer(pgdumpopts, " --disable-triggers");
349
appendPQExpBuffer(pgdumpopts, " --inserts");
351
appendPQExpBuffer(pgdumpopts, " --no-tablespaces");
352
if (quote_all_identifiers)
353
appendPQExpBuffer(pgdumpopts, " --quote-all-identifiers");
355
appendPQExpBuffer(pgdumpopts, " --use-set-session-authorization");
356
if (no_security_label)
357
appendPQExpBuffer(pgdumpopts, " --no-security-label");
358
if (no_unlogged_table_data)
359
appendPQExpBuffer(pgdumpopts, " --no-unlogged-table-data");
362
* If there was a database specified on the command line, use that,
363
* otherwise try to connect to database "postgres", and failing that
364
* "template1". "postgres" is the preferred choice for 8.1 and later
365
* servers, but it usually will not exist on older ones.
369
conn = connectDatabase(pgdb, pghost, pgport, pguser,
370
prompt_password, false);
374
fprintf(stderr, _("%s: could not connect to database \"%s\"\n"),
381
conn = connectDatabase("postgres", pghost, pgport, pguser,
382
prompt_password, false);
384
conn = connectDatabase("template1", pghost, pgport, pguser,
385
prompt_password, true);
389
fprintf(stderr, _("%s: could not connect to databases \"postgres\" or \"template1\"\n"
390
"Please specify an alternative database.\n"),
392
fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
399
* Open the output file if required, otherwise use stdout
403
OPF = fopen(filename, PG_BINARY_W);
406
fprintf(stderr, _("%s: could not open the output file \"%s\": %s\n"),
407
progname, filename, strerror(errno));
415
* Get the active encoding and the standard_conforming_strings setting, so
416
* we know how to escape strings.
418
encoding = PQclientEncoding(conn);
419
std_strings = PQparameterStatus(conn, "standard_conforming_strings");
423
/* Set the role if requested */
424
if (use_role && server_version >= 80100)
426
PQExpBuffer query = createPQExpBuffer();
428
appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
429
executeCommand(conn, query->data);
430
destroyPQExpBuffer(query);
433
/* Force quoting of all identifiers if requested. */
434
if (quote_all_identifiers && server_version >= 90100)
435
executeCommand(conn, "SET quote_all_identifiers = true");
437
fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
439
dumpTimestamp("Started on");
441
fprintf(OPF, "\\connect postgres\n\n");
443
/* Replicate encoding and std_strings in output */
444
fprintf(OPF, "SET client_encoding = '%s';\n",
445
pg_encoding_to_char(encoding));
446
fprintf(OPF, "SET standard_conforming_strings = %s;\n", std_strings);
447
if (strcmp(std_strings, "off") == 0)
448
fprintf(OPF, "SET escape_string_warning = off;\n");
454
* If asked to --clean, do that first. We can avoid detailed
455
* dependency analysis because databases never depend on each other,
456
* and tablespaces never depend on each other. Roles could have
457
* grants to each other, but DROP ROLE will clean those up silently.
461
if (!globals_only && !roles_only && !tablespaces_only)
464
if (!roles_only && !no_tablespaces)
466
if (server_version >= 80000)
467
dropTablespaces(conn);
470
if (!tablespaces_only)
475
* Now create objects as requested. Be careful that option logic here
476
* is the same as for drops above.
478
if (!tablespaces_only)
480
/* Dump roles (users) */
483
/* Dump role memberships --- need different method for pre-8.1 */
484
if (server_version >= 80100)
485
dumpRoleMembership(conn);
490
if (!roles_only && !no_tablespaces)
492
/* Dump tablespaces */
493
if (server_version >= 80000)
494
dumpTablespaces(conn);
497
/* Dump CREATE DATABASE commands */
498
if (!globals_only && !roles_only && !tablespaces_only)
501
/* Dump role/database settings */
502
if (!tablespaces_only && !roles_only)
504
if (server_version >= 90000)
505
dumpDbRoleConfig(conn);
509
if (!globals_only && !roles_only && !tablespaces_only)
515
dumpTimestamp("Completed on");
516
fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
528
printf(_("%s extracts a PostgreSQL database cluster into an SQL script file.\n\n"), progname);
529
printf(_("Usage:\n"));
530
printf(_(" %s [OPTION]...\n"), progname);
532
printf(_("\nGeneral options:\n"));
533
printf(_(" -f, --file=FILENAME output file name\n"));
534
printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
535
printf(_(" --help show this help, then exit\n"));
536
printf(_(" --version output version information, then exit\n"));
537
printf(_("\nOptions controlling the output content:\n"));
538
printf(_(" -a, --data-only dump only the data, not the schema\n"));
539
printf(_(" -c, --clean clean (drop) databases before recreating\n"));
540
printf(_(" -g, --globals-only dump only global objects, no databases\n"));
541
printf(_(" -o, --oids include OIDs in dump\n"));
542
printf(_(" -O, --no-owner skip restoration of object ownership\n"));
543
printf(_(" -r, --roles-only dump only roles, no databases or tablespaces\n"));
544
printf(_(" -s, --schema-only dump only the schema, no data\n"));
545
printf(_(" -S, --superuser=NAME superuser user name to use in the dump\n"));
546
printf(_(" -t, --tablespaces-only dump only tablespaces, no databases or roles\n"));
547
printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
548
printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
549
printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
550
printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
551
printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
552
printf(_(" --disable-triggers disable triggers during data-only restore\n"));
553
printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
554
printf(_(" --quote-all-identifiers quote all identifiers, even if not keywords\n"));
555
printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
556
printf(_(" --no-security-label do not dump security label assignments\n"));
557
printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
558
printf(_(" --use-set-session-authorization\n"
559
" use SET SESSION AUTHORIZATION commands instead of\n"
560
" ALTER OWNER commands to set ownership\n"));
562
printf(_("\nConnection options:\n"));
563
printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
564
printf(_(" -l, --database=DBNAME alternative default database\n"));
565
printf(_(" -p, --port=PORT database server port number\n"));
566
printf(_(" -U, --username=NAME connect as specified database user\n"));
567
printf(_(" -w, --no-password never prompt for password\n"));
568
printf(_(" -W, --password force password prompt (should happen automatically)\n"));
570
printf(_("\nIf -f/--file is not used, then the SQL script will be written to the standard\n"
572
printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
580
dropRoles(PGconn *conn)
586
if (server_version >= 80100)
587
res = executeQuery(conn,
592
res = executeQuery(conn,
593
"SELECT usename as rolname "
596
"SELECT groname as rolname "
600
i_rolname = PQfnumber(res, "rolname");
602
if (PQntuples(res) > 0)
603
fprintf(OPF, "--\n-- Drop roles\n--\n\n");
605
for (i = 0; i < PQntuples(res); i++)
607
const char *rolename;
609
rolename = PQgetvalue(res, i, i_rolname);
611
fprintf(OPF, "DROP ROLE %s;\n", fmtId(rolename));
616
fprintf(OPF, "\n\n");
623
dumpRoles(PGconn *conn)
625
PQExpBuffer buf = createPQExpBuffer();
641
/* note: rolconfig is dumped later */
642
if (server_version >= 90100)
643
printfPQExpBuffer(buf,
644
"SELECT oid, rolname, rolsuper, rolinherit, "
645
"rolcreaterole, rolcreatedb, "
646
"rolcanlogin, rolconnlimit, rolpassword, "
647
"rolvaliduntil, rolreplication, "
648
"pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment "
651
else if (server_version >= 80200)
652
printfPQExpBuffer(buf,
653
"SELECT oid, rolname, rolsuper, rolinherit, "
654
"rolcreaterole, rolcreatedb, "
655
"rolcanlogin, rolconnlimit, rolpassword, "
656
"rolvaliduntil, false as rolreplication, "
657
"pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment "
660
else if (server_version >= 80100)
661
printfPQExpBuffer(buf,
662
"SELECT oid, rolname, rolsuper, rolinherit, "
663
"rolcreaterole, rolcreatedb, "
664
"rolcanlogin, rolconnlimit, rolpassword, "
665
"rolvaliduntil, false as rolreplication, "
666
"null as rolcomment "
670
printfPQExpBuffer(buf,
671
"SELECT 0, usename as rolname, "
672
"usesuper as rolsuper, "
673
"true as rolinherit, "
674
"usesuper as rolcreaterole, "
675
"usecreatedb as rolcreatedb, "
676
"true as rolcanlogin, "
677
"-1 as rolconnlimit, "
678
"passwd as rolpassword, "
679
"valuntil as rolvaliduntil, "
680
"false as rolreplication, "
681
"null as rolcomment "
684
"SELECT 0, groname as rolname, "
685
"false as rolsuper, "
686
"true as rolinherit, "
687
"false as rolcreaterole, "
688
"false as rolcreatedb, "
689
"false as rolcanlogin, "
690
"-1 as rolconnlimit, "
691
"null::text as rolpassword, "
692
"null::abstime as rolvaliduntil, "
693
"false as rolreplication, "
694
"null as rolcomment "
696
"WHERE NOT EXISTS (SELECT 1 FROM pg_shadow "
697
" WHERE usename = groname) "
700
res = executeQuery(conn, buf->data);
702
i_oid = PQfnumber(res, "oid");
703
i_rolname = PQfnumber(res, "rolname");
704
i_rolsuper = PQfnumber(res, "rolsuper");
705
i_rolinherit = PQfnumber(res, "rolinherit");
706
i_rolcreaterole = PQfnumber(res, "rolcreaterole");
707
i_rolcreatedb = PQfnumber(res, "rolcreatedb");
708
i_rolcanlogin = PQfnumber(res, "rolcanlogin");
709
i_rolconnlimit = PQfnumber(res, "rolconnlimit");
710
i_rolpassword = PQfnumber(res, "rolpassword");
711
i_rolvaliduntil = PQfnumber(res, "rolvaliduntil");
712
i_rolreplication = PQfnumber(res, "rolreplication");
713
i_rolcomment = PQfnumber(res, "rolcomment");
715
if (PQntuples(res) > 0)
716
fprintf(OPF, "--\n-- Roles\n--\n\n");
718
for (i = 0; i < PQntuples(res); i++)
720
const char *rolename;
722
rolename = PQgetvalue(res, i, i_rolname);
724
resetPQExpBuffer(buf);
728
Oid auth_oid = atooid(PQgetvalue(res, i, i_oid));
730
appendPQExpBuffer(buf, "\n-- For binary upgrade, must preserve pg_authid.oid\n");
731
appendPQExpBuffer(buf,
732
"SELECT binary_upgrade.set_next_pg_authid_oid('%u'::pg_catalog.oid);\n\n",
737
* We dump CREATE ROLE followed by ALTER ROLE to ensure that the role
738
* will acquire the right properties even if it already exists (ie, it
739
* won't hurt for the CREATE to fail). This is particularly important
740
* for the role we are connected as, since even with --clean we will
741
* have failed to drop it.
743
appendPQExpBuffer(buf, "CREATE ROLE %s;\n", fmtId(rolename));
744
appendPQExpBuffer(buf, "ALTER ROLE %s WITH", fmtId(rolename));
746
if (strcmp(PQgetvalue(res, i, i_rolsuper), "t") == 0)
747
appendPQExpBuffer(buf, " SUPERUSER");
749
appendPQExpBuffer(buf, " NOSUPERUSER");
751
if (strcmp(PQgetvalue(res, i, i_rolinherit), "t") == 0)
752
appendPQExpBuffer(buf, " INHERIT");
754
appendPQExpBuffer(buf, " NOINHERIT");
756
if (strcmp(PQgetvalue(res, i, i_rolcreaterole), "t") == 0)
757
appendPQExpBuffer(buf, " CREATEROLE");
759
appendPQExpBuffer(buf, " NOCREATEROLE");
761
if (strcmp(PQgetvalue(res, i, i_rolcreatedb), "t") == 0)
762
appendPQExpBuffer(buf, " CREATEDB");
764
appendPQExpBuffer(buf, " NOCREATEDB");
766
if (strcmp(PQgetvalue(res, i, i_rolcanlogin), "t") == 0)
767
appendPQExpBuffer(buf, " LOGIN");
769
appendPQExpBuffer(buf, " NOLOGIN");
771
if (strcmp(PQgetvalue(res, i, i_rolreplication), "t") == 0)
772
appendPQExpBuffer(buf, " REPLICATION");
774
appendPQExpBuffer(buf, " NOREPLICATION");
776
if (strcmp(PQgetvalue(res, i, i_rolconnlimit), "-1") != 0)
777
appendPQExpBuffer(buf, " CONNECTION LIMIT %s",
778
PQgetvalue(res, i, i_rolconnlimit));
780
if (!PQgetisnull(res, i, i_rolpassword))
782
appendPQExpBuffer(buf, " PASSWORD ");
783
appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolpassword), conn);
786
if (!PQgetisnull(res, i, i_rolvaliduntil))
787
appendPQExpBuffer(buf, " VALID UNTIL '%s'",
788
PQgetvalue(res, i, i_rolvaliduntil));
790
appendPQExpBuffer(buf, ";\n");
792
if (!PQgetisnull(res, i, i_rolcomment))
794
appendPQExpBuffer(buf, "COMMENT ON ROLE %s IS ", fmtId(rolename));
795
appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolcomment), conn);
796
appendPQExpBuffer(buf, ";\n");
799
fprintf(OPF, "%s", buf->data);
801
if (server_version >= 70300)
802
dumpUserConfig(conn, rolename);
807
fprintf(OPF, "\n\n");
809
destroyPQExpBuffer(buf);
814
* Dump role memberships. This code is used for 8.1 and later servers.
816
* Note: we expect dumpRoles already created all the roles, but there is
820
dumpRoleMembership(PGconn *conn)
825
res = executeQuery(conn, "SELECT ur.rolname AS roleid, "
826
"um.rolname AS member, "
828
"ug.rolname AS grantor "
829
"FROM pg_auth_members a "
830
"LEFT JOIN pg_authid ur on ur.oid = a.roleid "
831
"LEFT JOIN pg_authid um on um.oid = a.member "
832
"LEFT JOIN pg_authid ug on ug.oid = a.grantor "
835
if (PQntuples(res) > 0)
836
fprintf(OPF, "--\n-- Role memberships\n--\n\n");
838
for (i = 0; i < PQntuples(res); i++)
840
char *roleid = PQgetvalue(res, i, 0);
841
char *member = PQgetvalue(res, i, 1);
842
char *option = PQgetvalue(res, i, 2);
844
fprintf(OPF, "GRANT %s", fmtId(roleid));
845
fprintf(OPF, " TO %s", fmtId(member));
847
fprintf(OPF, " WITH ADMIN OPTION");
850
* We don't track the grantor very carefully in the backend, so cope
851
* with the possibility that it has been dropped.
853
if (!PQgetisnull(res, i, 3))
855
char *grantor = PQgetvalue(res, i, 3);
857
fprintf(OPF, " GRANTED BY %s", fmtId(grantor));
864
fprintf(OPF, "\n\n");
868
* Dump group memberships from a pre-8.1 server. It's annoying that we
869
* can't share any useful amount of code with the post-8.1 case, but
870
* the catalog representations are too different.
872
* Note: we expect dumpRoles already created all the roles, but there is
876
dumpGroups(PGconn *conn)
878
PQExpBuffer buf = createPQExpBuffer();
882
res = executeQuery(conn,
883
"SELECT groname, grolist FROM pg_group ORDER BY 1");
885
if (PQntuples(res) > 0)
886
fprintf(OPF, "--\n-- Role memberships\n--\n\n");
888
for (i = 0; i < PQntuples(res); i++)
890
char *groname = PQgetvalue(res, i, 0);
891
char *grolist = PQgetvalue(res, i, 1);
896
* Array representation is {1,2,3} ... convert to (1,2,3)
898
if (strlen(grolist) < 3)
901
grolist = strdup(grolist);
903
grolist[strlen(grolist) - 1] = ')';
904
printfPQExpBuffer(buf,
905
"SELECT usename FROM pg_shadow "
906
"WHERE usesysid IN %s ORDER BY 1",
910
res2 = executeQuery(conn, buf->data);
912
for (j = 0; j < PQntuples(res2); j++)
914
char *usename = PQgetvalue(res2, j, 0);
917
* Don't try to grant a role to itself; can happen if old
918
* installation has identically named user and group.
920
if (strcmp(groname, usename) == 0)
923
fprintf(OPF, "GRANT %s", fmtId(groname));
924
fprintf(OPF, " TO %s;\n", fmtId(usename));
931
destroyPQExpBuffer(buf);
933
fprintf(OPF, "\n\n");
941
dropTablespaces(PGconn *conn)
947
* Get all tablespaces except built-in ones (which we assume are named
950
res = executeQuery(conn, "SELECT spcname "
951
"FROM pg_catalog.pg_tablespace "
952
"WHERE spcname !~ '^pg_' "
955
if (PQntuples(res) > 0)
956
fprintf(OPF, "--\n-- Drop tablespaces\n--\n\n");
958
for (i = 0; i < PQntuples(res); i++)
960
char *spcname = PQgetvalue(res, i, 0);
962
fprintf(OPF, "DROP TABLESPACE %s;\n", fmtId(spcname));
967
fprintf(OPF, "\n\n");
974
dumpTablespaces(PGconn *conn)
980
* Get all tablespaces except built-in ones (which we assume are named
983
if (server_version >= 90000)
984
res = executeQuery(conn, "SELECT spcname, "
985
"pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
986
"spclocation, spcacl, "
987
"array_to_string(spcoptions, ', '),"
988
"pg_catalog.shobj_description(oid, 'pg_tablespace') "
989
"FROM pg_catalog.pg_tablespace "
990
"WHERE spcname !~ '^pg_' "
992
else if (server_version >= 80200)
993
res = executeQuery(conn, "SELECT spcname, "
994
"pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
995
"spclocation, spcacl, null, "
996
"pg_catalog.shobj_description(oid, 'pg_tablespace') "
997
"FROM pg_catalog.pg_tablespace "
998
"WHERE spcname !~ '^pg_' "
1001
res = executeQuery(conn, "SELECT spcname, "
1002
"pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1003
"spclocation, spcacl, "
1005
"FROM pg_catalog.pg_tablespace "
1006
"WHERE spcname !~ '^pg_' "
1009
if (PQntuples(res) > 0)
1010
fprintf(OPF, "--\n-- Tablespaces\n--\n\n");
1012
for (i = 0; i < PQntuples(res); i++)
1014
PQExpBuffer buf = createPQExpBuffer();
1015
char *spcname = PQgetvalue(res, i, 0);
1016
char *spcowner = PQgetvalue(res, i, 1);
1017
char *spclocation = PQgetvalue(res, i, 2);
1018
char *spcacl = PQgetvalue(res, i, 3);
1019
char *spcoptions = PQgetvalue(res, i, 4);
1020
char *spccomment = PQgetvalue(res, i, 5);
1023
/* needed for buildACLCommands() */
1024
fspcname = strdup(fmtId(spcname));
1026
appendPQExpBuffer(buf, "CREATE TABLESPACE %s", fspcname);
1027
appendPQExpBuffer(buf, " OWNER %s", fmtId(spcowner));
1029
appendPQExpBuffer(buf, " LOCATION ");
1030
appendStringLiteralConn(buf, spclocation, conn);
1031
appendPQExpBuffer(buf, ";\n");
1033
if (spcoptions && spcoptions[0] != '\0')
1034
appendPQExpBuffer(buf, "ALTER TABLESPACE %s SET (%s);\n",
1035
fspcname, spcoptions);
1038
!buildACLCommands(fspcname, NULL, "TABLESPACE", spcacl, spcowner,
1039
"", server_version, buf))
1041
fprintf(stderr, _("%s: could not parse ACL list (%s) for tablespace \"%s\"\n"),
1042
progname, spcacl, fspcname);
1047
if (spccomment && strlen(spccomment))
1049
appendPQExpBuffer(buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
1050
appendStringLiteralConn(buf, spccomment, conn);
1051
appendPQExpBuffer(buf, ";\n");
1054
fprintf(OPF, "%s", buf->data);
1057
destroyPQExpBuffer(buf);
1061
fprintf(OPF, "\n\n");
1066
* Dump commands to drop each database.
1068
* This should match the set of databases targeted by dumpCreateDB().
1071
dropDBs(PGconn *conn)
1076
if (server_version >= 70100)
1077
res = executeQuery(conn,
1079
"FROM pg_database d "
1080
"WHERE datallowconn ORDER BY 1");
1082
res = executeQuery(conn,
1084
"FROM pg_database d "
1087
if (PQntuples(res) > 0)
1088
fprintf(OPF, "--\n-- Drop databases\n--\n\n");
1090
for (i = 0; i < PQntuples(res); i++)
1092
char *dbname = PQgetvalue(res, i, 0);
1095
* Skip "template1" and "postgres"; the restore script is almost
1096
* certainly going to be run in one or the other, and we don't know
1097
* which. This must agree with dumpCreateDB's choices!
1099
if (strcmp(dbname, "template1") != 0 &&
1100
strcmp(dbname, "postgres") != 0)
1102
fprintf(OPF, "DROP DATABASE %s;\n", fmtId(dbname));
1108
fprintf(OPF, "\n\n");
1112
* Dump commands to create each database.
1114
* To minimize the number of reconnections (and possibly ensuing
1115
* password prompts) required by the output script, we emit all CREATE
1116
* DATABASE commands during the initial phase of the script, and then
1117
* run pg_dump for each database to dump the contents of that
1118
* database. We skip databases marked not datallowconn, since we'd be
1119
* unable to connect to them anyway (and besides, we don't want to
1123
dumpCreateDB(PGconn *conn)
1125
PQExpBuffer buf = createPQExpBuffer();
1126
char *default_encoding = NULL;
1127
char *default_collate = NULL;
1128
char *default_ctype = NULL;
1132
fprintf(OPF, "--\n-- Database creation\n--\n\n");
1135
* First, get the installation's default encoding and locale information.
1136
* We will dump encoding and locale specifications in the CREATE DATABASE
1137
* commands for just those databases with values different from defaults.
1139
* We consider template0's encoding and locale (or, pre-7.1, template1's)
1140
* to define the installation default. Pre-8.4 installations do not have
1141
* per-database locale settings; for them, every database must necessarily
1142
* be using the installation default, so there's no need to do anything
1143
* (which is good, since in very old versions there is no good way to find
1144
* out what the installation locale is anyway...)
1146
if (server_version >= 80400)
1147
res = executeQuery(conn,
1148
"SELECT pg_encoding_to_char(encoding), "
1149
"datcollate, datctype "
1151
"WHERE datname = 'template0'");
1152
else if (server_version >= 70100)
1153
res = executeQuery(conn,
1154
"SELECT pg_encoding_to_char(encoding), "
1155
"null::text AS datcollate, null::text AS datctype "
1157
"WHERE datname = 'template0'");
1159
res = executeQuery(conn,
1160
"SELECT pg_encoding_to_char(encoding), "
1161
"null::text AS datcollate, null::text AS datctype "
1163
"WHERE datname = 'template1'");
1165
/* If for some reason the template DB isn't there, treat as unknown */
1166
if (PQntuples(res) > 0)
1168
if (!PQgetisnull(res, 0, 0))
1169
default_encoding = strdup(PQgetvalue(res, 0, 0));
1170
if (!PQgetisnull(res, 0, 1))
1171
default_collate = strdup(PQgetvalue(res, 0, 1));
1172
if (!PQgetisnull(res, 0, 2))
1173
default_ctype = strdup(PQgetvalue(res, 0, 2));
1178
/* Now collect all the information about databases to dump */
1179
if (server_version >= 80400)
1180
res = executeQuery(conn,
1182
"coalesce(rolname, (select rolname from pg_authid where oid=(select datdba from pg_database where datname='template0'))), "
1183
"pg_encoding_to_char(d.encoding), "
1184
"datcollate, datctype, datfrozenxid, "
1185
"datistemplate, datacl, datconnlimit, "
1186
"(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1187
"FROM pg_database d LEFT JOIN pg_authid u ON (datdba = u.oid) "
1188
"WHERE datallowconn ORDER BY 1");
1189
else if (server_version >= 80100)
1190
res = executeQuery(conn,
1192
"coalesce(rolname, (select rolname from pg_authid where oid=(select datdba from pg_database where datname='template0'))), "
1193
"pg_encoding_to_char(d.encoding), "
1194
"null::text AS datcollate, null::text AS datctype, datfrozenxid, "
1195
"datistemplate, datacl, datconnlimit, "
1196
"(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1197
"FROM pg_database d LEFT JOIN pg_authid u ON (datdba = u.oid) "
1198
"WHERE datallowconn ORDER BY 1");
1199
else if (server_version >= 80000)
1200
res = executeQuery(conn,
1202
"coalesce(usename, (select usename from pg_shadow where usesysid=(select datdba from pg_database where datname='template0'))), "
1203
"pg_encoding_to_char(d.encoding), "
1204
"null::text AS datcollate, null::text AS datctype, datfrozenxid, "
1205
"datistemplate, datacl, -1 as datconnlimit, "
1206
"(SELECT spcname FROM pg_tablespace t WHERE t.oid = d.dattablespace) AS dattablespace "
1207
"FROM pg_database d LEFT JOIN pg_shadow u ON (datdba = usesysid) "
1208
"WHERE datallowconn ORDER BY 1");
1209
else if (server_version >= 70300)
1210
res = executeQuery(conn,
1212
"coalesce(usename, (select usename from pg_shadow where usesysid=(select datdba from pg_database where datname='template0'))), "
1213
"pg_encoding_to_char(d.encoding), "
1214
"null::text AS datcollate, null::text AS datctype, datfrozenxid, "
1215
"datistemplate, datacl, -1 as datconnlimit, "
1216
"'pg_default' AS dattablespace "
1217
"FROM pg_database d LEFT JOIN pg_shadow u ON (datdba = usesysid) "
1218
"WHERE datallowconn ORDER BY 1");
1219
else if (server_version >= 70100)
1220
res = executeQuery(conn,
1223
"(select usename from pg_shadow where usesysid=datdba), "
1224
"(select usename from pg_shadow where usesysid=(select datdba from pg_database where datname='template0'))), "
1225
"pg_encoding_to_char(d.encoding), "
1226
"null::text AS datcollate, null::text AS datctype, 0 AS datfrozenxid, "
1227
"datistemplate, '' as datacl, -1 as datconnlimit, "
1228
"'pg_default' AS dattablespace "
1229
"FROM pg_database d "
1230
"WHERE datallowconn ORDER BY 1");
1234
* Note: 7.0 fails to cope with sub-select in COALESCE, so just deal
1235
* with getting a NULL by not printing any OWNER clause.
1237
res = executeQuery(conn,
1239
"(select usename from pg_shadow where usesysid=datdba), "
1240
"pg_encoding_to_char(d.encoding), "
1241
"null::text AS datcollate, null::text AS datctype, 0 AS datfrozenxid, "
1242
"'f' as datistemplate, "
1243
"'' as datacl, -1 as datconnlimit, "
1244
"'pg_default' AS dattablespace "
1245
"FROM pg_database d "
1249
for (i = 0; i < PQntuples(res); i++)
1251
char *dbname = PQgetvalue(res, i, 0);
1252
char *dbowner = PQgetvalue(res, i, 1);
1253
char *dbencoding = PQgetvalue(res, i, 2);
1254
char *dbcollate = PQgetvalue(res, i, 3);
1255
char *dbctype = PQgetvalue(res, i, 4);
1256
uint32 dbfrozenxid = atooid(PQgetvalue(res, i, 5));
1257
char *dbistemplate = PQgetvalue(res, i, 6);
1258
char *dbacl = PQgetvalue(res, i, 7);
1259
char *dbconnlimit = PQgetvalue(res, i, 8);
1260
char *dbtablespace = PQgetvalue(res, i, 9);
1263
fdbname = strdup(fmtId(dbname));
1265
resetPQExpBuffer(buf);
1268
* Skip the CREATE DATABASE commands for "template1" and "postgres",
1269
* since they are presumably already there in the destination cluster.
1270
* We do want to emit their ACLs and config options if any, however.
1272
if (strcmp(dbname, "template1") != 0 &&
1273
strcmp(dbname, "postgres") != 0)
1275
appendPQExpBuffer(buf, "CREATE DATABASE %s", fdbname);
1277
appendPQExpBuffer(buf, " WITH TEMPLATE = template0");
1279
if (strlen(dbowner) != 0)
1280
appendPQExpBuffer(buf, " OWNER = %s", fmtId(dbowner));
1282
if (default_encoding && strcmp(dbencoding, default_encoding) != 0)
1284
appendPQExpBuffer(buf, " ENCODING = ");
1285
appendStringLiteralConn(buf, dbencoding, conn);
1288
if (default_collate && strcmp(dbcollate, default_collate) != 0)
1290
appendPQExpBuffer(buf, " LC_COLLATE = ");
1291
appendStringLiteralConn(buf, dbcollate, conn);
1294
if (default_ctype && strcmp(dbctype, default_ctype) != 0)
1296
appendPQExpBuffer(buf, " LC_CTYPE = ");
1297
appendStringLiteralConn(buf, dbctype, conn);
1301
* Output tablespace if it isn't the default. For default, it
1302
* uses the default from the template database. If tablespace is
1303
* specified and tablespace creation failed earlier, (e.g. no such
1304
* directory), the database creation will fail too. One solution
1305
* would be to use 'SET default_tablespace' like we do in pg_dump
1306
* for setting non-default database locations.
1308
if (strcmp(dbtablespace, "pg_default") != 0 && !no_tablespaces)
1309
appendPQExpBuffer(buf, " TABLESPACE = %s",
1310
fmtId(dbtablespace));
1312
if (strcmp(dbconnlimit, "-1") != 0)
1313
appendPQExpBuffer(buf, " CONNECTION LIMIT = %s",
1316
appendPQExpBuffer(buf, ";\n");
1318
if (strcmp(dbistemplate, "t") == 0)
1320
appendPQExpBuffer(buf, "UPDATE pg_catalog.pg_database SET datistemplate = 't' WHERE datname = ");
1321
appendStringLiteralConn(buf, dbname, conn);
1322
appendPQExpBuffer(buf, ";\n");
1327
appendPQExpBuffer(buf, "-- For binary upgrade, set datfrozenxid.\n");
1328
appendPQExpBuffer(buf, "UPDATE pg_catalog.pg_database "
1329
"SET datfrozenxid = '%u' "
1332
appendStringLiteralConn(buf, dbname, conn);
1333
appendPQExpBuffer(buf, ";\n");
1338
!buildACLCommands(fdbname, NULL, "DATABASE", dbacl, dbowner,
1339
"", server_version, buf))
1341
fprintf(stderr, _("%s: could not parse ACL list (%s) for database \"%s\"\n"),
1342
progname, dbacl, fdbname);
1347
fprintf(OPF, "%s", buf->data);
1349
if (server_version >= 70300)
1350
dumpDatabaseConfig(conn, dbname);
1356
destroyPQExpBuffer(buf);
1358
fprintf(OPF, "\n\n");
1363
* Dump database-specific configuration
1366
dumpDatabaseConfig(PGconn *conn, const char *dbname)
1368
PQExpBuffer buf = createPQExpBuffer();
1375
if (server_version >= 90000)
1376
printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting WHERE "
1377
"setrole = 0 AND setdatabase = (SELECT oid FROM pg_database WHERE datname = ", count);
1379
printfPQExpBuffer(buf, "SELECT datconfig[%d] FROM pg_database WHERE datname = ", count);
1380
appendStringLiteralConn(buf, dbname, conn);
1382
if (server_version >= 90000)
1383
appendPQExpBuffer(buf, ")");
1385
appendPQExpBuffer(buf, ";");
1387
res = executeQuery(conn, buf->data);
1388
if (PQntuples(res) == 1 &&
1389
!PQgetisnull(res, 0, 0))
1391
makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
1392
"DATABASE", dbname, NULL, NULL);
1403
destroyPQExpBuffer(buf);
1409
* Dump user-specific configuration
1412
dumpUserConfig(PGconn *conn, const char *username)
1414
PQExpBuffer buf = createPQExpBuffer();
1421
if (server_version >= 90000)
1422
printfPQExpBuffer(buf, "SELECT setconfig[%d] FROM pg_db_role_setting WHERE "
1423
"setdatabase = 0 AND setrole = "
1424
"(SELECT oid FROM pg_authid WHERE rolname = ", count);
1425
else if (server_version >= 80100)
1426
printfPQExpBuffer(buf, "SELECT rolconfig[%d] FROM pg_authid WHERE rolname = ", count);
1428
printfPQExpBuffer(buf, "SELECT useconfig[%d] FROM pg_shadow WHERE usename = ", count);
1429
appendStringLiteralConn(buf, username, conn);
1430
if (server_version >= 90000)
1431
appendPQExpBuffer(buf, ")");
1433
res = executeQuery(conn, buf->data);
1434
if (PQntuples(res) == 1 &&
1435
!PQgetisnull(res, 0, 0))
1437
makeAlterConfigCommand(conn, PQgetvalue(res, 0, 0),
1438
"ROLE", username, NULL, NULL);
1449
destroyPQExpBuffer(buf);
1454
* Dump user-and-database-specific configuration
1457
dumpDbRoleConfig(PGconn *conn)
1459
PQExpBuffer buf = createPQExpBuffer();
1463
printfPQExpBuffer(buf, "SELECT rolname, datname, unnest(setconfig) "
1464
"FROM pg_db_role_setting, pg_authid, pg_database "
1465
"WHERE setrole = pg_authid.oid AND setdatabase = pg_database.oid");
1466
res = executeQuery(conn, buf->data);
1468
if (PQntuples(res) > 0)
1470
fprintf(OPF, "--\n-- Per-Database Role Settings \n--\n\n");
1472
for (i = 0; i < PQntuples(res); i++)
1474
makeAlterConfigCommand(conn, PQgetvalue(res, i, 2),
1475
"ROLE", PQgetvalue(res, i, 0),
1476
"DATABASE", PQgetvalue(res, i, 1));
1479
fprintf(OPF, "\n\n");
1483
destroyPQExpBuffer(buf);
1488
* Helper function for dumpXXXConfig().
1491
makeAlterConfigCommand(PGconn *conn, const char *arrayitem,
1492
const char *type, const char *name,
1493
const char *type2, const char *name2)
1497
PQExpBuffer buf = createPQExpBuffer();
1499
mine = strdup(arrayitem);
1500
pos = strchr(mine, '=');
1505
appendPQExpBuffer(buf, "ALTER %s %s ", type, fmtId(name));
1506
if (type2 != NULL && name2 != NULL)
1507
appendPQExpBuffer(buf, "IN %s %s ", type2, fmtId(name2));
1508
appendPQExpBuffer(buf, "SET %s TO ", fmtId(mine));
1511
* Some GUC variable names are 'LIST' type and hence must not be quoted.
1513
if (pg_strcasecmp(mine, "DateStyle") == 0
1514
|| pg_strcasecmp(mine, "search_path") == 0)
1515
appendPQExpBuffer(buf, "%s", pos + 1);
1517
appendStringLiteralConn(buf, pos + 1, conn);
1518
appendPQExpBuffer(buf, ";\n");
1520
fprintf(OPF, "%s", buf->data);
1521
destroyPQExpBuffer(buf);
1528
* Dump contents of databases.
1531
dumpDatabases(PGconn *conn)
1536
if (server_version >= 70100)
1537
res = executeQuery(conn, "SELECT datname FROM pg_database WHERE datallowconn ORDER BY 1");
1539
res = executeQuery(conn, "SELECT datname FROM pg_database ORDER BY 1");
1541
for (i = 0; i < PQntuples(res); i++)
1545
char *dbname = PQgetvalue(res, i, 0);
1548
fprintf(stderr, _("%s: dumping database \"%s\"...\n"), progname, dbname);
1550
fprintf(OPF, "\\connect %s\n\n", fmtId(dbname));
1555
ret = runPgDump(dbname);
1558
fprintf(stderr, _("%s: pg_dump failed on database \"%s\", exiting\n"), progname, dbname);
1564
OPF = fopen(filename, PG_BINARY_A);
1567
fprintf(stderr, _("%s: could not re-open the output file \"%s\": %s\n"),
1568
progname, filename, strerror(errno));
1581
* Run pg_dump on dbname.
1584
runPgDump(const char *dbname)
1586
PQExpBuffer cmd = createPQExpBuffer();
1589
appendPQExpBuffer(cmd, SYSTEMQUOTE "\"%s\" %s", pg_dump_bin,
1593
* If we have a filename, use the undocumented plain-append pg_dump
1597
appendPQExpBuffer(cmd, " -Fa ");
1599
appendPQExpBuffer(cmd, " -Fp ");
1601
doShellQuoting(cmd, dbname);
1603
appendPQExpBuffer(cmd, "%s", SYSTEMQUOTE);
1606
fprintf(stderr, _("%s: running \"%s\"\n"), progname, cmd->data);
1611
ret = system(cmd->data);
1613
destroyPQExpBuffer(cmd);
1620
* Make a database connection with the given parameters. An
1621
* interactive password prompt is automatically issued if required.
1623
* If fail_on_error is false, we return NULL without printing any message
1624
* on failure, but preserve any prompted password for the next try.
1627
connectDatabase(const char *dbname, const char *pghost, const char *pgport,
1628
const char *pguser, enum trivalue prompt_password, bool fail_on_error)
1632
const char *remoteversion_str;
1634
static char *password = NULL;
1636
if (prompt_password == TRI_YES && !password)
1637
password = simple_prompt("Password: ", 100, false);
1640
* Start the connection. Loop until we have a password if requested by
1645
#define PARAMS_ARRAY_SIZE 7
1646
const char **keywords = malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1647
const char **values = malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1649
if (!keywords || !values)
1651
fprintf(stderr, _("%s: out of memory\n"), progname);
1655
keywords[0] = "host";
1657
keywords[1] = "port";
1659
keywords[2] = "user";
1661
keywords[3] = "password";
1662
values[3] = password;
1663
keywords[4] = "dbname";
1665
keywords[5] = "fallback_application_name";
1666
values[5] = progname;
1671
conn = PQconnectdbParams(keywords, values, true);
1678
fprintf(stderr, _("%s: could not connect to database \"%s\"\n"),
1683
if (PQstatus(conn) == CONNECTION_BAD &&
1684
PQconnectionNeedsPassword(conn) &&
1686
prompt_password != TRI_NO)
1689
password = simple_prompt("Password: ", 100, false);
1694
/* check to see that the backend connection was successfully made */
1695
if (PQstatus(conn) == CONNECTION_BAD)
1700
_("%s: could not connect to database \"%s\": %s\n"),
1701
progname, dbname, PQerrorMessage(conn));
1711
remoteversion_str = PQparameterStatus(conn, "server_version");
1712
if (!remoteversion_str)
1714
fprintf(stderr, _("%s: could not get server version\n"), progname);
1717
server_version = parse_version(remoteversion_str);
1718
if (server_version < 0)
1720
fprintf(stderr, _("%s: could not parse server version \"%s\"\n"),
1721
progname, remoteversion_str);
1725
my_version = parse_version(PG_VERSION);
1728
fprintf(stderr, _("%s: could not parse version \"%s\"\n"),
1729
progname, PG_VERSION);
1734
* We allow the server to be back to 7.0, and up to any minor release of
1735
* our own major version. (See also version check in pg_dump.c.)
1737
if (my_version != server_version
1738
&& (server_version < 70000 ||
1739
(server_version / 100) > (my_version / 100)))
1741
fprintf(stderr, _("server version: %s; %s version: %s\n"),
1742
remoteversion_str, progname, PG_VERSION);
1743
fprintf(stderr, _("aborting because of server version mismatch\n"));
1748
* On 7.3 and later, make sure we are not fooled by non-system schemas in
1751
if (server_version >= 70300)
1752
executeCommand(conn, "SET search_path = pg_catalog");
1759
* Run a query, return the results, exit program on failure.
1762
executeQuery(PGconn *conn, const char *query)
1767
fprintf(stderr, _("%s: executing %s\n"), progname, query);
1769
res = PQexec(conn, query);
1771
PQresultStatus(res) != PGRES_TUPLES_OK)
1773
fprintf(stderr, _("%s: query failed: %s"),
1774
progname, PQerrorMessage(conn));
1775
fprintf(stderr, _("%s: query was: %s\n"),
1785
* As above for a SQL command (which returns nothing).
1788
executeCommand(PGconn *conn, const char *query)
1793
fprintf(stderr, _("%s: executing %s\n"), progname, query);
1795
res = PQexec(conn, query);
1797
PQresultStatus(res) != PGRES_COMMAND_OK)
1799
fprintf(stderr, _("%s: query failed: %s"),
1800
progname, PQerrorMessage(conn));
1801
fprintf(stderr, _("%s: query was: %s\n"),
1815
dumpTimestamp(char *msg)
1818
time_t now = time(NULL);
1821
* We don't print the timezone on Win32, because the names are long and
1822
* localized, which means they may contain characters in various random
1823
* encodings; this has been seen to cause encoding errors when reading the
1826
if (strftime(buf, sizeof(buf),
1828
"%Y-%m-%d %H:%M:%S %Z",
1830
"%Y-%m-%d %H:%M:%S",
1832
localtime(&now)) != 0)
1833
fprintf(OPF, "-- %s %s\n\n", msg, buf);
1838
* Append the given string to the shell command being built in the buffer,
1839
* with suitable shell-style quoting.
1842
doShellQuoting(PQExpBuffer buf, const char *str)
1847
appendPQExpBufferChar(buf, '\'');
1848
for (p = str; *p; p++)
1851
appendPQExpBuffer(buf, "'\"'\"'");
1853
appendPQExpBufferChar(buf, *p);
1855
appendPQExpBufferChar(buf, '\'');
1858
appendPQExpBufferChar(buf, '"');
1859
for (p = str; *p; p++)
1862
appendPQExpBuffer(buf, "\\\"");
1864
appendPQExpBufferChar(buf, *p);
1866
appendPQExpBufferChar(buf, '"');