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

1631 {
1633  PGresult *res;
1634 
1635  buildShSecLabelQuery(catalog_name, objectId, sql);
1636  res = executeQuery(conn, sql->data);
1637  emitShSecLabels(conn, res, buffer, objtype, objname);
1638 
1639  PQclear(res);
1640  destroyPQExpBuffer(sql);
1641 }
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition: dumputils.c:636
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition: dumputils.c:654
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1874
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 1654 of file pg_dumpall.c.

1657 {
1658  PGconn *conn;
1659  bool new_pass;
1660  const char *remoteversion_str;
1661  int my_version;
1662  const char **keywords = NULL;
1663  const char **values = NULL;
1664  PQconninfoOption *conn_opts = NULL;
1665  static char *password = NULL;
1666 
1667  if (prompt_password == TRI_YES && !password)
1668  password = simple_prompt("Password: ", false);
1669 
1670  /*
1671  * Start the connection. Loop until we have a password if requested by
1672  * backend.
1673  */
1674  do
1675  {
1676  int argcount = 6;
1677  PQconninfoOption *conn_opt;
1678  char *err_msg = NULL;
1679  int i = 0;
1680 
1681  free(keywords);
1682  free(values);
1683  PQconninfoFree(conn_opts);
1684 
1685  /*
1686  * Merge the connection info inputs given in form of connection string
1687  * and other options. Explicitly discard any dbname value in the
1688  * connection string; otherwise, PQconnectdbParams() would interpret
1689  * that value as being itself a connection string.
1690  */
1691  if (connection_string)
1692  {
1693  conn_opts = PQconninfoParse(connection_string, &err_msg);
1694  if (conn_opts == NULL)
1695  pg_fatal("%s", err_msg);
1696 
1697  for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
1698  {
1699  if (conn_opt->val != NULL && conn_opt->val[0] != '\0' &&
1700  strcmp(conn_opt->keyword, "dbname") != 0)
1701  argcount++;
1702  }
1703 
1704  keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1705  values = pg_malloc0((argcount + 1) * sizeof(*values));
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  {
1712  keywords[i] = conn_opt->keyword;
1713  values[i] = conn_opt->val;
1714  i++;
1715  }
1716  }
1717  }
1718  else
1719  {
1720  keywords = pg_malloc0((argcount + 1) * sizeof(*keywords));
1721  values = pg_malloc0((argcount + 1) * sizeof(*values));
1722  }
1723 
1724  if (pghost)
1725  {
1726  keywords[i] = "host";
1727  values[i] = pghost;
1728  i++;
1729  }
1730  if (pgport)
1731  {
1732  keywords[i] = "port";
1733  values[i] = pgport;
1734  i++;
1735  }
1736  if (pguser)
1737  {
1738  keywords[i] = "user";
1739  values[i] = pguser;
1740  i++;
1741  }
1742  if (password)
1743  {
1744  keywords[i] = "password";
1745  values[i] = password;
1746  i++;
1747  }
1748  if (dbname)
1749  {
1750  keywords[i] = "dbname";
1751  values[i] = dbname;
1752  i++;
1753  }
1754  keywords[i] = "fallback_application_name";
1755  values[i] = progname;
1756  i++;
1757 
1758  new_pass = false;
1759  conn = PQconnectdbParams(keywords, values, true);
1760 
1761  if (!conn)
1762  pg_fatal("could not connect to database \"%s\"", dbname);
1763 
1764  if (PQstatus(conn) == CONNECTION_BAD &&
1766  !password &&
1767  prompt_password != TRI_NO)
1768  {
1769  PQfinish(conn);
1770  password = simple_prompt("Password: ", false);
1771  new_pass = true;
1772  }
1773  } while (new_pass);
1774 
1775  /* check to see that the backend connection was successfully made */
1776  if (PQstatus(conn) == CONNECTION_BAD)
1777  {
1778  if (fail_on_error)
1779  pg_fatal("%s", PQerrorMessage(conn));
1780  else
1781  {
1782  PQfinish(conn);
1783 
1784  free(keywords);
1785  free(values);
1786  PQconninfoFree(conn_opts);
1787 
1788  return NULL;
1789  }
1790  }
1791 
1792  /*
1793  * Ok, connected successfully. Remember the options used, in the form of a
1794  * connection string.
1795  */
1796  connstr = constructConnStr(keywords, values);
1797 
1798  free(keywords);
1799  free(values);
1800  PQconninfoFree(conn_opts);
1801 
1802  /* Check version */
1803  remoteversion_str = PQparameterStatus(conn, "server_version");
1804  if (!remoteversion_str)
1805  pg_fatal("could not get server version");
1807  if (server_version == 0)
1808  pg_fatal("could not parse server version \"%s\"",
1809  remoteversion_str);
1810 
1811  my_version = PG_VERSION_NUM;
1812 
1813  /*
1814  * We allow the server to be back to 9.2, and up to any minor release of
1815  * our own major version. (See also version check in pg_dump.c.)
1816  */
1817  if (my_version != server_version
1818  && (server_version < 90200 ||
1819  (server_version / 100) > (my_version / 100)))
1820  {
1821  pg_log_error("aborting because of server version mismatch");
1822  pg_log_error_detail("server version: %s; %s version: %s",
1823  remoteversion_str, progname, PG_VERSION);
1824  exit_nicely(1);
1825  }
1826 
1828 
1829  return conn;
1830 }
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:7213
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7238
PQconninfoOption * PQconninfoParse(const char *conninfo, char **errmsg)
Definition: fe-connect.c:5829
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:676
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7081
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:7299
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7248
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7195
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4602
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:1843
static int server_version
Definition: pg_dumpall.c:110
static const char * progname
Definition: pg_dumpall.c:86
const char * pghost
Definition: pgbench.c:294
const char * pgport
Definition: pgbench.c:295
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 1843 of file pg_dumpall.c.

1844 {
1846  char *connstr;
1847  int i;
1848  bool firstkeyword = true;
1849 
1850  /* Construct a new connection string in key='value' format. */
1851  for (i = 0; keywords[i] != NULL; i++)
1852  {
1853  if (strcmp(keywords[i], "dbname") == 0 ||
1854  strcmp(keywords[i], "password") == 0 ||
1855  strcmp(keywords[i], "fallback_application_name") == 0)
1856  continue;
1857 
1858  if (!firstkeyword)
1859  appendPQExpBufferChar(buf, ' ');
1860  firstkeyword = false;
1861  appendPQExpBuffer(buf, "%s=", keywords[i]);
1863  }
1864 
1865  connstr = pg_strdup(buf->data);
1867  return connstr;
1868 }
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 1345 of file pg_dumpall.c.

1346 {
1347  PGresult *res;
1348  int i;
1349 
1350  /*
1351  * Skip databases marked not datallowconn, since we'd be unable to connect
1352  * to them anyway. This must agree with dumpDatabases().
1353  */
1354  res = executeQuery(conn,
1355  "SELECT datname "
1356  "FROM pg_database d "
1357  "WHERE datallowconn AND datconnlimit != -2 "
1358  "ORDER BY datname");
1359 
1360  if (PQntuples(res) > 0)
1361  fprintf(OPF, "--\n-- Drop databases (except postgres and template1)\n--\n\n");
1362 
1363  for (i = 0; i < PQntuples(res); i++)
1364  {
1365  char *dbname = PQgetvalue(res, i, 0);
1366 
1367  /*
1368  * Skip "postgres" and "template1"; dumpDatabases() will deal with
1369  * them specially. Also, be sure to skip "template0", even if for
1370  * some reason it's not marked !datallowconn.
1371  */
1372  if (strcmp(dbname, "template1") != 0 &&
1373  strcmp(dbname, "template0") != 0 &&
1374  strcmp(dbname, "postgres") != 0)
1375  {
1376  fprintf(OPF, "DROP DATABASE %s%s;\n",
1377  if_exists ? "IF EXISTS " : "",
1378  fmtId(dbname));
1379  }
1380  }
1381 
1382  PQclear(res);
1383 
1384  fprintf(OPF, "\n\n");
1385 }
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3395
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3790
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:3503
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 1206 of file pg_dumpall.c.

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

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

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

1152 {
1153  PGresult *res;
1154  int i;
1155 
1156  /*
1157  * Get all parameters that have non-default acls defined.
1158  */
1159  res = executeQuery(conn, "SELECT parname, "
1160  "pg_catalog.pg_get_userbyid(" CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS parowner, "
1161  "paracl, "
1162  "pg_catalog.acldefault('p', " CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS acldefault "
1163  "FROM pg_catalog.pg_parameter_acl "
1164  "ORDER BY 1");
1165 
1166  if (PQntuples(res) > 0)
1167  fprintf(OPF, "--\n-- Role privileges on configuration parameters\n--\n\n");
1168 
1169  for (i = 0; i < PQntuples(res); i++)
1170  {
1172  char *parname = PQgetvalue(res, i, 0);
1173  char *parowner = PQgetvalue(res, i, 1);
1174  char *paracl = PQgetvalue(res, i, 2);
1175  char *acldefault = PQgetvalue(res, i, 3);
1176  char *fparname;
1177 
1178  /* needed for buildACLCommands() */
1179  fparname = pg_strdup(fmtId(parname));
1180 
1181  if (!buildACLCommands(fparname, NULL, NULL, "PARAMETER",
1182  paracl, acldefault,
1183  parowner, "", server_version, buf))
1184  {
1185  pg_log_error("could not parse ACL list (%s) for parameter \"%s\"",
1186  paracl, parname);
1187  PQfinish(conn);
1188  exit_nicely(1);
1189  }
1190 
1191  fprintf(OPF, "%s", buf->data);
1192 
1193  free(fparname);
1195  }
1196 
1197  PQclear(res);
1198  fprintf(OPF, "\n\n");
1199 }
Acl * acldefault(ObjectType objtype, Oid ownerId)
Definition: acl.c:777
#define CppAsString2(x)
Definition: c.h:316
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 arbitrary order, because a role
999  * that is named as a grantor must already have ADMIN OPTION on the role
1000  * for which it is granting permissions, except for the bootstrap
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 bootstrap
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 let
1009  * 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 passes 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  prev_remaining = remaining;
1056 
1057  /* Make one pass over the grants for this role. */
1058  for (i = start; i < end; ++i)
1059  {
1060  char *member;
1061  char *admin_option;
1062  char *grantorid;
1063  char *grantor;
1064  char *set_option = "true";
1065  bool found;
1066 
1067  /* If we already did this grant, don't do it again. */
1068  if (done[i - start])
1069  continue;
1070 
1071  member = PQgetvalue(res, i, 1);
1072  grantorid = PQgetvalue(res, i, 2);
1073  grantor = PQgetvalue(res, i, 3);
1074  admin_option = PQgetvalue(res, i, 4);
1075  if (dump_grant_options)
1076  set_option = PQgetvalue(res, i, i_set_option);
1077 
1078  /*
1079  * If we're not dumping grantors or if the grantor is the
1080  * bootstrap superuser, it's fine to dump this now. Otherwise,
1081  * it's got to be someone who has already been granted ADMIN
1082  * OPTION.
1083  */
1084  if (dump_grantors &&
1085  atooid(grantorid) != BOOTSTRAP_SUPERUSERID &&
1086  rolename_lookup(ht, grantor) == NULL)
1087  continue;
1088 
1089  /* Remember that we did this so that we don't do it again. */
1090  done[i - start] = true;
1091  --remaining;
1092 
1093  /*
1094  * If ADMIN OPTION is being granted, remember that grants
1095  * listing this member as the grantor can now be dumped.
1096  */
1097  if (*admin_option == 't')
1098  rolename_insert(ht, member, &found);
1099 
1100  /* Generate the actual GRANT statement. */
1101  resetPQExpBuffer(optbuf);
1102  fprintf(OPF, "GRANT %s", fmtId(role));
1103  fprintf(OPF, " TO %s", fmtId(member));
1104  if (*admin_option == 't')
1105  appendPQExpBufferStr(optbuf, "ADMIN OPTION");
1106  if (dump_grant_options)
1107  {
1108  char *inherit_option;
1109 
1110  if (optbuf->data[0] != '\0')
1111  appendPQExpBufferStr(optbuf, ", ");
1112  inherit_option = PQgetvalue(res, i, i_inherit_option);
1113  appendPQExpBuffer(optbuf, "INHERIT %s",
1114  *inherit_option == 't' ?
1115  "TRUE" : "FALSE");
1116  }
1117  if (*set_option != 't')
1118  {
1119  if (optbuf->data[0] != '\0')
1120  appendPQExpBufferStr(optbuf, ", ");
1121  appendPQExpBuffer(optbuf, "SET FALSE");
1122  }
1123  if (optbuf->data[0] != '\0')
1124  fprintf(OPF, " WITH %s", optbuf->data);
1125  if (dump_grantors)
1126  fprintf(OPF, " GRANTED BY %s", fmtId(grantor));
1127  fprintf(OPF, ";\n");
1128  }
1129  }
1130 
1131  rolename_destroy(ht);
1132  pg_free(done);
1133  start = end;
1134  }
1135 
1136  PQclear(res);
1138 
1139  fprintf(OPF, "\n\n");
1140 }
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:3815
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:1392
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:1628
#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 1241 of file pg_dumpall.c.

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

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

1922 {
1923  char buf[64];
1924  time_t now = time(NULL);
1925 
1926  if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
1927  fprintf(OPF, "-- %s %s\n\n", msg, buf);
1928 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
#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 1392 of file pg_dumpall.c.

1393 {
1395  PGresult *res;
1396 
1397  printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1398  "WHERE setdatabase = 0 AND setrole = "
1399  "(SELECT oid FROM %s WHERE rolname = ",
1400  role_catalog);
1402  appendPQExpBufferChar(buf, ')');
1403 
1404  res = executeQuery(conn, buf->data);
1405 
1406  if (PQntuples(res) > 0)
1407  fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", username);
1408 
1409  for (int i = 0; i < PQntuples(res); i++)
1410  {
1413  "ROLE", username, NULL, NULL,
1414  buf);
1415  fprintf(OPF, "%s", buf->data);
1416  }
1417 
1418  PQclear(res);
1419 
1421 }
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition: dumputils.c:822
const char * username
Definition: pgbench.c:296

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

1898 {
1899  PGresult *res;
1900 
1901  pg_log_info("executing %s", query);
1902 
1903  res = PQexec(conn, query);
1904  if (!res ||
1906  {
1907  pg_log_error("query failed: %s", PQerrorMessage(conn));
1908  pg_log_error_detail("Query was: %s", query);
1909  PQfinish(conn);
1910  exit_nicely(1);
1911  }
1912 
1913  PQclear(res);
1914 }
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3325
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2228
@ 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 1428 of file pg_dumpall.c.

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

1935 {
1936  unsigned char *ss = (unsigned char *) s;
1937 
1938  return hash_bytes(ss, strlen(s));
1939 }
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:91
#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:1227
#define PG_BINARY_W
Definition: c.h:1286
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:158
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:436
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:327
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:708
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:7336
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:7344
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: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:1921
static int on_conflict_do_nothing
Definition: pg_dumpall.c:112
static void dropTablespaces(PGconn *conn)
Definition: pg_dumpall.c:1206
static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
Definition: pg_dumpall.c:1428
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:1241
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:1654
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:1481
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:1897
static bool verbose
Definition: pg_dumpall.c:91
static void dumpRoleGUCPrivs(PGconn *conn)
Definition: pg_dumpall.c:1151
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:1345
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 1574 of file pg_dumpall.c.

1575 {
1576  PQExpBufferData connstrbuf;
1577  PQExpBufferData cmd;
1578  int ret;
1579 
1580  initPQExpBuffer(&connstrbuf);
1581  initPQExpBuffer(&cmd);
1582 
1583  printfPQExpBuffer(&cmd, "\"%s\" %s %s", pg_dump_bin,
1584  pgdumpopts->data, create_opts);
1585 
1586  /*
1587  * If we have a filename, use the undocumented plain-append pg_dump
1588  * format.
1589  */
1590  if (filename)
1591  appendPQExpBufferStr(&cmd, " -Fa ");
1592  else
1593  appendPQExpBufferStr(&cmd, " -Fp ");
1594 
1595  /*
1596  * Append the database name to the already-constructed stem of connection
1597  * string.
1598  */
1599  appendPQExpBuffer(&connstrbuf, "%s dbname=", connstr);
1600  appendConnStrVal(&connstrbuf, dbname);
1601 
1602  appendShellString(&cmd, connstrbuf.data);
1603 
1604  pg_log_info("running \"%s\"", cmd.data);
1605 
1606  fflush(NULL);
1607 
1608  ret = system(cmd.data);
1609 
1610  termPQExpBuffer(&cmd);
1611  termPQExpBuffer(&connstrbuf);
1612 
1613  return ret;
1614 }
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(), 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(), hasSuffix(), 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(), run_diff(), runPgDump(), sendFile(), sendFileWithContent(), set_input(), set_stack_entry_location(), SetOutput(), setup_run_file(), shell_construct_command(), shell_run_command(), should_allow_existing_directory(), 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(), 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().