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.h"
#include "common/logging.h"
#include "common/string.h"
#include "dumputils.h"
#include "fe_utils/string_utils.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_pointer(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 uint32 hash_string_pointer (char *s)
 
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)
 
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 33 of file pg_dumpall.c.

◆ SH_DECLARE

#define SH_DECLARE

Definition at line 54 of file pg_dumpall.c.

◆ SH_DEFINE

#define SH_DEFINE

Definition at line 55 of file pg_dumpall.c.

◆ SH_ELEMENT_TYPE

#define SH_ELEMENT_TYPE   RoleNameEntry

Definition at line 45 of file pg_dumpall.c.

◆ SH_EQUAL

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

Definition at line 49 of file pg_dumpall.c.

◆ SH_GET_HASH

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

Definition at line 51 of file pg_dumpall.c.

◆ SH_HASH_KEY

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

Definition at line 48 of file pg_dumpall.c.

◆ SH_KEY

#define SH_KEY   rolename

Definition at line 47 of file pg_dumpall.c.

◆ SH_KEY_TYPE

#define SH_KEY_TYPE   char *

Definition at line 46 of file pg_dumpall.c.

◆ SH_PREFIX

#define SH_PREFIX   rolename

Definition at line 44 of file pg_dumpall.c.

◆ SH_RAW_ALLOCATOR

#define SH_RAW_ALLOCATOR   pg_malloc0

Definition at line 53 of file pg_dumpall.c.

◆ SH_SCOPE

#define SH_SCOPE   static inline

Definition at line 52 of file pg_dumpall.c.

◆ SH_STORE_HASH

#define SH_STORE_HASH

Definition at line 50 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 1615 of file pg_dumpall.c.

1618 {
1620  PGresult *res;
1621 
1622  buildShSecLabelQuery(catalog_name, objectId, sql);
1623  res = executeQuery(conn, sql->data);
1624  emitShSecLabels(conn, res, buffer, objtype, objname);
1625 
1626  PQclear(res);
1627  destroyPQExpBuffer(sql);
1628 }
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition: dumputils.c:630
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition: dumputils.c:648
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1861
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
PGconn * conn
Definition: streamutil.c:54

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 1641 of file pg_dumpall.c.

1644 {
1645  PGconn *conn;
1646  bool new_pass;
1647  const char *remoteversion_str;
1648  int my_version;
1649  const char **keywords = NULL;
1650  const char **values = NULL;
1651  PQconninfoOption *conn_opts = NULL;
1652  static char *password = NULL;
1653 
1654  if (prompt_password == TRI_YES && !password)
1655  password = simple_prompt("Password: ", false);
1656 
1657  /*
1658  * Start the connection. Loop until we have a password if requested by
1659  * backend.
1660  */
1661  do
1662  {
1663  int argcount = 6;
1664  PQconninfoOption *conn_opt;
1665  char *err_msg = NULL;
1666  int i = 0;
1667 
1668  free(keywords);
1669  free(values);
1670  PQconninfoFree(conn_opts);
1671 
1672  /*
1673  * Merge the connection info inputs given in form of connection string
1674  * and other options. Explicitly discard any dbname value in the
1675  * connection string; otherwise, PQconnectdbParams() would interpret
1676  * that value as being itself a connection string.
1677  */
1678  if (connection_string)
1679  {
1680  conn_opts = PQconninfoParse(connection_string, &err_msg);
1681  if (conn_opts == NULL)
1682  pg_fatal("%s", err_msg);
1683 
1684  for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1685  {
1686  if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1687  strcmp(conn_opt->keyword, "dbname") != 0)
1688  argcount++;
1689  }
1690 
1691  keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1692  values = pg_malloc0((argcount + 1) * sizeof(*values));
1693 
1694  for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1695  {
1696  if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1697  strcmp(conn_opt->keyword, "dbname") != 0)
1698  {
1699  keywords[i] = conn_opt->keyword;
1700  values[i] = conn_opt->val;
1701  i++;
1702  }
1703  }
1704  }
1705  else
1706  {
1707  keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1708  values = pg_malloc0((argcount + 1) * sizeof(*values));
1709  }
1710 
1711  if (pghost)
1712  {
1713  keywords[i] = "host";
1714  values[i] = pghost;
1715  i++;
1716  }
1717  if (pgport)
1718  {
1719  keywords[i] = "port";
1720  values[i] = pgport;
1721  i++;
1722  }
1723  if (pguser)
1724  {
1725  keywords[i] = "user";
1726  values[i] = pguser;
1727  i++;
1728  }
1729  if (password)
1730  {
1731  keywords[i] = "password";
1732  values[i] = password;
1733  i++;
1734  }
1735  if (dbname)
1736  {
1737  keywords[i] = "dbname";
1738  values[i] = dbname;
1739  i++;
1740  }
1741  keywords[i] = "fallback_application_name";
1742  values[i] = progname;
1743  i++;
1744 
1745  new_pass = false;
1746  conn = PQconnectdbParams(keywords, values, true);
1747 
1748  if (!conn)
1749  pg_fatal("could not connect to database \"%s\"", dbname);
1750 
1751  if (PQstatus(conn) == CONNECTION_BAD &&
1753  !password &&
1754  prompt_password != TRI_NO)
1755  {
1756  PQfinish(conn);
1757  password = simple_prompt("Password: ", false);
1758  new_pass = true;
1759  }
1760  } while (new_pass);
1761 
1762  /* check to see that the backend connection was successfully made */
1763  if (PQstatus(conn) == CONNECTION_BAD)
1764  {
1765  if (fail_on_error)
1766  pg_fatal("%s", PQerrorMessage(conn));
1767  else
1768  {
1769  PQfinish(conn);
1770 
1771  free(keywords);
1772  free(values);
1773  PQconninfoFree(conn_opts);
1774 
1775  return NULL;
1776  }
1777  }
1778 
1779  /*
1780  * Ok, connected successfully. Remember the options used, in the form of a
1781  * connection string.
1782  */
1783  connstr = constructConnStr(keywords, values);
1784 
1785  free(keywords);
1786  free(values);
1787  PQconninfoFree(conn_opts);
1788 
1789  /* Check version */
1790  remoteversion_str = PQparameterStatus(conn, "server_version");
1791  if (!remoteversion_str)
1792  pg_fatal("could not get server version");
1794  if (server_version == 0)
1795  pg_fatal("could not parse server version \"%s\"",
1796  remoteversion_str);
1797 
1798  my_version = PG_VERSION_NUM;
1799 
1800  /*
1801  * We allow the server to be back to 9.2, and up to any minor release of
1802  * our own major version. (See also version check in pg_dump.c.)
1803  */
1804  if (my_version != server_version
1805  && (server_version < 90200 ||
1806  (server_version / 100) > (my_version / 100)))
1807  {
1808  pg_log_error("aborting because of server version mismatch");
1809  pg_log_error_detail("server version: %s; %s version: %s",
1810  remoteversion_str, progname, PG_VERSION);
1811  exit_nicely(1);
1812  }
1813 
1815 
1816  return conn;
1817 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition: connect.h:25
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6708
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6733
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5357
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:652
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6576
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6794
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6743
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6690
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4130
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:73
@ CONNECTION_BAD
Definition: libpq-fe.h:61
#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:1830
static int server_version
Definition: pg_dumpall.c:110
static const char * progname
Definition: pg_dumpall.c:86
const char * pghost
Definition: pgbench.c:303
const char * pgport
Definition: pgbench.c:304
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
static char * password
Definition: streamutil.c:53
char * connection_string
Definition: streamutil.c:47
char * dbname
Definition: streamutil.c:51
@ 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, 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 1830 of file pg_dumpall.c.

1831 {
1833  char *connstr;
1834  int i;
1835  bool firstkeyword = true;
1836 
1837  /* Construct a new connection string in key='value' format. */
1838  for (i = 0; keywords[i] != NULL; i++)
1839  {
1840  if (strcmp(keywords[i], "dbname") == 0 ||
1841  strcmp(keywords[i], "password") == 0 ||
1842  strcmp(keywords[i], "fallback_application_name") == 0)
1843  continue;
1844 
1845  if (!firstkeyword)
1846  appendPQExpBufferChar(buf, ' ');
1847  firstkeyword = false;
1848  appendPQExpBuffer(buf, "%s=", keywords[i]);
1850  }
1851 
1852  connstr = pg_strdup(buf->data);
1854  return connstr;
1855 }
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * buf
Definition: pg_test_fsync.c:67
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:545

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

Referenced by connectDatabase().

◆ dropDBs()

static void dropDBs ( PGconn conn)
static

Definition at line 1335 of file pg_dumpall.c.

1336 {
1337  PGresult *res;
1338  int i;
1339 
1340  /*
1341  * Skip databases marked not datallowconn, since we'd be unable to connect
1342  * to them anyway. This must agree with dumpDatabases().
1343  */
1344  res = executeQuery(conn,
1345  "SELECT datname "
1346  "FROM pg_database d "
1347  "WHERE datallowconn "
1348  "ORDER BY datname");
1349 
1350  if (PQntuples(res) > 0)
1351  fprintf(OPF, "--\n-- Drop databases (except postgres and template1)\n--\n\n");
1352 
1353  for (i = 0; i < PQntuples(res); i++)
1354  {
1355  char *dbname = PQgetvalue(res, i, 0);
1356 
1357  /*
1358  * Skip "postgres" and "template1"; dumpDatabases() will deal with
1359  * them specially. Also, be sure to skip "template0", even if for
1360  * some reason it's not marked !datallowconn.
1361  */
1362  if (strcmp(dbname, "template1") != 0 &&
1363  strcmp(dbname, "template0") != 0 &&
1364  strcmp(dbname, "postgres") != 0)
1365  {
1366  fprintf(OPF, "DROP DATABASE %s%s;\n",
1367  if_exists ? "IF EXISTS " : "",
1368  fmtId(dbname));
1369  }
1370  }
1371 
1372  PQclear(res);
1373 
1374  fprintf(OPF, "\n\n");
1375 }
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3310
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3705
static int if_exists
Definition: pg_dumpall.c:98
static FILE * OPF
Definition: pg_dumpall.c:118
#define fprintf
Definition: port.h:242
const char * fmtId(const char *rawid)
Definition: string_utils.c:64

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 697 of file pg_dumpall.c.

698 {
700  PGresult *res;
701  int i_rolname;
702  int i;
703 
704  if (server_version >= 90600)
706  "SELECT rolname "
707  "FROM %s "
708  "WHERE rolname !~ '^pg_' "
709  "ORDER BY 1", role_catalog);
710  else
712  "SELECT rolname "
713  "FROM %s "
714  "ORDER BY 1", role_catalog);
715 
716  res = executeQuery(conn, buf->data);
717 
718  i_rolname = PQfnumber(res, "rolname");
719 
720  if (PQntuples(res) > 0)
721  fprintf(OPF, "--\n-- Drop roles\n--\n\n");
722 
723  for (i = 0; i < PQntuples(res); i++)
724  {
725  const char *rolename;
726 
727  rolename = PQgetvalue(res, i, i_rolname);
728 
729  fprintf(OPF, "DROP ROLE %s%s;\n",
730  if_exists ? "IF EXISTS " : "",
731  fmtId(rolename));
732  }
733 
734  PQclear(res);
736 
737  fprintf(OPF, "\n\n");
738 }
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3418
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 1205 of file pg_dumpall.c.

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

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 1471 of file pg_dumpall.c.

1472 {
1473  PGresult *res;
1474  int i;
1475 
1476  /*
1477  * Skip databases marked not datallowconn, since we'd be unable to connect
1478  * to them anyway. This must agree with dropDBs().
1479  *
1480  * We arrange for template1 to be processed first, then we process other
1481  * DBs in alphabetical order. If we just did them all alphabetically, we
1482  * might find ourselves trying to drop the "postgres" database while still
1483  * connected to it. This makes trying to run the restore script while
1484  * connected to "template1" a bad idea, but there's no fixed order that
1485  * doesn't have some failure mode with --clean.
1486  */
1487  res = executeQuery(conn,
1488  "SELECT datname "
1489  "FROM pg_database d "
1490  "WHERE datallowconn "
1491  "ORDER BY (datname <> 'template1'), datname");
1492 
1493  if (PQntuples(res) > 0)
1494  fprintf(OPF, "--\n-- Databases\n--\n\n");
1495 
1496  for (i = 0; i < PQntuples(res); i++)
1497  {
1498  char *dbname = PQgetvalue(res, i, 0);
1499  const char *create_opts;
1500  int ret;
1501 
1502  /* Skip template0, even if it's not marked !datallowconn. */
1503  if (strcmp(dbname, "template0") == 0)
1504  continue;
1505 
1506  /* Skip any explicitly excluded database */
1508  {
1509  pg_log_info("excluding database \"%s\"", dbname);
1510  continue;
1511  }
1512 
1513  pg_log_info("dumping database \"%s\"", dbname);
1514 
1515  fprintf(OPF, "--\n-- Database \"%s\" dump\n--\n\n", dbname);
1516 
1517  /*
1518  * We assume that "template1" and "postgres" already exist in the
1519  * target installation. dropDBs() won't have removed them, for fear
1520  * of removing the DB the restore script is initially connected to. If
1521  * --clean was specified, tell pg_dump to drop and recreate them;
1522  * otherwise we'll merely restore their contents. Other databases
1523  * should simply be created.
1524  */
1525  if (strcmp(dbname, "template1") == 0 || strcmp(dbname, "postgres") == 0)
1526  {
1527  if (output_clean)
1528  create_opts = "--clean --create";
1529  else
1530  {
1531  create_opts = "";
1532  /* Since pg_dump won't emit a \connect command, we must */
1533  fprintf(OPF, "\\connect %s\n\n", dbname);
1534  }
1535  }
1536  else
1537  create_opts = "--create";
1538 
1539  if (filename)
1540  fclose(OPF);
1541 
1542  ret = runPgDump(dbname, create_opts);
1543  if (ret != 0)
1544  pg_fatal("pg_dump failed on database \"%s\", exiting", dbname);
1545 
1546  if (filename)
1547  {
1548  OPF = fopen(filename, PG_BINARY_A);
1549  if (!OPF)
1550  pg_fatal("could not re-open the output file \"%s\": %m",
1551  filename);
1552  }
1553  }
1554 
1555  PQclear(res);
1556 }
#define PG_BINARY_A
Definition: c.h:1210
#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:1564
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 1150 of file pg_dumpall.c.

1151 {
1152  PGresult *res;
1153  int i;
1154 
1155  /*
1156  * Get all parameters that have non-default acls defined.
1157  */
1158  res = executeQuery(conn, "SELECT parname, "
1159  "pg_catalog.pg_get_userbyid(" CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS parowner, "
1160  "paracl, "
1161  "pg_catalog.acldefault('p', " CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS acldefault "
1162  "FROM pg_catalog.pg_parameter_acl "
1163  "ORDER BY 1");
1164 
1165  if (PQntuples(res) > 0)
1166  fprintf(OPF, "--\n-- Role privileges on configuration parameters\n--\n\n");
1167 
1168  for (i = 0; i < PQntuples(res); i++)
1169  {
1171  char *parname = PQgetvalue(res, i, 0);
1172  char *parowner = PQgetvalue(res, i, 1);
1173  char *paracl = PQgetvalue(res, i, 2);
1174  char *acldefault = PQgetvalue(res, i, 3);
1175  char *fparname;
1176 
1177  /* needed for buildACLCommands() */
1178  fparname = pg_strdup(fmtId(parname));
1179 
1180  if (!buildACLCommands(fparname, NULL, NULL, "PARAMETER",
1181  paracl, acldefault,
1182  parowner, "", server_version, buf))
1183  {
1184  pg_log_error("could not parse ACL list (%s) for parameter \"%s\"",
1185  paracl, parname);
1186  PQfinish(conn);
1187  exit_nicely(1);
1188  }
1189 
1190  fprintf(OPF, "%s", buf->data);
1191 
1192  free(fparname);
1194  }
1195 
1196  PQclear(res);
1197  fprintf(OPF, "\n\n");
1198 }
Acl * acldefault(ObjectType objtype, Oid ownerId)
Definition: acl.c:749
#define CppAsString2(x)
Definition: c.h:311
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 949 of file pg_dumpall.c.

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

Referenced by main().

◆ dumpRoles()

static void dumpRoles ( PGconn conn)
static

Definition at line 744 of file pg_dumpall.c.

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

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 1240 of file pg_dumpall.c.

1241 {
1242  PGresult *res;
1243  int i;
1244 
1245  /*
1246  * Get all tablespaces except built-in ones (which we assume are named
1247  * pg_xxx)
1248  */
1249  res = executeQuery(conn, "SELECT oid, spcname, "
1250  "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1251  "pg_catalog.pg_tablespace_location(oid), "
1252  "spcacl, acldefault('t', spcowner) AS acldefault, "
1253  "array_to_string(spcoptions, ', '),"
1254  "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1255  "FROM pg_catalog.pg_tablespace "
1256  "WHERE spcname !~ '^pg_' "
1257  "ORDER BY 1");
1258 
1259  if (PQntuples(res) > 0)
1260  fprintf(OPF, "--\n-- Tablespaces\n--\n\n");
1261 
1262  for (i = 0; i < PQntuples(res); i++)
1263  {
1265  Oid spcoid = atooid(PQgetvalue(res, i, 0));
1266  char *spcname = PQgetvalue(res, i, 1);
1267  char *spcowner = PQgetvalue(res, i, 2);
1268  char *spclocation = PQgetvalue(res, i, 3);
1269  char *spcacl = PQgetvalue(res, i, 4);
1270  char *acldefault = PQgetvalue(res, i, 5);
1271  char *spcoptions = PQgetvalue(res, i, 6);
1272  char *spccomment = PQgetvalue(res, i, 7);
1273  char *fspcname;
1274 
1275  /* needed for buildACLCommands() */
1276  fspcname = pg_strdup(fmtId(spcname));
1277 
1278  if (binary_upgrade)
1279  {
1280  appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_tablespace oid\n");
1281  appendPQExpBuffer(buf, "SELECT pg_catalog.binary_upgrade_set_next_pg_tablespace_oid('%u'::pg_catalog.oid);\n", spcoid);
1282  }
1283 
1284  appendPQExpBuffer(buf, "CREATE TABLESPACE %s", fspcname);
1285  appendPQExpBuffer(buf, " OWNER %s", fmtId(spcowner));
1286 
1287  appendPQExpBufferStr(buf, " LOCATION ");
1288  appendStringLiteralConn(buf, spclocation, conn);
1289  appendPQExpBufferStr(buf, ";\n");
1290 
1291  if (spcoptions && spcoptions[0] != '\0')
1292  appendPQExpBuffer(buf, "ALTER TABLESPACE %s SET (%s);\n",
1293  fspcname, spcoptions);
1294 
1295  /* tablespaces can't have initprivs */
1296 
1297  if (!skip_acls &&
1298  !buildACLCommands(fspcname, NULL, NULL, "TABLESPACE",
1299  spcacl, acldefault,
1300  spcowner, "", server_version, buf))
1301  {
1302  pg_log_error("could not parse ACL list (%s) for tablespace \"%s\"",
1303  spcacl, spcname);
1304  PQfinish(conn);
1305  exit_nicely(1);
1306  }
1307 
1308  if (!no_comments && spccomment && spccomment[0] != '\0')
1309  {
1310  appendPQExpBuffer(buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
1311  appendStringLiteralConn(buf, spccomment, conn);
1312  appendPQExpBufferStr(buf, ";\n");
1313  }
1314 
1315  if (!no_security_labels)
1316  buildShSecLabels(conn, "pg_tablespace", spcoid,
1317  "TABLESPACE", spcname,
1318  buf);
1319 
1320  fprintf(OPF, "%s", buf->data);
1321 
1322  free(fspcname);
1324  }
1325 
1326  PQclear(res);
1327  fprintf(OPF, "\n\n");
1328 }
static bool skip_acls
Definition: pg_dumpall.c:90

References acldefault(), appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), atooid, binary_upgrade, buf, buildACLCommands(), buildShSecLabels(), conn, createPQExpBuffer(), destroyPQExpBuffer(), executeQuery(), exit_nicely, fmtId(), fprintf, free, i, 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 1908 of file pg_dumpall.c.

1909 {
1910  char buf[64];
1911  time_t now = time(NULL);
1912 
1913  if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
1914  fprintf(OPF, "-- %s %s\n\n", msg, buf);
1915 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1537
#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 1382 of file pg_dumpall.c.

1383 {
1385  PGresult *res;
1386 
1387  printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1388  "WHERE setdatabase = 0 AND setrole = "
1389  "(SELECT oid FROM %s WHERE rolname = ",
1390  role_catalog);
1392  appendPQExpBufferChar(buf, ')');
1393 
1394  res = executeQuery(conn, buf->data);
1395 
1396  if (PQntuples(res) > 0)
1397  fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", username);
1398 
1399  for (int i = 0; i < PQntuples(res); i++)
1400  {
1403  "ROLE", username, NULL, NULL,
1404  buf);
1405  fprintf(OPF, "%s", buf->data);
1406  }
1407 
1408  PQclear(res);
1409 
1411 }
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition: dumputils.c:816
const char * username
Definition: pgbench.c:305

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 1884 of file pg_dumpall.c.

1885 {
1886  PGresult *res;
1887 
1888  pg_log_info("executing %s", query);
1889 
1890  res = PQexec(conn, query);
1891  if (!res ||
1893  {
1894  pg_log_error("query failed: %s", PQerrorMessage(conn));
1895  pg_log_error_detail("Query was: %s", query);
1896  PQfinish(conn);
1897  exit_nicely(1);
1898  }
1899 
1900  PQclear(res);
1901 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3240
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2225
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97

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()

static PGresult * executeQuery ( PGconn conn,
const char *  query 
)
static

◆ expand_dbname_patterns()

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

Definition at line 1418 of file pg_dumpall.c.

1421 {
1422  PQExpBuffer query;
1423  PGresult *res;
1424 
1425  if (patterns->head == NULL)
1426  return; /* nothing to do */
1427 
1428  query = createPQExpBuffer();
1429 
1430  /*
1431  * The loop below runs multiple SELECTs, which might sometimes result in
1432  * duplicate entries in the name list, but we don't care, since all we're
1433  * going to do is test membership of the list.
1434  */
1435 
1436  for (SimpleStringListCell *cell = patterns->head; cell; cell = cell->next)
1437  {
1438  int dotcnt;
1439 
1440  appendPQExpBufferStr(query,
1441  "SELECT datname FROM pg_catalog.pg_database n\n");
1442  processSQLNamePattern(conn, query, cell->val, false,
1443  false, NULL, "datname", NULL, NULL, NULL,
1444  &dotcnt);
1445 
1446  if (dotcnt > 0)
1447  {
1448  pg_log_error("improper qualified name (too many dotted names): %s",
1449  cell->val);
1450  PQfinish(conn);
1451  exit_nicely(1);
1452  }
1453 
1454  res = executeQuery(conn, query->data);
1455  for (int i = 0; i < PQntuples(res); i++)
1456  {
1458  }
1459 
1460  PQclear(res);
1461  resetPQExpBuffer(query);
1462  }
1463 
1464  destroyPQExpBuffer(query);
1465 }
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)
Definition: string_utils.c:891
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().

◆ hash_string_pointer()

static uint32 hash_string_pointer ( char *  s)
static

Definition at line 1921 of file pg_dumpall.c.

1922 {
1923  unsigned char *ss = (unsigned char *) s;
1924 
1925  return hash_bytes(ss, strlen(s));
1926 }
uint32 hash_bytes(const unsigned char *k, int keylen)
Definition: hashfn.c:146

References hash_bytes().

◆ help()

static void help ( void  )
static

Definition at line 627 of file pg_dumpall.c.

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

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 
181  {NULL, 0, NULL, 0}
182  };
183 
184  char *pghost = NULL;
185  char *pgport = NULL;
186  char *pguser = NULL;
187  char *pgdb = NULL;
188  char *use_role = NULL;
189  const char *dumpencoding = NULL;
190  trivalue prompt_password = TRI_DEFAULT;
191  bool data_only = false;
192  bool globals_only = false;
193  bool roles_only = false;
194  bool tablespaces_only = false;
195  PGconn *conn;
196  int encoding;
197  const char *std_strings;
198  int c,
199  ret;
200  int optindex;
201 
202  pg_logging_init(argv[0]);
204  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
205  progname = get_progname(argv[0]);
206 
207  if (argc > 1)
208  {
209  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
210  {
211  help();
212  exit_nicely(0);
213  }
214  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
215  {
216  puts("pg_dumpall (PostgreSQL) " PG_VERSION);
217  exit_nicely(0);
218  }
219  }
220 
221  if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
222  pg_dump_bin)) < 0)
223  {
224  char full_path[MAXPGPATH];
225 
226  if (find_my_exec(argv[0], full_path) < 0)
227  strlcpy(full_path, progname, sizeof(full_path));
228 
229  if (ret == -1)
230  pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
231  "pg_dump", progname, full_path);
232  else
233  pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
234  "pg_dump", full_path, progname);
235  }
236 
238 
239  while ((c = getopt_long(argc, argv, "acd:E:f:gh:l:Op:rsS:tU:vwWx", long_options, &optindex)) != -1)
240  {
241  switch (c)
242  {
243  case 'a':
244  data_only = true;
246  break;
247 
248  case 'c':
249  output_clean = true;
250  break;
251 
252  case 'd':
254  break;
255 
256  case 'E':
257  dumpencoding = pg_strdup(optarg);
260  break;
261 
262  case 'f':
266  break;
267 
268  case 'g':
269  globals_only = true;
270  break;
271 
272  case 'h':
274  break;
275 
276  case 'l':
277  pgdb = pg_strdup(optarg);
278  break;
279 
280  case 'O':
282  break;
283 
284  case 'p':
286  break;
287 
288  case 'r':
289  roles_only = true;
290  break;
291 
292  case 's':
294  break;
295 
296  case 'S':
299  break;
300 
301  case 't':
302  tablespaces_only = true;
303  break;
304 
305  case 'U':
306  pguser = pg_strdup(optarg);
307  break;
308 
309  case 'v':
310  verbose = true;
313  break;
314 
315  case 'w':
316  prompt_password = TRI_NO;
318  break;
319 
320  case 'W':
321  prompt_password = TRI_YES;
323  break;
324 
325  case 'x':
326  skip_acls = true;
328  break;
329 
330  case 0:
331  break;
332 
333  case 2:
334  appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
336  break;
337 
338  case 3:
339  use_role = pg_strdup(optarg);
340  appendPQExpBufferStr(pgdumpopts, " --role ");
341  appendShellString(pgdumpopts, use_role);
342  break;
343 
344  case 4:
345  dosync = false;
346  appendPQExpBufferStr(pgdumpopts, " --no-sync");
347  break;
348 
349  case 5:
350  appendPQExpBufferStr(pgdumpopts, " --extra-float-digits ");
352  break;
353 
354  case 6:
356  break;
357 
358  case 7:
359  appendPQExpBufferStr(pgdumpopts, " --rows-per-insert ");
361  break;
362 
363  default:
364  /* getopt_long already emitted a complaint */
365  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
366  exit_nicely(1);
367  }
368  }
369 
370  /* Complain if any arguments remain */
371  if (optind < argc)
372  {
373  pg_log_error("too many command-line arguments (first is \"%s\")",
374  argv[optind]);
375  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
376  exit_nicely(1);
377  }
378 
379  if (database_exclude_patterns.head != NULL &&
380  (globals_only || roles_only || tablespaces_only))
381  {
382  pg_log_error("option --exclude-database cannot be used together with -g/--globals-only, -r/--roles-only, or -t/--tablespaces-only");
383  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
384  exit_nicely(1);
385  }
386 
387  /* Make sure the user hasn't specified a mix of globals-only options */
388  if (globals_only && roles_only)
389  {
390  pg_log_error("options -g/--globals-only and -r/--roles-only cannot be used together");
391  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
392  exit_nicely(1);
393  }
394 
395  if (globals_only && tablespaces_only)
396  {
397  pg_log_error("options -g/--globals-only and -t/--tablespaces-only cannot be used together");
398  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
399  exit_nicely(1);
400  }
401 
402  if (if_exists && !output_clean)
403  pg_fatal("option --if-exists requires option -c/--clean");
404 
405  if (roles_only && tablespaces_only)
406  {
407  pg_log_error("options -r/--roles-only and -t/--tablespaces-only cannot be used together");
408  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
409  exit_nicely(1);
410  }
411 
412  /*
413  * If password values are not required in the dump, switch to using
414  * pg_roles which is equally useful, just more likely to have unrestricted
415  * access than pg_authid.
416  */
417  if (no_role_passwords)
418  sprintf(role_catalog, "%s", PG_ROLES);
419  else
421 
422  /* Add long options to the pg_dump argument list */
423  if (binary_upgrade)
424  appendPQExpBufferStr(pgdumpopts, " --binary-upgrade");
425  if (column_inserts)
426  appendPQExpBufferStr(pgdumpopts, " --column-inserts");
428  appendPQExpBufferStr(pgdumpopts, " --disable-dollar-quoting");
429  if (disable_triggers)
430  appendPQExpBufferStr(pgdumpopts, " --disable-triggers");
431  if (inserts)
432  appendPQExpBufferStr(pgdumpopts, " --inserts");
434  appendPQExpBufferStr(pgdumpopts, " --no-table-access-method");
435  if (no_tablespaces)
436  appendPQExpBufferStr(pgdumpopts, " --no-tablespaces");
438  appendPQExpBufferStr(pgdumpopts, " --quote-all-identifiers");
440  appendPQExpBufferStr(pgdumpopts, " --load-via-partition-root");
441  if (use_setsessauth)
442  appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
443  if (no_comments)
444  appendPQExpBufferStr(pgdumpopts, " --no-comments");
445  if (no_publications)
446  appendPQExpBufferStr(pgdumpopts, " --no-publications");
447  if (no_security_labels)
448  appendPQExpBufferStr(pgdumpopts, " --no-security-labels");
449  if (no_subscriptions)
450  appendPQExpBufferStr(pgdumpopts, " --no-subscriptions");
452  appendPQExpBufferStr(pgdumpopts, " --no-toast-compression");
454  appendPQExpBufferStr(pgdumpopts, " --no-unlogged-table-data");
456  appendPQExpBufferStr(pgdumpopts, " --on-conflict-do-nothing");
457 
458  /*
459  * If there was a database specified on the command line, use that,
460  * otherwise try to connect to database "postgres", and failing that
461  * "template1".
462  */
463  if (pgdb)
464  {
465  conn = connectDatabase(pgdb, connstr, pghost, pgport, pguser,
466  prompt_password, false);
467 
468  if (!conn)
469  pg_fatal("could not connect to database \"%s\"", pgdb);
470  }
471  else
472  {
473  conn = connectDatabase("postgres", connstr, pghost, pgport, pguser,
474  prompt_password, false);
475  if (!conn)
476  conn = connectDatabase("template1", connstr, pghost, pgport, pguser,
477  prompt_password, true);
478 
479  if (!conn)
480  {
481  pg_log_error("could not connect to databases \"postgres\" or \"template1\"\n"
482  "Please specify an alternative database.");
483  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
484  exit_nicely(1);
485  }
486  }
487 
488  /*
489  * Get a list of database names that match the exclude patterns
490  */
493 
494  /*
495  * Open the output file if required, otherwise use stdout
496  */
497  if (filename)
498  {
499  OPF = fopen(filename, PG_BINARY_W);
500  if (!OPF)
501  pg_fatal("could not open output file \"%s\": %m",
502  filename);
503  }
504  else
505  OPF = stdout;
506 
507  /*
508  * Set the client encoding if requested.
509  */
510  if (dumpencoding)
511  {
512  if (PQsetClientEncoding(conn, dumpencoding) < 0)
513  pg_fatal("invalid client encoding \"%s\" specified",
514  dumpencoding);
515  }
516 
517  /*
518  * Get the active encoding and the standard_conforming_strings setting, so
519  * we know how to escape strings.
520  */
522  std_strings = PQparameterStatus(conn, "standard_conforming_strings");
523  if (!std_strings)
524  std_strings = "off";
525 
526  /* Set the role if requested */
527  if (use_role)
528  {
529  PQExpBuffer query = createPQExpBuffer();
530 
531  appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
532  executeCommand(conn, query->data);
533  destroyPQExpBuffer(query);
534  }
535 
536  /* Force quoting of all identifiers if requested. */
538  executeCommand(conn, "SET quote_all_identifiers = true");
539 
540  fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
541  if (verbose)
542  dumpTimestamp("Started on");
543 
544  /*
545  * We used to emit \connect postgres here, but that served no purpose
546  * other than to break things for installations without a postgres
547  * database. Everything we're restoring here is a global, so whichever
548  * database we're connected to at the moment is fine.
549  */
550 
551  /* Restore will need to write to the target cluster */
552  fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
553 
554  /* Replicate encoding and std_strings in output */
555  fprintf(OPF, "SET client_encoding = '%s';\n",
557  fprintf(OPF, "SET standard_conforming_strings = %s;\n", std_strings);
558  if (strcmp(std_strings, "off") == 0)
559  fprintf(OPF, "SET escape_string_warning = off;\n");
560  fprintf(OPF, "\n");
561 
562  if (!data_only)
563  {
564  /*
565  * If asked to --clean, do that first. We can avoid detailed
566  * dependency analysis because databases never depend on each other,
567  * and tablespaces never depend on each other. Roles could have
568  * grants to each other, but DROP ROLE will clean those up silently.
569  */
570  if (output_clean)
571  {
572  if (!globals_only && !roles_only && !tablespaces_only)
573  dropDBs(conn);
574 
575  if (!roles_only && !no_tablespaces)
577 
578  if (!tablespaces_only)
579  dropRoles(conn);
580  }
581 
582  /*
583  * Now create objects as requested. Be careful that option logic here
584  * is the same as for drops above.
585  */
586  if (!tablespaces_only)
587  {
588  /* Dump roles (users) */
589  dumpRoles(conn);
590 
591  /* Dump role memberships */
593 
594  /* Dump role GUC privileges */
595  if (server_version >= 150000 && !skip_acls)
597  }
598 
599  /* Dump tablespaces */
600  if (!roles_only && !no_tablespaces)
602  }
603 
604  if (!globals_only && !roles_only && !tablespaces_only)
606 
607  PQfinish(conn);
608 
609  if (verbose)
610  dumpTimestamp("Completed on");
611  fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
612 
613  if (filename)
614  {
615  fclose(OPF);
616 
617  /* sync the resulting file, errors are not fatal */
618  if (dosync)
619  (void) fsync_fname(filename, false);
620  }
621 
622  exit_nicely(0);
623 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1153
#define PG_BINARY_W
Definition: c.h:1212
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:152
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:460
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:351
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:662
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6820
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6828
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
void pg_logging_increase_verbosity(void)
Definition: logging.c:182
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:173
#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:1908
static int on_conflict_do_nothing
Definition: pg_dumpall.c:112
static void dropTablespaces(PGconn *conn)
Definition: pg_dumpall.c:1205
static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
Definition: pg_dumpall.c:1418
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:1240
static void dumpRoleMembership(PGconn *conn)
Definition: pg_dumpall.c:949
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:1641
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:1471
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:1884
static bool verbose
Definition: pg_dumpall.c:91
static void dumpRoleGUCPrivs(PGconn *conn)
Definition: pg_dumpall.c:1150
static void dumpRoles(PGconn *conn)
Definition: pg_dumpall.c:744
static void help(void)
Definition: pg_dumpall.c:627
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 dropRoles(PGconn *conn)
Definition: pg_dumpall.c:697
static void dropDBs(PGconn *conn)
Definition: pg_dumpall.c:1335
static int no_subscriptions
Definition: pg_dumpall.c:106
#define PGDUMP_VERSIONSTR
Definition: pg_dumpall.c:33
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define sprintf
Definition: port.h:240
const char * get_progname(const char *argv0)
Definition: path.c:574
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char * c
bool quote_all_identifiers
Definition: ruleutils.c:324
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:429
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, required_argument, role_catalog, server_version, set_pglocale_pgservice(), simple_string_list_append(), skip_acls, sprintf, generate_unaccent_rules::stdout, strlcpy(), TRI_DEFAULT, TRI_NO, TRI_YES, use_setsessauth, and verbose.

◆ runPgDump()

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

Definition at line 1564 of file pg_dumpall.c.

1565 {
1566  PQExpBuffer connstrbuf = createPQExpBuffer();
1568  int ret;
1569 
1570  appendPQExpBuffer(cmd, "\"%s\" %s %s", pg_dump_bin,
1571  pgdumpopts->data, create_opts);
1572 
1573  /*
1574  * If we have a filename, use the undocumented plain-append pg_dump
1575  * format.
1576  */
1577  if (filename)
1578  appendPQExpBufferStr(cmd, " -Fa ");
1579  else
1580  appendPQExpBufferStr(cmd, " -Fp ");
1581 
1582  /*
1583  * Append the database name to the already-constructed stem of connection
1584  * string.
1585  */
1586  appendPQExpBuffer(connstrbuf, "%s dbname=", connstr);
1587  appendConnStrVal(connstrbuf, dbname);
1588 
1589  appendShellString(cmd, connstrbuf->data);
1590 
1591  pg_log_info("running \"%s\"", cmd->data);
1592 
1593  fflush(NULL);
1594 
1595  ret = system(cmd->data);
1596 
1597  destroyPQExpBuffer(cmd);
1598  destroyPQExpBuffer(connstrbuf);
1599 
1600  return ret;
1601 }
static void const char fflush(stdout)

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

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 _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(), execute_extension_script(), expand_tilde(), exportFile(), extract_directory(), extract_link(), file_acquire_sample_rows(), file_fdw_validator(), fileAnalyzeForeignTable(), fileBeginForeignScan(), fileExplainForeignScan(), fileGetOptions(), fill_hba_line(), fill_ident_line(), first_dir_separator(), get_sock_dir(), GetConfFilesInDir(), importFile(), initTrie(), internal_load_library(), is_checksummed_file(), is_extension_control_filename(), is_extension_script_filename(), is_xlogfilename(), 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_native_path(), make_outputdirs(), next_field_expand(), NIImportAffixes(), NIImportDictionary(), NIImportOOAffixes(), open_auth_file(), parse_extension_control_file(), parseIntFromText(), ParseTzFile(), parseVxidFromText(), parseXidFromText(), pg_file_sync(), pg_file_unlink(), pg_file_unlink_v1_1(), pg_file_write_internal(), pg_log_generic_v(), pg_read_file(), pg_stat_file(), PLy_traceback(), process_file(), process_psqlrc_file(), process_queued_fetch_requests(), progress_update_filename(), read_binary_file(), read_dictionary(), read_extension_script_file(), read_text_file(), read_whole_file(), readstoplist(), regcomp_auth_token(), rmtree(), run_diff(), runPgDump(), sendFile(), sendFileWithContent(), set_input(), SetOutput(), setup_run_file(), shell_construct_command(), shell_run_command(), splitTzLine(), SysLogger_Start(), tar_get_file_name(), tarOpen(), test_slru_scan_cb(), thesaurusRead(), tokenize_auth_file(), TrimExtension(), tsearch_readline_begin(), UpdateLastRemovedPtr(), verify_backup_directory(), write_auto_conf_file(), WriteRecoveryConfig(), and writeTimeLineHistoryFile().

◆ 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().