PostgreSQL Source Code git master
pg_dumpall.c File Reference
#include "postgres_fe.h"
#include <time.h>
#include <unistd.h>
#include "catalog/pg_authid_d.h"
#include "common/connect.h"
#include "common/file_utils.h"
#include "common/hashfn_unstable.h"
#include "common/logging.h"
#include "common/string.h"
#include "dumputils.h"
#include "fe_utils/string_utils.h"
#include "filter.h"
#include "getopt_long.h"
#include "pg_backup.h"
#include "lib/simplehash.h"
Include dependency graph for pg_dumpall.c:

Go to the source code of this file.

Data Structures

struct  RoleNameEntry
 

Macros

#define PGDUMP_VERSIONSTR   "pg_dump (PostgreSQL) " PG_VERSION "\n"
 
#define SH_PREFIX   rolename
 
#define SH_ELEMENT_TYPE   RoleNameEntry
 
#define SH_KEY_TYPE   char *
 
#define SH_KEY   rolename
 
#define SH_HASH_KEY(tb, key)   hash_string(key)
 
#define SH_EQUAL(tb, a, b)   (strcmp(a, b) == 0)
 
#define SH_STORE_HASH
 
#define SH_GET_HASH(tb, a)   (a)->hashval
 
#define SH_SCOPE   static inline
 
#define SH_RAW_ALLOCATOR   pg_malloc0
 
#define SH_DECLARE
 
#define SH_DEFINE
 
#define PG_AUTHID   "pg_authid"
 
#define PG_ROLES   "pg_roles "
 
#define exit_nicely(code)   exit(code)
 

Functions

static void help (void)
 
static void dropRoles (PGconn *conn)
 
static void dumpRoles (PGconn *conn)
 
static void dumpRoleMembership (PGconn *conn)
 
static void dumpRoleGUCPrivs (PGconn *conn)
 
static void dropTablespaces (PGconn *conn)
 
static void dumpTablespaces (PGconn *conn)
 
static void dropDBs (PGconn *conn)
 
static void dumpUserConfig (PGconn *conn, const char *username)
 
static void dumpDatabases (PGconn *conn)
 
static void dumpTimestamp (const char *msg)
 
static int runPgDump (const char *dbname, const char *create_opts)
 
static void buildShSecLabels (PGconn *conn, const char *catalog_name, Oid objectId, const char *objtype, const char *objname, PQExpBuffer buffer)
 
static PGconnconnectDatabase (const char *dbname, const char *connection_string, const char *pghost, const char *pgport, const char *pguser, trivalue prompt_password, bool fail_on_error)
 
static char * constructConnStr (const char **keywords, const char **values)
 
static PGresultexecuteQuery (PGconn *conn, const char *query)
 
static void executeCommand (PGconn *conn, const char *query)
 
static void expand_dbname_patterns (PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
 
static void read_dumpall_filters (const char *filename, SimpleStringList *pattern)
 
int main (int argc, char *argv[])
 

Variables

static char pg_dump_bin [MAXPGPATH]
 
static const char * progname
 
static PQExpBuffer pgdumpopts
 
static char * connstr = ""
 
static bool output_clean = false
 
static bool skip_acls = false
 
static bool verbose = false
 
static bool dosync = true
 
static int binary_upgrade = 0
 
static int column_inserts = 0
 
static int disable_dollar_quoting = 0
 
static int disable_triggers = 0
 
static int if_exists = 0
 
static int inserts = 0
 
static int no_table_access_method = 0
 
static int no_tablespaces = 0
 
static int use_setsessauth = 0
 
static int no_comments = 0
 
static int no_publications = 0
 
static int no_security_labels = 0
 
static int no_subscriptions = 0
 
static int no_toast_compression = 0
 
static int no_unlogged_table_data = 0
 
static int no_role_passwords = 0
 
static int server_version
 
static int load_via_partition_root = 0
 
static int on_conflict_do_nothing = 0
 
static char role_catalog [10]
 
static FILE * OPF
 
static char * filename = NULL
 
static SimpleStringList database_exclude_patterns = {NULL, NULL}
 
static SimpleStringList database_exclude_names = {NULL, NULL}
 

Macro Definition Documentation

◆ exit_nicely

#define exit_nicely (   code)    exit(code)

Definition at line 124 of file pg_dumpall.c.

◆ PG_AUTHID

#define PG_AUTHID   "pg_authid"

Definition at line 115 of file pg_dumpall.c.

◆ PG_ROLES

#define PG_ROLES   "pg_roles "

Definition at line 116 of file pg_dumpall.c.

◆ PGDUMP_VERSIONSTR

#define PGDUMP_VERSIONSTR   "pg_dump (PostgreSQL) " PG_VERSION "\n"

Definition at line 34 of file pg_dumpall.c.

◆ SH_DECLARE

#define SH_DECLARE

Definition at line 53 of file pg_dumpall.c.

◆ SH_DEFINE

#define SH_DEFINE

Definition at line 54 of file pg_dumpall.c.

◆ SH_ELEMENT_TYPE

#define SH_ELEMENT_TYPE   RoleNameEntry

Definition at line 44 of file pg_dumpall.c.

◆ SH_EQUAL

#define SH_EQUAL (   tb,
  a,
  b 
)    (strcmp(a, b) == 0)

Definition at line 48 of file pg_dumpall.c.

◆ SH_GET_HASH

#define SH_GET_HASH (   tb,
  a 
)    (a)->hashval

Definition at line 50 of file pg_dumpall.c.

◆ SH_HASH_KEY

#define SH_HASH_KEY (   tb,
  key 
)    hash_string(key)

Definition at line 47 of file pg_dumpall.c.

◆ SH_KEY

#define SH_KEY   rolename

Definition at line 46 of file pg_dumpall.c.

◆ SH_KEY_TYPE

#define SH_KEY_TYPE   char *

Definition at line 45 of file pg_dumpall.c.

◆ SH_PREFIX

#define SH_PREFIX   rolename

Definition at line 43 of file pg_dumpall.c.

◆ SH_RAW_ALLOCATOR

#define SH_RAW_ALLOCATOR   pg_malloc0

Definition at line 52 of file pg_dumpall.c.

◆ SH_SCOPE

#define SH_SCOPE   static inline

Definition at line 51 of file pg_dumpall.c.

◆ SH_STORE_HASH

#define SH_STORE_HASH

Definition at line 49 of file pg_dumpall.c.

Function Documentation

◆ buildShSecLabels()

static void buildShSecLabels ( PGconn conn,
const char *  catalog_name,
Oid  objectId,
const char *  objtype,
const char *  objname,
PQExpBuffer  buffer 
)
static

Definition at line 1638 of file pg_dumpall.c.

1641{
1643 PGresult *res;
1644
1645 buildShSecLabelQuery(catalog_name, objectId, sql);
1646 res = executeQuery(conn, sql->data);
1647 emitShSecLabels(conn, res, buffer, objtype, objname);
1648
1649 PQclear(res);
1650 destroyPQExpBuffer(sql);
1651}
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition: dumputils.c:637
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition: dumputils.c:655
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1884
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
PGconn * conn
Definition: streamutil.c:53

References buildShSecLabelQuery(), conn, createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), emitShSecLabels(), executeQuery(), PQclear(), and res.

Referenced by dumpRoles(), and dumpTablespaces().

◆ connectDatabase()

static PGconn * connectDatabase ( const char *  dbname,
const char *  connection_string,
const char *  pghost,
const char *  pgport,
const char *  pguser,
trivalue  prompt_password,
bool  fail_on_error 
)
static

Definition at line 1664 of file pg_dumpall.c.

1667{
1668 PGconn *conn;
1669 bool new_pass;
1670 const char *remoteversion_str;
1671 int my_version;
1672 const char **keywords = NULL;
1673 const char **values = NULL;
1674 PQconninfoOption *conn_opts = NULL;
1675 static char *password = NULL;
1676
1677 if (prompt_password == TRI_YES && !password)
1678 password = simple_prompt("Password: ", false);
1679
1680 /*
1681 * Start the connection. Loop until we have a password if requested by
1682 * backend.
1683 */
1684 do
1685 {
1686 int argcount = 6;
1687 PQconninfoOption *conn_opt;
1688 char *err_msg = NULL;
1689 int i = 0;
1690
1691 free(keywords);
1692 free(values);
1693 PQconninfoFree(conn_opts);
1694
1695 /*
1696 * Merge the connection info inputs given in form of connection string
1697 * and other options. Explicitly discard any dbname value in the
1698 * connection string; otherwise, PQconnectdbParams() would interpret
1699 * that value as being itself a connection string.
1700 */
1702 {
1703 conn_opts = PQconninfoParse(connection_string, &err_msg);
1704 if (conn_opts == NULL)
1705 pg_fatal("%s", err_msg);
1706
1707 for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1708 {
1709 if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1710 strcmp(conn_opt->keyword, "dbname") != 0)
1711 argcount++;
1712 }
1713
1714 keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1715 values = pg_malloc0((argcount + 1) * sizeof(*values));
1716
1717 for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1718 {
1719 if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1720 strcmp(conn_opt->keyword, "dbname") != 0)
1721 {
1722 keywords[i] = conn_opt->keyword;
1723 values[i] = conn_opt->val;
1724 i++;
1725 }
1726 }
1727 }
1728 else
1729 {
1730 keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1731 values = pg_malloc0((argcount + 1) * sizeof(*values));
1732 }
1733
1734 if (pghost)
1735 {
1736 keywords[i] = "host";
1737 values[i] = pghost;
1738 i++;
1739 }
1740 if (pgport)
1741 {
1742 keywords[i] = "port";
1743 values[i] = pgport;
1744 i++;
1745 }
1746 if (pguser)
1747 {
1748 keywords[i] = "user";
1749 values[i] = pguser;
1750 i++;
1751 }
1752 if (password)
1753 {
1754 keywords[i] = "password";
1755 values[i] = password;
1756 i++;
1757 }
1758 if (dbname)
1759 {
1760 keywords[i] = "dbname";
1761 values[i] = dbname;
1762 i++;
1763 }
1764 keywords[i] = "fallback_application_name";
1765 values[i] = progname;
1766 i++;
1767
1768 new_pass = false;
1770
1771 if (!conn)
1772 pg_fatal("could not connect to database \"%s\"", dbname);
1773
1774 if (PQstatus(conn) == CONNECTION_BAD &&
1776 !password &&
1777 prompt_password != TRI_NO)
1778 {
1779 PQfinish(conn);
1780 password = simple_prompt("Password: ", false);
1781 new_pass = true;
1782 }
1783 } while (new_pass);
1784
1785 /* check to see that the backend connection was successfully made */
1787 {
1788 if (fail_on_error)
1790 else
1791 {
1792 PQfinish(conn);
1793
1794 free(keywords);
1795 free(values);
1796 PQconninfoFree(conn_opts);
1797
1798 return NULL;
1799 }
1800 }
1801
1802 /*
1803 * Ok, connected successfully. Remember the options used, in the form of a
1804 * connection string.
1805 */
1807
1808 free(keywords);
1809 free(values);
1810 PQconninfoFree(conn_opts);
1811
1812 /* Check version */
1813 remoteversion_str = PQparameterStatus(conn, "server_version");
1814 if (!remoteversion_str)
1815 pg_fatal("could not get server version");
1817 if (server_version == 0)
1818 pg_fatal("could not parse server version \"%s\"",
1819 remoteversion_str);
1820
1821 my_version = PG_VERSION_NUM;
1822
1823 /*
1824 * We allow the server to be back to 9.2, and up to any minor release of
1825 * our own major version. (See also version check in pg_dump.c.)
1826 */
1827 if (my_version != server_version
1828 && (server_version < 90200 ||
1829 (server_version / 100) > (my_version / 100)))
1830 {
1831 pg_log_error("aborting because of server version mismatch");
1832 pg_log_error_detail("server version: %s; %s version: %s",
1833 remoteversion_str, progname, PG_VERSION);
1834 exit_nicely(1);
1835 }
1836
1838
1839 return conn;
1840}
static Datum values[MAXATTR]
Definition: bootstrap.c:151
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7497
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7322
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:6038
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7462
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7560
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7444
void PQfinish(PGconn *conn)
Definition: fe-connect.c:5178
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7507
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:717
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:72
static const JsonPathKeyword keywords[]
@ CONNECTION_BAD
Definition: libpq-fe.h:82
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_detail(...)
Definition: logging.h:109
#define pg_fatal(...)
static char * connstr
Definition: pg_dumpall.c:88
#define exit_nicely(code)
Definition: pg_dumpall.c:124
static char * constructConnStr(const char **keywords, const char **values)
Definition: pg_dumpall.c:1853
static int server_version
Definition: pg_dumpall.c:110
static const char * progname
Definition: pg_dumpall.c:86
static const char * pghost
Definition: pgbench.c:295
static const char * pgport
Definition: pgbench.c:296
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static char * password
Definition: streamutil.c:52
char * connection_string
Definition: streamutil.c:46
char * dbname
Definition: streamutil.c:50
@ TRI_YES
Definition: vacuumlo.c:38
@ TRI_NO
Definition: vacuumlo.c:37

References ALWAYS_SECURE_SEARCH_PATH_SQL, conn, CONNECTION_BAD, connection_string, connstr, constructConnStr(), dbname, executeQuery(), exit_nicely, free, i, _PQconninfoOption::keyword, keywords, password, pg_fatal, pg_log_error, pg_log_error_detail, pg_malloc0(), pghost, pgport, PQclear(), PQconnectdbParams(), PQconnectionNeedsPassword(), PQconninfoFree(), PQconninfoParse(), PQerrorMessage(), PQfinish(), PQparameterStatus(), PQserverVersion(), PQstatus(), progname, server_version, simple_prompt(), TRI_NO, TRI_YES, _PQconninfoOption::val, and values.

Referenced by cluster_one_database(), connect_slot(), main(), reindex_one_database(), and vacuum_one_database().

◆ constructConnStr()

static char * constructConnStr ( const char **  keywords,
const char **  values 
)
static

Definition at line 1853 of file pg_dumpall.c.

1854{
1856 char *connstr;
1857 int i;
1858 bool firstkeyword = true;
1859
1860 /* Construct a new connection string in key='value' format. */
1861 for (i = 0; keywords[i] != NULL; i++)
1862 {
1863 if (strcmp(keywords[i], "dbname") == 0 ||
1864 strcmp(keywords[i], "password") == 0 ||
1865 strcmp(keywords[i], "fallback_application_name") == 0)
1866 continue;
1867
1868 if (!firstkeyword)
1870 firstkeyword = false;
1871 appendPQExpBuffer(buf, "%s=", keywords[i]);
1873 }
1874
1875 connstr = pg_strdup(buf->data);
1877 return connstr;
1878}
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * buf
Definition: pg_test_fsync.c:72
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:719

References appendConnStrVal(), appendPQExpBuffer(), appendPQExpBufferChar(), buf, connstr, createPQExpBuffer(), destroyPQExpBuffer(), i, keywords, pg_strdup(), and values.

Referenced by connectDatabase().

◆ dropDBs()

static void dropDBs ( PGconn conn)
static

Definition at line 1355 of file pg_dumpall.c.

1356{
1357 PGresult *res;
1358 int i;
1359
1360 /*
1361 * Skip databases marked not datallowconn, since we'd be unable to connect
1362 * to them anyway. This must agree with dumpDatabases().
1363 */
1365 "SELECT datname "
1366 "FROM pg_database d "
1367 "WHERE datallowconn AND datconnlimit != -2 "
1368 "ORDER BY datname");
1369
1370 if (PQntuples(res) > 0)
1371 fprintf(OPF, "--\n-- Drop databases (except postgres and template1)\n--\n\n");
1372
1373 for (i = 0; i < PQntuples(res); i++)
1374 {
1375 char *dbname = PQgetvalue(res, i, 0);
1376
1377 /*
1378 * Skip "postgres" and "template1"; dumpDatabases() will deal with
1379 * them specially. Also, be sure to skip "template0", even if for
1380 * some reason it's not marked !datallowconn.
1381 */
1382 if (strcmp(dbname, "template1") != 0 &&
1383 strcmp(dbname, "template0") != 0 &&
1384 strcmp(dbname, "postgres") != 0)
1385 {
1386 fprintf(OPF, "DROP DATABASE %s%s;\n",
1387 if_exists ? "IF EXISTS " : "",
1388 fmtId(dbname));
1389 }
1390 }
1391
1392 PQclear(res);
1393
1394 fprintf(OPF, "\n\n");
1395}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
static int if_exists
Definition: pg_dumpall.c:98
static FILE * OPF
Definition: pg_dumpall.c:118
const char * fmtId(const char *rawid)
Definition: string_utils.c:259

References conn, dbname, executeQuery(), fmtId(), fprintf, i, if_exists, OPF, PQclear(), PQgetvalue(), PQntuples(), and res.

Referenced by main().

◆ dropRoles()

static void dropRoles ( PGconn conn)
static

Definition at line 704 of file pg_dumpall.c.

705{
707 PGresult *res;
708 int i_rolname;
709 int i;
710
711 if (server_version >= 90600)
713 "SELECT rolname "
714 "FROM %s "
715 "WHERE rolname !~ '^pg_' "
716 "ORDER BY 1", role_catalog);
717 else
719 "SELECT rolname "
720 "FROM %s "
721 "ORDER BY 1", role_catalog);
722
723 res = executeQuery(conn, buf->data);
724
725 i_rolname = PQfnumber(res, "rolname");
726
727 if (PQntuples(res) > 0)
728 fprintf(OPF, "--\n-- Drop roles\n--\n\n");
729
730 for (i = 0; i < PQntuples(res); i++)
731 {
732 const char *rolename;
733
734 rolename = PQgetvalue(res, i, i_rolname);
735
736 fprintf(OPF, "DROP ROLE %s%s;\n",
737 if_exists ? "IF EXISTS " : "",
738 fmtId(rolename));
739 }
740
741 PQclear(res);
743
744 fprintf(OPF, "\n\n");
745}
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3589
static char role_catalog[10]
Definition: pg_dumpall.c:114
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235

References buf, conn, createPQExpBuffer(), destroyPQExpBuffer(), executeQuery(), fmtId(), fprintf, i, if_exists, OPF, PQclear(), PQfnumber(), PQgetvalue(), PQntuples(), printfPQExpBuffer(), res, role_catalog, and server_version.

Referenced by main().

◆ dropTablespaces()

static void dropTablespaces ( PGconn conn)
static

Definition at line 1216 of file pg_dumpall.c.

1217{
1218 PGresult *res;
1219 int i;
1220
1221 /*
1222 * Get all tablespaces except built-in ones (which we assume are named
1223 * pg_xxx)
1224 */
1225 res = executeQuery(conn, "SELECT spcname "
1226 "FROM pg_catalog.pg_tablespace "
1227 "WHERE spcname !~ '^pg_' "
1228 "ORDER BY 1");
1229
1230 if (PQntuples(res) > 0)
1231 fprintf(OPF, "--\n-- Drop tablespaces\n--\n\n");
1232
1233 for (i = 0; i < PQntuples(res); i++)
1234 {
1235 char *spcname = PQgetvalue(res, i, 0);
1236
1237 fprintf(OPF, "DROP TABLESPACE %s%s;\n",
1238 if_exists ? "IF EXISTS " : "",
1239 fmtId(spcname));
1240 }
1241
1242 PQclear(res);
1243
1244 fprintf(OPF, "\n\n");
1245}

References conn, executeQuery(), fmtId(), fprintf, i, if_exists, OPF, PQclear(), PQgetvalue(), PQntuples(), and res.

Referenced by main().

◆ dumpDatabases()

static void dumpDatabases ( PGconn conn)
static

Definition at line 1491 of file pg_dumpall.c.

1492{
1493 PGresult *res;
1494 int i;
1495
1496 /*
1497 * Skip databases marked not datallowconn, since we'd be unable to connect
1498 * to them anyway. This must agree with dropDBs().
1499 *
1500 * We arrange for template1 to be processed first, then we process other
1501 * DBs in alphabetical order. If we just did them all alphabetically, we
1502 * might find ourselves trying to drop the "postgres" database while still
1503 * connected to it. This makes trying to run the restore script while
1504 * connected to "template1" a bad idea, but there's no fixed order that
1505 * doesn't have some failure mode with --clean.
1506 */
1508 "SELECT datname "
1509 "FROM pg_database d "
1510 "WHERE datallowconn AND datconnlimit != -2 "
1511 "ORDER BY (datname <> 'template1'), datname");
1512
1513 if (PQntuples(res) > 0)
1514 fprintf(OPF, "--\n-- Databases\n--\n\n");
1515
1516 for (i = 0; i < PQntuples(res); i++)
1517 {
1518 char *dbname = PQgetvalue(res, i, 0);
1519 const char *create_opts;
1520 int ret;
1521
1522 /* Skip template0, even if it's not marked !datallowconn. */
1523 if (strcmp(dbname, "template0") == 0)
1524 continue;
1525
1526 /* Skip any explicitly excluded database */
1528 {
1529 pg_log_info("excluding database \"%s\"", dbname);
1530 continue;
1531 }
1532
1533 pg_log_info("dumping database \"%s\"", dbname);
1534
1535 fprintf(OPF, "--\n-- Database \"%s\" dump\n--\n\n", dbname);
1536
1537 /*
1538 * We assume that "template1" and "postgres" already exist in the
1539 * target installation. dropDBs() won't have removed them, for fear
1540 * of removing the DB the restore script is initially connected to. If
1541 * --clean was specified, tell pg_dump to drop and recreate them;
1542 * otherwise we'll merely restore their contents. Other databases
1543 * should simply be created.
1544 */
1545 if (strcmp(dbname, "template1") == 0 || strcmp(dbname, "postgres") == 0)
1546 {
1547 if (output_clean)
1548 create_opts = "--clean --create";
1549 else
1550 {
1551 create_opts = "";
1552 /* Since pg_dump won't emit a \connect command, we must */
1553 fprintf(OPF, "\\connect %s\n\n", dbname);
1554 }
1555 }
1556 else
1557 create_opts = "--create";
1558
1559 if (filename)
1560 fclose(OPF);
1561
1562 ret = runPgDump(dbname, create_opts);
1563 if (ret != 0)
1564 pg_fatal("pg_dump failed on database \"%s\", exiting", dbname);
1565
1566 if (filename)
1567 {
1568 OPF = fopen(filename, PG_BINARY_A);
1569 if (!OPF)
1570 pg_fatal("could not re-open the output file \"%s\": %m",
1571 filename);
1572 }
1573 }
1574
1575 PQclear(res);
1576}
#define PG_BINARY_A
Definition: c.h:1231
#define pg_log_info(...)
Definition: logging.h:124
static SimpleStringList database_exclude_names
Definition: pg_dumpall.c:122
static int runPgDump(const char *dbname, const char *create_opts)
Definition: pg_dumpall.c:1584
static bool output_clean
Definition: pg_dumpall.c:89
static char * filename
Definition: pg_dumpall.c:119
bool simple_string_list_member(SimpleStringList *list, const char *val)
Definition: simple_list.c:87

References conn, database_exclude_names, dbname, executeQuery(), filename, fprintf, i, OPF, output_clean, PG_BINARY_A, pg_fatal, pg_log_info, PQclear(), PQgetvalue(), PQntuples(), res, runPgDump(), and simple_string_list_member().

Referenced by main().

◆ dumpRoleGUCPrivs()

static void dumpRoleGUCPrivs ( PGconn conn)
static

Definition at line 1161 of file pg_dumpall.c.

1162{
1163 PGresult *res;
1164 int i;
1165
1166 /*
1167 * Get all parameters that have non-default acls defined.
1168 */
1169 res = executeQuery(conn, "SELECT parname, "
1170 "pg_catalog.pg_get_userbyid(" CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS parowner, "
1171 "paracl, "
1172 "pg_catalog.acldefault('p', " CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS acldefault "
1173 "FROM pg_catalog.pg_parameter_acl "
1174 "ORDER BY 1");
1175
1176 if (PQntuples(res) > 0)
1177 fprintf(OPF, "--\n-- Role privileges on configuration parameters\n--\n\n");
1178
1179 for (i = 0; i < PQntuples(res); i++)
1180 {
1182 char *parname = PQgetvalue(res, i, 0);
1183 char *parowner = PQgetvalue(res, i, 1);
1184 char *paracl = PQgetvalue(res, i, 2);
1185 char *acldefault = PQgetvalue(res, i, 3);
1186 char *fparname;
1187
1188 /* needed for buildACLCommands() */
1189 fparname = pg_strdup(fmtId(parname));
1190
1191 if (!buildACLCommands(fparname, NULL, NULL, "PARAMETER",
1192 paracl, acldefault,
1193 parowner, "", server_version, buf))
1194 {
1195 pg_log_error("could not parse ACL list (%s) for parameter \"%s\"",
1196 paracl, parname);
1197 PQfinish(conn);
1198 exit_nicely(1);
1199 }
1200
1201 fprintf(OPF, "%s", buf->data);
1202
1203 free(fparname);
1205 }
1206
1207 PQclear(res);
1208 fprintf(OPF, "\n\n");
1209}
Acl * acldefault(ObjectType objtype, Oid ownerId)
Definition: acl.c:787
#define CppAsString2(x)
Definition: c.h:349
bool buildACLCommands(const char *name, const char *subname, const char *nspname, const char *type, const char *acls, const char *baseacls, const char *owner, const char *prefix, int remoteVersion, PQExpBuffer sql)
Definition: dumputils.c:64

References acldefault(), buf, buildACLCommands(), conn, CppAsString2, createPQExpBuffer(), destroyPQExpBuffer(), executeQuery(), exit_nicely, fmtId(), fprintf, free, i, OPF, pg_log_error, pg_strdup(), PQclear(), PQfinish(), PQgetvalue(), PQntuples(), res, and server_version.

Referenced by main().

◆ dumpRoleMembership()

static void dumpRoleMembership ( PGconn conn)
static

Definition at line 959 of file pg_dumpall.c.

960{
963 PGresult *res;
964 int start = 0,
965 end,
966 total;
967 bool dump_grantors;
968 bool dump_grant_options;
969 int i_inherit_option;
970 int i_set_option;
971
972 /*
973 * Previous versions of PostgreSQL didn't used to track the grantor very
974 * carefully in the backend, and the grantor could be any user even if
975 * they didn't have ADMIN OPTION on the role, or a user that no longer
976 * existed. To avoid dump and restore failures, don't dump the grantor
977 * when talking to an old server version.
978 */
979 dump_grantors = (PQserverVersion(conn) >= 160000);
980
981 /*
982 * Previous versions of PostgreSQL also did not have grant-level options.
983 */
984 dump_grant_options = (server_version >= 160000);
985
986 /* Generate and execute query. */
987 printfPQExpBuffer(buf, "SELECT ur.rolname AS role, "
988 "um.rolname AS member, "
989 "ug.oid AS grantorid, "
990 "ug.rolname AS grantor, "
991 "a.admin_option");
992 if (dump_grant_options)
993 appendPQExpBufferStr(buf, ", a.inherit_option, a.set_option");
994 appendPQExpBuffer(buf, " FROM pg_auth_members a "
995 "LEFT JOIN %s ur on ur.oid = a.roleid "
996 "LEFT JOIN %s um on um.oid = a.member "
997 "LEFT JOIN %s ug on ug.oid = a.grantor "
998 "WHERE NOT (ur.rolname ~ '^pg_' AND um.rolname ~ '^pg_')"
999 "ORDER BY 1,2,4", role_catalog, role_catalog, role_catalog);
1000 res = executeQuery(conn, buf->data);
1001 i_inherit_option = PQfnumber(res, "inherit_option");
1002 i_set_option = PQfnumber(res, "set_option");
1003
1004 if (PQntuples(res) > 0)
1005 fprintf(OPF, "--\n-- Role memberships\n--\n\n");
1006
1007 /*
1008 * We can't dump these GRANT commands in arbitrary order, because a role
1009 * that is named as a grantor must already have ADMIN OPTION on the role
1010 * for which it is granting permissions, except for the bootstrap
1011 * superuser, who can always be named as the grantor.
1012 *
1013 * We handle this by considering these grants role by role. For each role,
1014 * we initially consider the only allowable grantor to be the bootstrap
1015 * superuser. Every time we grant ADMIN OPTION on the role to some user,
1016 * that user also becomes an allowable grantor. We make repeated passes
1017 * over the grants for the role, each time dumping those whose grantors
1018 * are allowable and which we haven't done yet. Eventually this should let
1019 * us dump all the grants.
1020 */
1021 total = PQntuples(res);
1022 while (start < total)
1023 {
1024 char *role = PQgetvalue(res, start, 0);
1025 int i;
1026 bool *done;
1027 int remaining;
1028 int prev_remaining = 0;
1029 rolename_hash *ht;
1030
1031 /* All memberships for a single role should be adjacent. */
1032 for (end = start; end < total; ++end)
1033 {
1034 char *otherrole;
1035
1036 otherrole = PQgetvalue(res, end, 0);
1037 if (strcmp(role, otherrole) != 0)
1038 break;
1039 }
1040
1041 role = PQgetvalue(res, start, 0);
1042 remaining = end - start;
1043 done = pg_malloc0(remaining * sizeof(bool));
1044 ht = rolename_create(remaining, NULL);
1045
1046 /*
1047 * Make repeated passes over the grants for this role until all have
1048 * been dumped.
1049 */
1050 while (remaining > 0)
1051 {
1052 /*
1053 * We should make progress on every iteration, because a notional
1054 * graph whose vertices are grants and whose edges point from
1055 * grantors to members should be connected and acyclic. If we fail
1056 * to make progress, either we or the server have messed up.
1057 */
1058 if (remaining == prev_remaining)
1059 {
1060 pg_log_error("could not find a legal dump ordering for memberships in role \"%s\"",
1061 role);
1062 PQfinish(conn);
1063 exit_nicely(1);
1064 }
1065 prev_remaining = remaining;
1066
1067 /* Make one pass over the grants for this role. */
1068 for (i = start; i < end; ++i)
1069 {
1070 char *member;
1071 char *admin_option;
1072 char *grantorid;
1073 char *grantor;
1074 char *set_option = "true";
1075 bool found;
1076
1077 /* If we already did this grant, don't do it again. */
1078 if (done[i - start])
1079 continue;
1080
1081 member = PQgetvalue(res, i, 1);
1082 grantorid = PQgetvalue(res, i, 2);
1083 grantor = PQgetvalue(res, i, 3);
1085 if (dump_grant_options)
1086 set_option = PQgetvalue(res, i, i_set_option);
1087
1088 /*
1089 * If we're not dumping grantors or if the grantor is the
1090 * bootstrap superuser, it's fine to dump this now. Otherwise,
1091 * it's got to be someone who has already been granted ADMIN
1092 * OPTION.
1093 */
1094 if (dump_grantors &&
1095 atooid(grantorid) != BOOTSTRAP_SUPERUSERID &&
1096 rolename_lookup(ht, grantor) == NULL)
1097 continue;
1098
1099 /* Remember that we did this so that we don't do it again. */
1100 done[i - start] = true;
1101 --remaining;
1102
1103 /*
1104 * If ADMIN OPTION is being granted, remember that grants
1105 * listing this member as the grantor can now be dumped.
1106 */
1107 if (*admin_option == 't')
1108 rolename_insert(ht, member, &found);
1109
1110 /* Generate the actual GRANT statement. */
1111 resetPQExpBuffer(optbuf);
1112 fprintf(OPF, "GRANT %s", fmtId(role));
1113 fprintf(OPF, " TO %s", fmtId(member));
1114 if (*admin_option == 't')
1115 appendPQExpBufferStr(optbuf, "ADMIN OPTION");
1116 if (dump_grant_options)
1117 {
1118 char *inherit_option;
1119
1120 if (optbuf->data[0] != '\0')
1121 appendPQExpBufferStr(optbuf, ", ");
1122 inherit_option = PQgetvalue(res, i, i_inherit_option);
1123 appendPQExpBuffer(optbuf, "INHERIT %s",
1124 *inherit_option == 't' ?
1125 "TRUE" : "FALSE");
1126 }
1127 if (*set_option != 't')
1128 {
1129 if (optbuf->data[0] != '\0')
1130 appendPQExpBufferStr(optbuf, ", ");
1131 appendPQExpBuffer(optbuf, "SET FALSE");
1132 }
1133 if (optbuf->data[0] != '\0')
1134 fprintf(OPF, " WITH %s", optbuf->data);
1135 if (dump_grantors)
1136 fprintf(OPF, " GRANTED BY %s", fmtId(grantor));
1137 fprintf(OPF, ";\n");
1138 }
1139 }
1140
1141 rolename_destroy(ht);
1142 pg_free(done);
1143 start = end;
1144 }
1145
1146 PQclear(res);
1148
1149 fprintf(OPF, "\n\n");
1150}
void pg_free(void *ptr)
Definition: fe_memutils.c:105
return str start
int remaining
Definition: informix.c:692
bool set_option
bool inherit_option
bool admin_option
#define atooid(x)
Definition: postgres_ext.h:43
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367

References admin_option, appendPQExpBuffer(), appendPQExpBufferStr(), atooid, buf, conn, createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), executeQuery(), exit_nicely, fmtId(), fprintf, i, inherit_option, OPF, pg_free(), pg_log_error, pg_malloc0(), PQclear(), PQfinish(), PQfnumber(), PQgetvalue(), PQntuples(), PQserverVersion(), printfPQExpBuffer(), remaining, res, resetPQExpBuffer(), role_catalog, server_version, set_option, and start.

Referenced by main().

◆ dumpRoles()

static void dumpRoles ( PGconn conn)
static

Definition at line 751 of file pg_dumpall.c.

752{
754 PGresult *res;
755 int i_oid,
756 i_rolname,
757 i_rolsuper,
758 i_rolinherit,
759 i_rolcreaterole,
760 i_rolcreatedb,
761 i_rolcanlogin,
762 i_rolconnlimit,
763 i_rolpassword,
764 i_rolvaliduntil,
765 i_rolreplication,
766 i_rolbypassrls,
767 i_rolcomment,
768 i_is_current_user;
769 int i;
770
771 /*
772 * Notes: rolconfig is dumped later, and pg_authid must be used for
773 * extracting rolcomment regardless of role_catalog.
774 */
775 if (server_version >= 90600)
777 "SELECT oid, rolname, rolsuper, rolinherit, "
778 "rolcreaterole, rolcreatedb, "
779 "rolcanlogin, rolconnlimit, rolpassword, "
780 "rolvaliduntil, rolreplication, rolbypassrls, "
781 "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
782 "rolname = current_user AS is_current_user "
783 "FROM %s "
784 "WHERE rolname !~ '^pg_' "
785 "ORDER BY 2", role_catalog);
786 else if (server_version >= 90500)
788 "SELECT oid, rolname, rolsuper, rolinherit, "
789 "rolcreaterole, rolcreatedb, "
790 "rolcanlogin, rolconnlimit, rolpassword, "
791 "rolvaliduntil, rolreplication, rolbypassrls, "
792 "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
793 "rolname = current_user AS is_current_user "
794 "FROM %s "
795 "ORDER BY 2", role_catalog);
796 else
798 "SELECT oid, rolname, rolsuper, rolinherit, "
799 "rolcreaterole, rolcreatedb, "
800 "rolcanlogin, rolconnlimit, rolpassword, "
801 "rolvaliduntil, rolreplication, "
802 "false as rolbypassrls, "
803 "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
804 "rolname = current_user AS is_current_user "
805 "FROM %s "
806 "ORDER BY 2", role_catalog);
807
808 res = executeQuery(conn, buf->data);
809
810 i_oid = PQfnumber(res, "oid");
811 i_rolname = PQfnumber(res, "rolname");
812 i_rolsuper = PQfnumber(res, "rolsuper");
813 i_rolinherit = PQfnumber(res, "rolinherit");
814 i_rolcreaterole = PQfnumber(res, "rolcreaterole");
815 i_rolcreatedb = PQfnumber(res, "rolcreatedb");
816 i_rolcanlogin = PQfnumber(res, "rolcanlogin");
817 i_rolconnlimit = PQfnumber(res, "rolconnlimit");
818 i_rolpassword = PQfnumber(res, "rolpassword");
819 i_rolvaliduntil = PQfnumber(res, "rolvaliduntil");
820 i_rolreplication = PQfnumber(res, "rolreplication");
821 i_rolbypassrls = PQfnumber(res, "rolbypassrls");
822 i_rolcomment = PQfnumber(res, "rolcomment");
823 i_is_current_user = PQfnumber(res, "is_current_user");
824
825 if (PQntuples(res) > 0)
826 fprintf(OPF, "--\n-- Roles\n--\n\n");
827
828 for (i = 0; i < PQntuples(res); i++)
829 {
830 const char *rolename;
831 Oid auth_oid;
832
833 auth_oid = atooid(PQgetvalue(res, i, i_oid));
834 rolename = PQgetvalue(res, i, i_rolname);
835
836 if (strncmp(rolename, "pg_", 3) == 0)
837 {
838 pg_log_warning("role name starting with \"pg_\" skipped (%s)",
839 rolename);
840 continue;
841 }
842
844
845 if (binary_upgrade)
846 {
847 appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_authid.oid\n");
849 "SELECT pg_catalog.binary_upgrade_set_next_pg_authid_oid('%u'::pg_catalog.oid);\n\n",
850 auth_oid);
851 }
852
853 /*
854 * We dump CREATE ROLE followed by ALTER ROLE to ensure that the role
855 * will acquire the right properties even if it already exists (ie, it
856 * won't hurt for the CREATE to fail). This is particularly important
857 * for the role we are connected as, since even with --clean we will
858 * have failed to drop it. binary_upgrade cannot generate any errors,
859 * so we assume the current role is already created.
860 */
861 if (!binary_upgrade ||
862 strcmp(PQgetvalue(res, i, i_is_current_user), "f") == 0)
863 appendPQExpBuffer(buf, "CREATE ROLE %s;\n", fmtId(rolename));
864 appendPQExpBuffer(buf, "ALTER ROLE %s WITH", fmtId(rolename));
865
866 if (strcmp(PQgetvalue(res, i, i_rolsuper), "t") == 0)
867 appendPQExpBufferStr(buf, " SUPERUSER");
868 else
869 appendPQExpBufferStr(buf, " NOSUPERUSER");
870
871 if (strcmp(PQgetvalue(res, i, i_rolinherit), "t") == 0)
872 appendPQExpBufferStr(buf, " INHERIT");
873 else
874 appendPQExpBufferStr(buf, " NOINHERIT");
875
876 if (strcmp(PQgetvalue(res, i, i_rolcreaterole), "t") == 0)
877 appendPQExpBufferStr(buf, " CREATEROLE");
878 else
879 appendPQExpBufferStr(buf, " NOCREATEROLE");
880
881 if (strcmp(PQgetvalue(res, i, i_rolcreatedb), "t") == 0)
882 appendPQExpBufferStr(buf, " CREATEDB");
883 else
884 appendPQExpBufferStr(buf, " NOCREATEDB");
885
886 if (strcmp(PQgetvalue(res, i, i_rolcanlogin), "t") == 0)
887 appendPQExpBufferStr(buf, " LOGIN");
888 else
889 appendPQExpBufferStr(buf, " NOLOGIN");
890
891 if (strcmp(PQgetvalue(res, i, i_rolreplication), "t") == 0)
892 appendPQExpBufferStr(buf, " REPLICATION");
893 else
894 appendPQExpBufferStr(buf, " NOREPLICATION");
895
896 if (strcmp(PQgetvalue(res, i, i_rolbypassrls), "t") == 0)
897 appendPQExpBufferStr(buf, " BYPASSRLS");
898 else
899 appendPQExpBufferStr(buf, " NOBYPASSRLS");
900
901 if (strcmp(PQgetvalue(res, i, i_rolconnlimit), "-1") != 0)
902 appendPQExpBuffer(buf, " CONNECTION LIMIT %s",
903 PQgetvalue(res, i, i_rolconnlimit));
904
905
906 if (!PQgetisnull(res, i, i_rolpassword) && !no_role_passwords)
907 {
908 appendPQExpBufferStr(buf, " PASSWORD ");
909 appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolpassword), conn);
910 }
911
912 if (!PQgetisnull(res, i, i_rolvaliduntil))
913 appendPQExpBuffer(buf, " VALID UNTIL '%s'",
914 PQgetvalue(res, i, i_rolvaliduntil));
915
917
918 if (!no_comments && !PQgetisnull(res, i, i_rolcomment))
919 {
920 appendPQExpBuffer(buf, "COMMENT ON ROLE %s IS ", fmtId(rolename));
921 appendStringLiteralConn(buf, PQgetvalue(res, i, i_rolcomment), conn);
923 }
924
926 buildShSecLabels(conn, "pg_authid", auth_oid,
927 "ROLE", rolename,
928 buf);
929
930 fprintf(OPF, "%s", buf->data);
931 }
932
933 /*
934 * Dump configuration settings for roles after all roles have been dumped.
935 * We do it this way because config settings for roles could mention the
936 * names of other roles.
937 */
938 if (PQntuples(res) > 0)
939 fprintf(OPF, "\n--\n-- User Configurations\n--\n");
940
941 for (i = 0; i < PQntuples(res); i++)
942 dumpUserConfig(conn, PQgetvalue(res, i, i_rolname));
943
944 PQclear(res);
945
946 fprintf(OPF, "\n\n");
947
949}
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3901
static int no_role_passwords
Definition: pg_dumpall.c:109
static int binary_upgrade
Definition: pg_dumpall.c:94
static void dumpUserConfig(PGconn *conn, const char *username)
Definition: pg_dumpall.c:1402
static int no_comments
Definition: pg_dumpall.c:103
static int no_security_labels
Definition: pg_dumpall.c:105
static void buildShSecLabels(PGconn *conn, const char *catalog_name, Oid objectId, const char *objtype, const char *objname, PQExpBuffer buffer)
Definition: pg_dumpall.c:1638
#define pg_log_warning(...)
Definition: pgfnames.c:24
unsigned int Oid
Definition: postgres_ext.h:32
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:467

References appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), atooid, binary_upgrade, buf, buildShSecLabels(), conn, createPQExpBuffer(), destroyPQExpBuffer(), dumpUserConfig(), executeQuery(), fmtId(), fprintf, i, no_comments, no_role_passwords, no_security_labels, OPF, pg_log_warning, PQclear(), PQfnumber(), PQgetisnull(), PQgetvalue(), PQntuples(), printfPQExpBuffer(), res, resetPQExpBuffer(), role_catalog, and server_version.

Referenced by main().

◆ dumpTablespaces()

static void dumpTablespaces ( PGconn conn)
static

Definition at line 1251 of file pg_dumpall.c.

1252{
1253 PGresult *res;
1254 int i;
1255
1256 /*
1257 * Get all tablespaces except built-in ones (which we assume are named
1258 * pg_xxx)
1259 */
1260 res = executeQuery(conn, "SELECT oid, spcname, "
1261 "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1262 "pg_catalog.pg_tablespace_location(oid), "
1263 "spcacl, acldefault('t', spcowner) AS acldefault, "
1264 "array_to_string(spcoptions, ', '),"
1265 "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1266 "FROM pg_catalog.pg_tablespace "
1267 "WHERE spcname !~ '^pg_' "
1268 "ORDER BY 1");
1269
1270 if (PQntuples(res) > 0)
1271 fprintf(OPF, "--\n-- Tablespaces\n--\n\n");
1272
1273 for (i = 0; i < PQntuples(res); i++)
1274 {
1276 Oid spcoid = atooid(PQgetvalue(res, i, 0));
1277 char *spcname = PQgetvalue(res, i, 1);
1278 char *spcowner = PQgetvalue(res, i, 2);
1279 char *spclocation = PQgetvalue(res, i, 3);
1280 char *spcacl = PQgetvalue(res, i, 4);
1281 char *acldefault = PQgetvalue(res, i, 5);
1282 char *spcoptions = PQgetvalue(res, i, 6);
1283 char *spccomment = PQgetvalue(res, i, 7);
1284 char *fspcname;
1285
1286 /* needed for buildACLCommands() */
1287 fspcname = pg_strdup(fmtId(spcname));
1288
1289 if (binary_upgrade)
1290 {
1291 appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_tablespace oid\n");
1292 appendPQExpBuffer(buf, "SELECT pg_catalog.binary_upgrade_set_next_pg_tablespace_oid('%u'::pg_catalog.oid);\n", spcoid);
1293 }
1294
1295 appendPQExpBuffer(buf, "CREATE TABLESPACE %s", fspcname);
1296 appendPQExpBuffer(buf, " OWNER %s", fmtId(spcowner));
1297
1298 appendPQExpBufferStr(buf, " LOCATION ");
1299
1300 /*
1301 * In-place tablespaces use a relative path, and need to be dumped
1302 * with an empty string as location.
1303 */
1304 if (is_absolute_path(spclocation))
1305 appendStringLiteralConn(buf, spclocation, conn);
1306 else
1308
1309 appendPQExpBufferStr(buf, ";\n");
1310
1311 if (spcoptions && spcoptions[0] != '\0')
1312 appendPQExpBuffer(buf, "ALTER TABLESPACE %s SET (%s);\n",
1313 fspcname, spcoptions);
1314
1315 /* tablespaces can't have initprivs */
1316
1317 if (!skip_acls &&
1318 !buildACLCommands(fspcname, NULL, NULL, "TABLESPACE",
1319 spcacl, acldefault,
1320 spcowner, "", server_version, buf))
1321 {
1322 pg_log_error("could not parse ACL list (%s) for tablespace \"%s\"",
1323 spcacl, spcname);
1324 PQfinish(conn);
1325 exit_nicely(1);
1326 }
1327
1328 if (!no_comments && spccomment && spccomment[0] != '\0')
1329 {
1330 appendPQExpBuffer(buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
1331 appendStringLiteralConn(buf, spccomment, conn);
1332 appendPQExpBufferStr(buf, ";\n");
1333 }
1334
1335 if (!no_security_labels)
1336 buildShSecLabels(conn, "pg_tablespace", spcoid,
1337 "TABLESPACE", spcname,
1338 buf);
1339
1340 fprintf(OPF, "%s", buf->data);
1341
1342 free(fspcname);
1344 }
1345
1346 PQclear(res);
1347 fprintf(OPF, "\n\n");
1348}
static bool skip_acls
Definition: pg_dumpall.c:90
#define is_absolute_path(filename)
Definition: port.h:104

References acldefault(), appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), atooid, binary_upgrade, buf, buildACLCommands(), buildShSecLabels(), conn, createPQExpBuffer(), destroyPQExpBuffer(), executeQuery(), exit_nicely, fmtId(), fprintf, free, i, is_absolute_path, no_comments, no_security_labels, OPF, pg_log_error, pg_strdup(), PQclear(), PQfinish(), PQgetvalue(), PQntuples(), res, server_version, and skip_acls.

Referenced by main().

◆ dumpTimestamp()

static void dumpTimestamp ( const char *  msg)
static

Definition at line 1931 of file pg_dumpall.c.

1932{
1933 char buf[64];
1934 time_t now = time(NULL);
1935
1936 if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
1937 fprintf(OPF, "-- %s %s\n\n", msg, buf);
1938}
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1608
#define PGDUMP_STRFTIME_FMT
Definition: dumputils.h:33

References buf, fprintf, now(), OPF, and PGDUMP_STRFTIME_FMT.

Referenced by main().

◆ dumpUserConfig()

static void dumpUserConfig ( PGconn conn,
const char *  username 
)
static

Definition at line 1402 of file pg_dumpall.c.

1403{
1405 PGresult *res;
1406
1407 printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1408 "WHERE setdatabase = 0 AND setrole = "
1409 "(SELECT oid FROM %s WHERE rolname = ",
1410 role_catalog);
1413
1414 res = executeQuery(conn, buf->data);
1415
1416 if (PQntuples(res) > 0)
1417 fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", username);
1418
1419 for (int i = 0; i < PQntuples(res); i++)
1420 {
1423 "ROLE", username, NULL, NULL,
1424 buf);
1425 fprintf(OPF, "%s", buf->data);
1426 }
1427
1428 PQclear(res);
1429
1431}
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition: dumputils.c:823
static char * username
Definition: initdb.c:153

References appendPQExpBufferChar(), appendStringLiteralConn(), buf, conn, createPQExpBuffer(), destroyPQExpBuffer(), executeQuery(), fprintf, i, makeAlterConfigCommand(), OPF, PQclear(), PQgetvalue(), PQntuples(), printfPQExpBuffer(), res, resetPQExpBuffer(), role_catalog, and username.

Referenced by dumpRoles().

◆ executeCommand()

static void executeCommand ( PGconn conn,
const char *  query 
)
static

Definition at line 1907 of file pg_dumpall.c.

1908{
1909 PGresult *res;
1910
1911 pg_log_info("executing %s", query);
1912
1913 res = PQexec(conn, query);
1914 if (!res ||
1916 {
1917 pg_log_error("query failed: %s", PQerrorMessage(conn));
1918 pg_log_error_detail("Query was: %s", query);
1919 PQfinish(conn);
1920 exit_nicely(1);
1921 }
1922
1923 PQclear(res);
1924}
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:122

References conn, exit_nicely, pg_log_error, pg_log_error_detail, pg_log_info, PGRES_COMMAND_OK, PQclear(), PQerrorMessage(), PQexec(), PQfinish(), PQresultStatus(), and res.

Referenced by appendQualifiedRelation(), connect_slot(), main(), and vacuum_one_database().

◆ executeQuery()

◆ expand_dbname_patterns()

static void expand_dbname_patterns ( PGconn conn,
SimpleStringList patterns,
SimpleStringList names 
)
static

Definition at line 1438 of file pg_dumpall.c.

1441{
1442 PQExpBuffer query;
1443 PGresult *res;
1444
1445 if (patterns->head == NULL)
1446 return; /* nothing to do */
1447
1448 query = createPQExpBuffer();
1449
1450 /*
1451 * The loop below runs multiple SELECTs, which might sometimes result in
1452 * duplicate entries in the name list, but we don't care, since all we're
1453 * going to do is test membership of the list.
1454 */
1455
1456 for (SimpleStringListCell *cell = patterns->head; cell; cell = cell->next)
1457 {
1458 int dotcnt;
1459
1461 "SELECT datname FROM pg_catalog.pg_database n\n");
1462 processSQLNamePattern(conn, query, cell->val, false,
1463 false, NULL, "datname", NULL, NULL, NULL,
1464 &dotcnt);
1465
1466 if (dotcnt > 0)
1467 {
1468 pg_log_error("improper qualified name (too many dotted names): %s",
1469 cell->val);
1470 PQfinish(conn);
1471 exit_nicely(1);
1472 }
1473
1474 res = executeQuery(conn, query->data);
1475 for (int i = 0; i < PQntuples(res); i++)
1476 {
1478 }
1479
1480 PQclear(res);
1481 resetPQExpBuffer(query);
1482 }
1483
1484 destroyPQExpBuffer(query);
1485}
void simple_string_list_append(SimpleStringList *list, const char *val)
Definition: simple_list.c:63
bool processSQLNamePattern(PGconn *conn, PQExpBuffer buf, const char *pattern, bool have_where, bool force_escape, const char *schemavar, const char *namevar, const char *altnamevar, const char *visibilityrule, PQExpBuffer dbnamebuf, int *dotcnt)
struct SimpleStringListCell * next
Definition: simple_list.h:34
SimpleStringListCell * head
Definition: simple_list.h:42

References appendPQExpBufferStr(), conn, createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), executeQuery(), exit_nicely, SimpleStringList::head, i, SimpleStringListCell::next, pg_log_error, PQclear(), PQfinish(), PQgetvalue(), PQntuples(), processSQLNamePattern(), res, resetPQExpBuffer(), and simple_string_list_append().

Referenced by main().

◆ help()

static void help ( void  )
static

Definition at line 633 of file pg_dumpall.c.

634{
635 printf(_("%s extracts a PostgreSQL database cluster into an SQL script file.\n\n"), progname);
636 printf(_("Usage:\n"));
637 printf(_(" %s [OPTION]...\n"), progname);
638
639 printf(_("\nGeneral options:\n"));
640 printf(_(" -f, --file=FILENAME output file name\n"));
641 printf(_(" -v, --verbose verbose mode\n"));
642 printf(_(" -V, --version output version information, then exit\n"));
643 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
644 printf(_(" -?, --help show this help, then exit\n"));
645 printf(_("\nOptions controlling the output content:\n"));
646 printf(_(" -a, --data-only dump only the data, not the schema\n"));
647 printf(_(" -c, --clean clean (drop) databases before recreating\n"));
648 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
649 printf(_(" -g, --globals-only dump only global objects, no databases\n"));
650 printf(_(" -O, --no-owner skip restoration of object ownership\n"));
651 printf(_(" -r, --roles-only dump only roles, no databases or tablespaces\n"));
652 printf(_(" -s, --schema-only dump only the schema, no data\n"));
653 printf(_(" -S, --superuser=NAME superuser user name to use in the dump\n"));
654 printf(_(" -t, --tablespaces-only dump only tablespaces, no databases or roles\n"));
655 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
656 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
657 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
658 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
659 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
660 printf(_(" --exclude-database=PATTERN exclude databases whose name matches PATTERN\n"));
661 printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
662 printf(_(" --filter=FILENAME exclude databases based on expressions in FILENAME\n"));
663 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
664 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
665 printf(_(" --load-via-partition-root load partitions via the root table\n"));
666 printf(_(" --no-comments do not dump comment commands\n"));
667 printf(_(" --no-publications do not dump publications\n"));
668 printf(_(" --no-role-passwords do not dump passwords for roles\n"));
669 printf(_(" --no-security-labels do not dump security label assignments\n"));
670 printf(_(" --no-subscriptions do not dump subscriptions\n"));
671 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
672 printf(_(" --no-table-access-method do not dump table access methods\n"));
673 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
674 printf(_(" --no-toast-compression do not dump TOAST compression methods\n"));
675 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
676 printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
677 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
678 printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
679 printf(_(" --use-set-session-authorization\n"
680 " use SET SESSION AUTHORIZATION commands instead of\n"
681 " ALTER OWNER commands to set ownership\n"));
682
683 printf(_("\nConnection options:\n"));
684 printf(_(" -d, --dbname=CONNSTR connect using connection string\n"));
685 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
686 printf(_(" -l, --database=DBNAME alternative default database\n"));
687 printf(_(" -p, --port=PORT database server port number\n"));
688 printf(_(" -U, --username=NAME connect as specified database user\n"));
689 printf(_(" -w, --no-password never prompt for password\n"));
690 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
691 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
692
693 printf(_("\nIf -f/--file is not used, then the SQL script will be written to the standard\n"
694 "output.\n\n"));
695 printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
696 printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
697}
#define _(x)
Definition: elog.c:90
#define printf(...)
Definition: port.h:245

References _, printf, and progname.

Referenced by main().

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 127 of file pg_dumpall.c.

128{
129 static struct option long_options[] = {
130 {"data-only", no_argument, NULL, 'a'},
131 {"clean", no_argument, NULL, 'c'},
132 {"encoding", required_argument, NULL, 'E'},
133 {"file", required_argument, NULL, 'f'},
134 {"globals-only", no_argument, NULL, 'g'},
135 {"host", required_argument, NULL, 'h'},
136 {"dbname", required_argument, NULL, 'd'},
137 {"database", required_argument, NULL, 'l'},
138 {"no-owner", no_argument, NULL, 'O'},
139 {"port", required_argument, NULL, 'p'},
140 {"roles-only", no_argument, NULL, 'r'},
141 {"schema-only", no_argument, NULL, 's'},
142 {"superuser", required_argument, NULL, 'S'},
143 {"tablespaces-only", no_argument, NULL, 't'},
144 {"username", required_argument, NULL, 'U'},
145 {"verbose", no_argument, NULL, 'v'},
146 {"no-password", no_argument, NULL, 'w'},
147 {"password", no_argument, NULL, 'W'},
148 {"no-privileges", no_argument, NULL, 'x'},
149 {"no-acl", no_argument, NULL, 'x'},
150
151 /*
152 * the following options don't have an equivalent short option letter
153 */
154 {"attribute-inserts", no_argument, &column_inserts, 1},
155 {"binary-upgrade", no_argument, &binary_upgrade, 1},
156 {"column-inserts", no_argument, &column_inserts, 1},
157 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
158 {"disable-triggers", no_argument, &disable_triggers, 1},
159 {"exclude-database", required_argument, NULL, 6},
160 {"extra-float-digits", required_argument, NULL, 5},
161 {"if-exists", no_argument, &if_exists, 1},
162 {"inserts", no_argument, &inserts, 1},
163 {"lock-wait-timeout", required_argument, NULL, 2},
164 {"no-table-access-method", no_argument, &no_table_access_method, 1},
165 {"no-tablespaces", no_argument, &no_tablespaces, 1},
166 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
167 {"load-via-partition-root", no_argument, &load_via_partition_root, 1},
168 {"role", required_argument, NULL, 3},
169 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
170 {"no-comments", no_argument, &no_comments, 1},
171 {"no-publications", no_argument, &no_publications, 1},
172 {"no-role-passwords", no_argument, &no_role_passwords, 1},
173 {"no-security-labels", no_argument, &no_security_labels, 1},
174 {"no-subscriptions", no_argument, &no_subscriptions, 1},
175 {"no-sync", no_argument, NULL, 4},
176 {"no-toast-compression", no_argument, &no_toast_compression, 1},
177 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
178 {"on-conflict-do-nothing", no_argument, &on_conflict_do_nothing, 1},
179 {"rows-per-insert", required_argument, NULL, 7},
180 {"filter", required_argument, NULL, 8},
181
182 {NULL, 0, NULL, 0}
183 };
184
185 char *pghost = NULL;
186 char *pgport = NULL;
187 char *pguser = NULL;
188 char *pgdb = NULL;
189 char *use_role = NULL;
190 const char *dumpencoding = NULL;
191 trivalue prompt_password = TRI_DEFAULT;
192 bool data_only = false;
193 bool globals_only = false;
194 bool roles_only = false;
195 bool tablespaces_only = false;
196 PGconn *conn;
197 int encoding;
198 const char *std_strings;
199 int c,
200 ret;
201 int optindex;
202
203 pg_logging_init(argv[0]);
205 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
206 progname = get_progname(argv[0]);
207
208 if (argc > 1)
209 {
210 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
211 {
212 help();
213 exit_nicely(0);
214 }
215 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
216 {
217 puts("pg_dumpall (PostgreSQL) " PG_VERSION);
218 exit_nicely(0);
219 }
220 }
221
222 if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
223 pg_dump_bin)) < 0)
224 {
225 char full_path[MAXPGPATH];
226
227 if (find_my_exec(argv[0], full_path) < 0)
228 strlcpy(full_path, progname, sizeof(full_path));
229
230 if (ret == -1)
231 pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
232 "pg_dump", progname, full_path);
233 else
234 pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
235 "pg_dump", full_path, progname);
236 }
237
239
240 while ((c = getopt_long(argc, argv, "acd:E:f:gh:l:Op:rsS:tU:vwWx", long_options, &optindex)) != -1)
241 {
242 switch (c)
243 {
244 case 'a':
245 data_only = true;
247 break;
248
249 case 'c':
250 output_clean = true;
251 break;
252
253 case 'd':
255 break;
256
257 case 'E':
258 dumpencoding = pg_strdup(optarg);
261 break;
262
263 case 'f':
267 break;
268
269 case 'g':
270 globals_only = true;
271 break;
272
273 case 'h':
275 break;
276
277 case 'l':
278 pgdb = pg_strdup(optarg);
279 break;
280
281 case 'O':
283 break;
284
285 case 'p':
287 break;
288
289 case 'r':
290 roles_only = true;
291 break;
292
293 case 's':
295 break;
296
297 case 'S':
300 break;
301
302 case 't':
303 tablespaces_only = true;
304 break;
305
306 case 'U':
307 pguser = pg_strdup(optarg);
308 break;
309
310 case 'v':
311 verbose = true;
314 break;
315
316 case 'w':
317 prompt_password = TRI_NO;
319 break;
320
321 case 'W':
322 prompt_password = TRI_YES;
324 break;
325
326 case 'x':
327 skip_acls = true;
329 break;
330
331 case 0:
332 break;
333
334 case 2:
335 appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
337 break;
338
339 case 3:
340 use_role = pg_strdup(optarg);
341 appendPQExpBufferStr(pgdumpopts, " --role ");
342 appendShellString(pgdumpopts, use_role);
343 break;
344
345 case 4:
346 dosync = false;
347 appendPQExpBufferStr(pgdumpopts, " --no-sync");
348 break;
349
350 case 5:
351 appendPQExpBufferStr(pgdumpopts, " --extra-float-digits ");
353 break;
354
355 case 6:
357 break;
358
359 case 7:
360 appendPQExpBufferStr(pgdumpopts, " --rows-per-insert ");
362 break;
363
364 case 8:
366 break;
367
368 default:
369 /* getopt_long already emitted a complaint */
370 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
371 exit_nicely(1);
372 }
373 }
374
375 /* Complain if any arguments remain */
376 if (optind < argc)
377 {
378 pg_log_error("too many command-line arguments (first is \"%s\")",
379 argv[optind]);
380 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
381 exit_nicely(1);
382 }
383
384 if (database_exclude_patterns.head != NULL &&
385 (globals_only || roles_only || tablespaces_only))
386 {
387 pg_log_error("option --exclude-database cannot be used together with -g/--globals-only, -r/--roles-only, or -t/--tablespaces-only");
388 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
389 exit_nicely(1);
390 }
391
392 /* Make sure the user hasn't specified a mix of globals-only options */
393 if (globals_only && roles_only)
394 {
395 pg_log_error("options -g/--globals-only and -r/--roles-only cannot be used together");
396 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
397 exit_nicely(1);
398 }
399
400 if (globals_only && tablespaces_only)
401 {
402 pg_log_error("options -g/--globals-only and -t/--tablespaces-only cannot be used together");
403 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
404 exit_nicely(1);
405 }
406
407 if (if_exists && !output_clean)
408 pg_fatal("option --if-exists requires option -c/--clean");
409
410 if (roles_only && tablespaces_only)
411 {
412 pg_log_error("options -r/--roles-only and -t/--tablespaces-only cannot be used together");
413 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
414 exit_nicely(1);
415 }
416
417 /*
418 * If password values are not required in the dump, switch to using
419 * pg_roles which is equally useful, just more likely to have unrestricted
420 * access than pg_authid.
421 */
424 else
426
427 /* Add long options to the pg_dump argument list */
428 if (binary_upgrade)
429 appendPQExpBufferStr(pgdumpopts, " --binary-upgrade");
430 if (column_inserts)
431 appendPQExpBufferStr(pgdumpopts, " --column-inserts");
433 appendPQExpBufferStr(pgdumpopts, " --disable-dollar-quoting");
435 appendPQExpBufferStr(pgdumpopts, " --disable-triggers");
436 if (inserts)
437 appendPQExpBufferStr(pgdumpopts, " --inserts");
439 appendPQExpBufferStr(pgdumpopts, " --no-table-access-method");
440 if (no_tablespaces)
441 appendPQExpBufferStr(pgdumpopts, " --no-tablespaces");
443 appendPQExpBufferStr(pgdumpopts, " --quote-all-identifiers");
445 appendPQExpBufferStr(pgdumpopts, " --load-via-partition-root");
446 if (use_setsessauth)
447 appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
448 if (no_comments)
449 appendPQExpBufferStr(pgdumpopts, " --no-comments");
450 if (no_publications)
451 appendPQExpBufferStr(pgdumpopts, " --no-publications");
453 appendPQExpBufferStr(pgdumpopts, " --no-security-labels");
455 appendPQExpBufferStr(pgdumpopts, " --no-subscriptions");
457 appendPQExpBufferStr(pgdumpopts, " --no-toast-compression");
459 appendPQExpBufferStr(pgdumpopts, " --no-unlogged-table-data");
461 appendPQExpBufferStr(pgdumpopts, " --on-conflict-do-nothing");
462
463 /*
464 * If there was a database specified on the command line, use that,
465 * otherwise try to connect to database "postgres", and failing that
466 * "template1".
467 */
468 if (pgdb)
469 {
470 conn = connectDatabase(pgdb, connstr, pghost, pgport, pguser,
471 prompt_password, false);
472
473 if (!conn)
474 pg_fatal("could not connect to database \"%s\"", pgdb);
475 }
476 else
477 {
478 conn = connectDatabase("postgres", connstr, pghost, pgport, pguser,
479 prompt_password, false);
480 if (!conn)
481 conn = connectDatabase("template1", connstr, pghost, pgport, pguser,
482 prompt_password, true);
483
484 if (!conn)
485 {
486 pg_log_error("could not connect to databases \"postgres\" or \"template1\"\n"
487 "Please specify an alternative database.");
488 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
489 exit_nicely(1);
490 }
491 }
492
493 /*
494 * Get a list of database names that match the exclude patterns
495 */
498
499 /*
500 * Open the output file if required, otherwise use stdout
501 */
502 if (filename)
503 {
504 OPF = fopen(filename, PG_BINARY_W);
505 if (!OPF)
506 pg_fatal("could not open output file \"%s\": %m",
507 filename);
508 }
509 else
510 OPF = stdout;
511
512 /*
513 * Set the client encoding if requested.
514 */
515 if (dumpencoding)
516 {
517 if (PQsetClientEncoding(conn, dumpencoding) < 0)
518 pg_fatal("invalid client encoding \"%s\" specified",
519 dumpencoding);
520 }
521
522 /*
523 * Get the active encoding and the standard_conforming_strings setting, so
524 * we know how to escape strings.
525 */
528 std_strings = PQparameterStatus(conn, "standard_conforming_strings");
529 if (!std_strings)
530 std_strings = "off";
531
532 /* Set the role if requested */
533 if (use_role)
534 {
536
537 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
538 executeCommand(conn, query->data);
539 destroyPQExpBuffer(query);
540 }
541
542 /* Force quoting of all identifiers if requested. */
544 executeCommand(conn, "SET quote_all_identifiers = true");
545
546 fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
547 if (verbose)
548 dumpTimestamp("Started on");
549
550 /*
551 * We used to emit \connect postgres here, but that served no purpose
552 * other than to break things for installations without a postgres
553 * database. Everything we're restoring here is a global, so whichever
554 * database we're connected to at the moment is fine.
555 */
556
557 /* Restore will need to write to the target cluster */
558 fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
559
560 /* Replicate encoding and std_strings in output */
561 fprintf(OPF, "SET client_encoding = '%s';\n",
563 fprintf(OPF, "SET standard_conforming_strings = %s;\n", std_strings);
564 if (strcmp(std_strings, "off") == 0)
565 fprintf(OPF, "SET escape_string_warning = off;\n");
566 fprintf(OPF, "\n");
567
568 if (!data_only)
569 {
570 /*
571 * If asked to --clean, do that first. We can avoid detailed
572 * dependency analysis because databases never depend on each other,
573 * and tablespaces never depend on each other. Roles could have
574 * grants to each other, but DROP ROLE will clean those up silently.
575 */
576 if (output_clean)
577 {
578 if (!globals_only && !roles_only && !tablespaces_only)
579 dropDBs(conn);
580
581 if (!roles_only && !no_tablespaces)
583
584 if (!tablespaces_only)
586 }
587
588 /*
589 * Now create objects as requested. Be careful that option logic here
590 * is the same as for drops above.
591 */
592 if (!tablespaces_only)
593 {
594 /* Dump roles (users) */
596
597 /* Dump role memberships */
599
600 /* Dump role GUC privileges */
601 if (server_version >= 150000 && !skip_acls)
603 }
604
605 /* Dump tablespaces */
606 if (!roles_only && !no_tablespaces)
608 }
609
610 if (!globals_only && !roles_only && !tablespaces_only)
612
613 PQfinish(conn);
614
615 if (verbose)
616 dumpTimestamp("Completed on");
617 fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
618
619 if (filename)
620 {
621 fclose(OPF);
622
623 /* sync the resulting file, errors are not fatal */
624 if (dosync)
625 (void) fsync_fname(filename, false);
626 }
627
628 exit_nicely(0);
629}
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1171
#define PG_BINARY_W
Definition: c.h:1233
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:429
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:310
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:755
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7597
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7605
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:60
#define no_argument
Definition: getopt_long.h:25
#define required_argument
Definition: getopt_long.h:26
void pg_logging_increase_verbosity(void)
Definition: logging.c:185
void pg_logging_init(const char *argv0)
Definition: logging.c:83
void pg_logging_set_level(enum pg_log_level new_level)
Definition: logging.c:176
#define pg_log_error_hint(...)
Definition: logging.h:112
@ PG_LOG_WARNING
Definition: logging.h:38
#define MAXPGPATH
int32 encoding
Definition: pg_database.h:41
static void dumpTimestamp(const char *msg)
Definition: pg_dumpall.c:1931
static int on_conflict_do_nothing
Definition: pg_dumpall.c:112
static void dropTablespaces(PGconn *conn)
Definition: pg_dumpall.c:1216
static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
Definition: pg_dumpall.c:1438
static PQExpBuffer pgdumpopts
Definition: pg_dumpall.c:87
static int no_table_access_method
Definition: pg_dumpall.c:100
static int no_unlogged_table_data
Definition: pg_dumpall.c:108
#define PG_AUTHID
Definition: pg_dumpall.c:115
static int disable_triggers
Definition: pg_dumpall.c:97
static bool dosync
Definition: pg_dumpall.c:92
static SimpleStringList database_exclude_patterns
Definition: pg_dumpall.c:121
static void dumpTablespaces(PGconn *conn)
Definition: pg_dumpall.c:1251
static void dumpRoleMembership(PGconn *conn)
Definition: pg_dumpall.c:959
static PGconn * connectDatabase(const char *dbname, const char *connection_string, const char *pghost, const char *pgport, const char *pguser, trivalue prompt_password, bool fail_on_error)
Definition: pg_dumpall.c:1664
static char pg_dump_bin[MAXPGPATH]
Definition: pg_dumpall.c:85
static int no_publications
Definition: pg_dumpall.c:104
static void dumpDatabases(PGconn *conn)
Definition: pg_dumpall.c:1491
static int disable_dollar_quoting
Definition: pg_dumpall.c:96
static int no_tablespaces
Definition: pg_dumpall.c:101
static int no_toast_compression
Definition: pg_dumpall.c:107
#define PG_ROLES
Definition: pg_dumpall.c:116
static int inserts
Definition: pg_dumpall.c:99
static void executeCommand(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1907
static bool verbose
Definition: pg_dumpall.c:91
static void dumpRoleGUCPrivs(PGconn *conn)
Definition: pg_dumpall.c:1161
static void dumpRoles(PGconn *conn)
Definition: pg_dumpall.c:751
static void help(void)
Definition: pg_dumpall.c:633
static int use_setsessauth
Definition: pg_dumpall.c:102
static int load_via_partition_root
Definition: pg_dumpall.c:111
static int column_inserts
Definition: pg_dumpall.c:95
static void read_dumpall_filters(const char *filename, SimpleStringList *pattern)
Definition: pg_dumpall.c:1950
static void dropRoles(PGconn *conn)
Definition: pg_dumpall.c:704
static void dropDBs(PGconn *conn)
Definition: pg_dumpall.c:1355
static int no_subscriptions
Definition: pg_dumpall.c:106
#define PGDUMP_VERSIONSTR
Definition: pg_dumpall.c:34
PGDLLIMPORT int optind
Definition: getopt.c:51
PGDLLIMPORT char * optarg
Definition: getopt.c:53
#define pg_encoding_to_char
Definition: pg_wchar.h:630
#define sprintf
Definition: port.h:241
const char * get_progname(const char *argv0)
Definition: path.c:652
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * c
bool quote_all_identifiers
Definition: ruleutils.c:339
void setFmtEncoding(int encoding)
Definition: string_utils.c:69
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:603
trivalue
Definition: vacuumlo.c:35
@ TRI_DEFAULT
Definition: vacuumlo.c:36

References appendPQExpBuffer(), appendPQExpBufferStr(), appendShellString(), binary_upgrade, column_inserts, conn, connectDatabase(), connstr, createPQExpBuffer(), PQExpBufferData::data, database_exclude_names, database_exclude_patterns, destroyPQExpBuffer(), disable_dollar_quoting, disable_triggers, dosync, dropDBs(), dropRoles(), dropTablespaces(), dumpDatabases(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpTablespaces(), dumpTimestamp(), encoding, executeCommand(), exit_nicely, expand_dbname_patterns(), filename, find_my_exec(), find_other_exec(), fmtId(), fprintf, fsync_fname(), get_progname(), getopt_long(), SimpleStringList::head, help(), if_exists, inserts, load_via_partition_root, MAXPGPATH, no_argument, no_comments, no_publications, no_role_passwords, no_security_labels, no_subscriptions, no_table_access_method, no_tablespaces, no_toast_compression, no_unlogged_table_data, on_conflict_do_nothing, OPF, optarg, optind, output_clean, PG_AUTHID, PG_BINARY_W, pg_dump_bin, pg_encoding_to_char, pg_fatal, pg_log_error, pg_log_error_hint, PG_LOG_WARNING, pg_logging_increase_verbosity(), pg_logging_init(), pg_logging_set_level(), PG_ROLES, pg_strdup(), PG_TEXTDOMAIN, PGDUMP_VERSIONSTR, pgdumpopts, pghost, pgport, PQclientEncoding(), PQfinish(), PQparameterStatus(), PQsetClientEncoding(), progname, quote_all_identifiers, read_dumpall_filters(), required_argument, role_catalog, server_version, set_pglocale_pgservice(), setFmtEncoding(), simple_string_list_append(), skip_acls, sprintf, generate_unaccent_rules::stdout, strlcpy(), TRI_DEFAULT, TRI_NO, TRI_YES, use_setsessauth, and verbose.

◆ read_dumpall_filters()

static void read_dumpall_filters ( const char *  filename,
SimpleStringList pattern 
)
static

Definition at line 1950 of file pg_dumpall.c.

1951{
1952 FilterStateData fstate;
1953 char *objname;
1954 FilterCommandType comtype;
1955 FilterObjectType objtype;
1956
1957 filter_init(&fstate, filename, exit);
1958
1959 while (filter_read_item(&fstate, &objname, &comtype, &objtype))
1960 {
1961 if (comtype == FILTER_COMMAND_TYPE_INCLUDE)
1962 {
1963 pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
1964 "include",
1965 filter_object_type_name(objtype));
1966 exit_nicely(1);
1967 }
1968
1969 switch (objtype)
1970 {
1972 break;
1983 pg_log_filter_error(&fstate, _("unsupported filter object"));
1984 exit_nicely(1);
1985 break;
1986
1988 simple_string_list_append(pattern, objname);
1989 break;
1990 }
1991
1992 if (objname)
1993 free(objname);
1994 }
1995
1996 filter_free(&fstate);
1997}
void filter_init(FilterStateData *fstate, const char *filename, exit_function f_exit)
Definition: filter.c:36
void filter_free(FilterStateData *fstate)
Definition: filter.c:60
const char * filter_object_type_name(FilterObjectType fot)
Definition: filter.c:82
bool filter_read_item(FilterStateData *fstate, char **objname, FilterCommandType *comtype, FilterObjectType *objtype)
Definition: filter.c:389
void pg_log_filter_error(FilterStateData *fstate, const char *fmt,...)
Definition: filter.c:154
FilterObjectType
Definition: filter.h:48
@ FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN
Definition: filter.h:51
@ FILTER_OBJECT_TYPE_SCHEMA
Definition: filter.h:57
@ FILTER_OBJECT_TYPE_INDEX
Definition: filter.h:56
@ FILTER_OBJECT_TYPE_TRIGGER
Definition: filter.h:60
@ FILTER_OBJECT_TYPE_FOREIGN_DATA
Definition: filter.h:54
@ FILTER_OBJECT_TYPE_DATABASE
Definition: filter.h:52
@ FILTER_OBJECT_TYPE_FUNCTION
Definition: filter.h:55
@ FILTER_OBJECT_TYPE_TABLE_DATA
Definition: filter.h:50
@ FILTER_OBJECT_TYPE_NONE
Definition: filter.h:49
@ FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN
Definition: filter.h:59
@ FILTER_OBJECT_TYPE_EXTENSION
Definition: filter.h:53
@ FILTER_OBJECT_TYPE_TABLE
Definition: filter.h:58
FilterCommandType
Definition: filter.h:38
@ FILTER_COMMAND_TYPE_INCLUDE
Definition: filter.h:40
exit(1)

References _, exit(), exit_nicely, filename, FILTER_COMMAND_TYPE_INCLUDE, filter_free(), filter_init(), FILTER_OBJECT_TYPE_DATABASE, FILTER_OBJECT_TYPE_EXTENSION, FILTER_OBJECT_TYPE_FOREIGN_DATA, FILTER_OBJECT_TYPE_FUNCTION, FILTER_OBJECT_TYPE_INDEX, filter_object_type_name(), FILTER_OBJECT_TYPE_NONE, FILTER_OBJECT_TYPE_SCHEMA, FILTER_OBJECT_TYPE_TABLE, FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN, FILTER_OBJECT_TYPE_TABLE_DATA, FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN, FILTER_OBJECT_TYPE_TRIGGER, filter_read_item(), free, pg_log_filter_error(), and simple_string_list_append().

Referenced by main().

◆ runPgDump()

static int runPgDump ( const char *  dbname,
const char *  create_opts 
)
static

Definition at line 1584 of file pg_dumpall.c.

1585{
1586 PQExpBufferData connstrbuf;
1587 PQExpBufferData cmd;
1588 int ret;
1589
1590 initPQExpBuffer(&connstrbuf);
1591 initPQExpBuffer(&cmd);
1592
1593 printfPQExpBuffer(&cmd, "\"%s\" %s %s", pg_dump_bin,
1594 pgdumpopts->data, create_opts);
1595
1596 /*
1597 * If we have a filename, use the undocumented plain-append pg_dump
1598 * format.
1599 */
1600 if (filename)
1601 appendPQExpBufferStr(&cmd, " -Fa ");
1602 else
1603 appendPQExpBufferStr(&cmd, " -Fp ");
1604
1605 /*
1606 * Append the database name to the already-constructed stem of connection
1607 * string.
1608 */
1609 appendPQExpBuffer(&connstrbuf, "%s dbname=", connstr);
1610 appendConnStrVal(&connstrbuf, dbname);
1611
1612 appendShellString(&cmd, connstrbuf.data);
1613
1614 pg_log_info("running \"%s\"", cmd.data);
1615
1616 fflush(NULL);
1617
1618 ret = system(cmd.data);
1619
1620 termPQExpBuffer(&cmd);
1621 termPQExpBuffer(&connstrbuf);
1622
1623 return ret;
1624}
static void const char fflush(stdout)
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129

References appendConnStrVal(), appendPQExpBuffer(), appendPQExpBufferStr(), appendShellString(), connstr, PQExpBufferData::data, dbname, fflush(), filename, initPQExpBuffer(), pg_dump_bin, pg_log_info, pgdumpopts, printfPQExpBuffer(), and termPQExpBuffer().

Referenced by dumpDatabases().

Variable Documentation

◆ binary_upgrade

int binary_upgrade = 0
static

Definition at line 94 of file pg_dumpall.c.

Referenced by dumpRoles(), dumpTablespaces(), and main().

◆ column_inserts

int column_inserts = 0
static

Definition at line 95 of file pg_dumpall.c.

Referenced by main().

◆ connstr

◆ database_exclude_names

SimpleStringList database_exclude_names = {NULL, NULL}
static

Definition at line 122 of file pg_dumpall.c.

Referenced by dumpDatabases(), and main().

◆ database_exclude_patterns

SimpleStringList database_exclude_patterns = {NULL, NULL}
static

Definition at line 121 of file pg_dumpall.c.

Referenced by main().

◆ disable_dollar_quoting

int disable_dollar_quoting = 0
static

Definition at line 96 of file pg_dumpall.c.

Referenced by main().

◆ disable_triggers

int disable_triggers = 0
static

Definition at line 97 of file pg_dumpall.c.

Referenced by main().

◆ dosync

bool dosync = true
static

Definition at line 92 of file pg_dumpall.c.

Referenced by main().

◆ filename

char* filename = NULL
static

Definition at line 119 of file pg_dumpall.c.

Referenced by _fileExistsInDirectory(), _PrintFileData(), _tarPositionTo(), _tarWriteHeader(), adjust_data_dir(), BaseBackup(), basebackup_read_file(), bbsink_server_begin_archive(), bbsink_server_end_manifest(), be_lo_export(), be_lo_import(), be_lo_import_with_oid(), BeginCopyFrom(), BeginCopyTo(), check_file_excluded(), CheckXLogRemoved(), convert_and_check_filename(), create_file_for_extract(), CreateExtensionInternal(), CreateLockFile(), db_dir_size(), dir_close(), dir_get_file_name(), dir_open_for_write(), dsynonym_init(), dumpDatabases(), dxsyn_init(), ecpg_postprocess_result(), errfinish(), errsave_finish(), execute_extension_script(), execute_sql_string(), expand_tilde(), exportFile(), extract_directory(), extract_link(), file_acquire_sample_rows(), file_fdw_validator(), fileAnalyzeForeignTable(), fileBeginForeignScan(), fileExplainForeignScan(), fileGetOptions(), fill_hba_line(), fill_ident_line(), filter_init(), first_dir_separator(), get_sock_dir(), GetConfFilesInDir(), hasSuffix(), importFile(), initTrie(), internal_load_library(), is_extension_control_filename(), is_extension_script_filename(), is_xlogfilename(), IsWalSummaryFilename(), last_dir_separator(), libpqrcv_readtimelinehistoryfile(), llvm_compile_module(), lo_export(), lo_import(), lo_import_internal(), lo_import_with_oid(), load_dh_file(), load_external_function(), load_file(), load_libraries(), load_tzoffsets(), log_locus_callback(), logfile_getname(), logfile_open(), logfile_rotate_dest(), LogicalTapeImport(), LogicalTapeSetCreate(), main(), make_incremental_rfile(), make_native_path(), make_outputdirs(), make_rfile(), next_field_expand(), NIImportAffixes(), NIImportDictionary(), NIImportOOAffixes(), open_auth_file(), parse_backup_label(), parse_extension_control_file(), parseIntFromText(), ParseTzFile(), parseVxidFromText(), parseXidFromText(), pg_log_generic_v(), pg_stat_file(), PLy_traceback(), process_file(), process_psqlrc_file(), process_queued_fetch_requests(), progress_update_filename(), read_binary_file(), read_dictionary(), read_dump_filters(), read_dumpall_filters(), read_extension_script_file(), read_pg_version_file(), read_restore_filters(), read_text_file(), read_whole_file(), readstoplist(), reconstruct_from_incremental_file(), regcomp_auth_token(), run_diff(), runPgDump(), sendFileWithContent(), set_input(), set_stack_entry_location(), SetOutput(), setup_run_file(), shell_construct_command(), shell_run_command(), should_allow_existing_directory(), slurp_file(), splitTzLine(), SysLogger_Start(), tar_get_file_name(), tarCreateHeader(), tarOpen(), test_slru_scan_cb(), thesaurusRead(), tokenize_auth_file(), TrimExtension(), tsearch_readline_begin(), UpdateLastRemovedPtr(), verify_plain_backup_directory(), verify_tar_backup(), write_auto_conf_file(), WriteRecoveryConfig(), writeTimeLineHistoryFile(), and XLogRecordSaveFPWs().

◆ if_exists

int if_exists = 0
static

Definition at line 98 of file pg_dumpall.c.

Referenced by dropDBs(), dropRoles(), dropTablespaces(), and main().

◆ inserts

int inserts = 0
static

Definition at line 99 of file pg_dumpall.c.

Referenced by main().

◆ load_via_partition_root

int load_via_partition_root = 0
static

Definition at line 111 of file pg_dumpall.c.

Referenced by main().

◆ no_comments

int no_comments = 0
static

Definition at line 103 of file pg_dumpall.c.

Referenced by dumpRoles(), dumpTablespaces(), and main().

◆ no_publications

int no_publications = 0
static

Definition at line 104 of file pg_dumpall.c.

Referenced by main().

◆ no_role_passwords

int no_role_passwords = 0
static

Definition at line 109 of file pg_dumpall.c.

Referenced by dumpRoles(), and main().

◆ no_security_labels

int no_security_labels = 0
static

Definition at line 105 of file pg_dumpall.c.

Referenced by dumpRoles(), dumpTablespaces(), and main().

◆ no_subscriptions

int no_subscriptions = 0
static

Definition at line 106 of file pg_dumpall.c.

Referenced by main().

◆ no_table_access_method

int no_table_access_method = 0
static

Definition at line 100 of file pg_dumpall.c.

Referenced by main().

◆ no_tablespaces

int no_tablespaces = 0
static

Definition at line 101 of file pg_dumpall.c.

Referenced by main().

◆ no_toast_compression

int no_toast_compression = 0
static

Definition at line 107 of file pg_dumpall.c.

Referenced by main().

◆ no_unlogged_table_data

int no_unlogged_table_data = 0
static

Definition at line 108 of file pg_dumpall.c.

Referenced by main().

◆ on_conflict_do_nothing

int on_conflict_do_nothing = 0
static

Definition at line 112 of file pg_dumpall.c.

Referenced by main().

◆ OPF

◆ output_clean

bool output_clean = false
static

Definition at line 89 of file pg_dumpall.c.

Referenced by dumpDatabases(), and main().

◆ pg_dump_bin

char pg_dump_bin[MAXPGPATH]
static

Definition at line 85 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ pgdumpopts

PQExpBuffer pgdumpopts
static

Definition at line 87 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ progname

const char* progname
static

Definition at line 86 of file pg_dumpall.c.

Referenced by connectDatabase(), help(), and main().

◆ role_catalog

char role_catalog[10]
static

Definition at line 114 of file pg_dumpall.c.

Referenced by dropRoles(), dumpRoleMembership(), dumpRoles(), dumpUserConfig(), and main().

◆ server_version

◆ skip_acls

bool skip_acls = false
static

Definition at line 90 of file pg_dumpall.c.

Referenced by dumpTablespaces(), and main().

◆ use_setsessauth

int use_setsessauth = 0
static

Definition at line 102 of file pg_dumpall.c.

Referenced by main().

◆ verbose

bool verbose = false
static

Definition at line 91 of file pg_dumpall.c.

Referenced by main().