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 "filter.h"
#include "getopt_long.h"
#include "pg_backup.h"
#include "lib/simplehash.h"
Include dependency graph for pg_dumpall.c:

Go to the source code of this file.

Data Structures

struct  RoleNameEntry
 

Macros

#define PGDUMP_VERSIONSTR   "pg_dump (PostgreSQL) " PG_VERSION "\n"
 
#define SH_PREFIX   rolename
 
#define SH_ELEMENT_TYPE   RoleNameEntry
 
#define SH_KEY_TYPE   char *
 
#define SH_KEY   rolename
 
#define SH_HASH_KEY(tb, key)   hash_string_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)
 
static void read_dumpall_filters (const char *filename, SimpleStringList *patterns)
 
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 126 of file pg_dumpall.c.

◆ PG_AUTHID

#define PG_AUTHID   "pg_authid"

Definition at line 117 of file pg_dumpall.c.

◆ PG_ROLES

#define PG_ROLES   "pg_roles "

Definition at line 118 of file pg_dumpall.c.

◆ PGDUMP_VERSIONSTR

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

Definition at line 34 of file pg_dumpall.c.

◆ SH_DECLARE

#define SH_DECLARE

Definition at line 55 of file pg_dumpall.c.

◆ SH_DEFINE

#define SH_DEFINE

Definition at line 56 of file pg_dumpall.c.

◆ SH_ELEMENT_TYPE

#define SH_ELEMENT_TYPE   RoleNameEntry

Definition at line 46 of file pg_dumpall.c.

◆ SH_EQUAL

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

Definition at line 50 of file pg_dumpall.c.

◆ SH_GET_HASH

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

Definition at line 52 of file pg_dumpall.c.

◆ SH_HASH_KEY

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

Definition at line 49 of file pg_dumpall.c.

◆ SH_KEY

#define SH_KEY   rolename

Definition at line 48 of file pg_dumpall.c.

◆ SH_KEY_TYPE

#define SH_KEY_TYPE   char *

Definition at line 47 of file pg_dumpall.c.

◆ SH_PREFIX

#define SH_PREFIX   rolename

Definition at line 45 of file pg_dumpall.c.

◆ SH_RAW_ALLOCATOR

#define SH_RAW_ALLOCATOR   pg_malloc0

Definition at line 54 of file pg_dumpall.c.

◆ SH_SCOPE

#define SH_SCOPE   static inline

Definition at line 53 of file pg_dumpall.c.

◆ SH_STORE_HASH

#define SH_STORE_HASH

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

1639 {
1641  PGresult *res;
1642 
1643  buildShSecLabelQuery(catalog_name, objectId, sql);
1644  res = executeQuery(conn, sql->data);
1645  emitShSecLabels(conn, res, buffer, objtype, objname);
1646 
1647  PQclear(res);
1648  destroyPQExpBuffer(sql);
1649 }
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition: dumputils.c:637
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition: dumputils.c:655
static PGresult * executeQuery(PGconn *conn, const char *query)
Definition: pg_dumpall.c:1882
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 1662 of file pg_dumpall.c.

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

1852 {
1854  char *connstr;
1855  int i;
1856  bool firstkeyword = true;
1857 
1858  /* Construct a new connection string in key='value' format. */
1859  for (i = 0; keywords[i] != NULL; i++)
1860  {
1861  if (strcmp(keywords[i], "dbname") == 0 ||
1862  strcmp(keywords[i], "password") == 0 ||
1863  strcmp(keywords[i], "fallback_application_name") == 0)
1864  continue;
1865 
1866  if (!firstkeyword)
1867  appendPQExpBufferChar(buf, ' ');
1868  firstkeyword = false;
1869  appendPQExpBuffer(buf, "%s=", keywords[i]);
1871  }
1872 
1873  connstr = pg_strdup(buf->data);
1875  return connstr;
1876 }
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * buf
Definition: pg_test_fsync.c:73
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 1353 of file pg_dumpall.c.

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

706 {
708  PGresult *res;
709  int i_rolname;
710  int i;
711 
712  if (server_version >= 90600)
714  "SELECT rolname "
715  "FROM %s "
716  "WHERE rolname !~ '^pg_' "
717  "ORDER BY 1", role_catalog);
718  else
720  "SELECT rolname "
721  "FROM %s "
722  "ORDER BY 1", role_catalog);
723 
724  res = executeQuery(conn, buf->data);
725 
726  i_rolname = PQfnumber(res, "rolname");
727 
728  if (PQntuples(res) > 0)
729  fprintf(OPF, "--\n-- Drop roles\n--\n\n");
730 
731  for (i = 0; i < PQntuples(res); i++)
732  {
733  const char *rolename;
734 
735  rolename = PQgetvalue(res, i, i_rolname);
736 
737  fprintf(OPF, "DROP ROLE %s%s;\n",
738  if_exists ? "IF EXISTS " : "",
739  fmtId(rolename));
740  }
741 
742  PQclear(res);
744 
745  fprintf(OPF, "\n\n");
746 }
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3549
static char role_catalog[10]
Definition: pg_dumpall.c:116
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 1214 of file pg_dumpall.c.

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

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

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

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

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

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

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

1930 {
1931  char buf[64];
1932  time_t now = time(NULL);
1933 
1934  if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
1935  fprintf(OPF, "-- %s %s\n\n", msg, buf);
1936 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
#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 1400 of file pg_dumpall.c.

1401 {
1403  PGresult *res;
1404 
1405  printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1406  "WHERE setdatabase = 0 AND setrole = "
1407  "(SELECT oid FROM %s WHERE rolname = ",
1408  role_catalog);
1410  appendPQExpBufferChar(buf, ')');
1411 
1412  res = executeQuery(conn, buf->data);
1413 
1414  if (PQntuples(res) > 0)
1415  fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", username);
1416 
1417  for (int i = 0; i < PQntuples(res); i++)
1418  {
1421  "ROLE", username, NULL, NULL,
1422  buf);
1423  fprintf(OPF, "%s", buf->data);
1424  }
1425 
1426  PQclear(res);
1427 
1429 }
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition: dumputils.c:823
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 1905 of file pg_dumpall.c.

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

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

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

1943 {
1944  unsigned char *ss = (unsigned char *) s;
1945 
1946  return hash_bytes(ss, strlen(s));
1947 }
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 634 of file pg_dumpall.c.

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

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

◆ read_dumpall_filters()

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

Definition at line 1959 of file pg_dumpall.c.

1960 {
1961  FilterStateData fstate;
1962  char *objname;
1963  FilterCommandType comtype;
1964  FilterObjectType objtype;
1965 
1966  filter_init(&fstate, filename, exit);
1967 
1968  while (filter_read_item(&fstate, &objname, &comtype, &objtype))
1969  {
1970  if (comtype == FILTER_COMMAND_TYPE_INCLUDE)
1971  {
1972  pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
1973  "include",
1974  filter_object_type_name(objtype));
1975  exit_nicely(1);
1976  }
1977 
1978  switch (objtype)
1979  {
1981  break;
1992  pg_log_filter_error(&fstate, _("unsupported filter object"));
1993  exit_nicely(1);
1994  break;
1995 
1997  simple_string_list_append(pattern, objname);
1998  break;
1999  }
2000 
2001  if (objname)
2002  free(objname);
2003  }
2004 
2005  filter_free(&fstate);
2006 }
void filter_init(FilterStateData *fstate, const char *filename, exit_function f_exit)
Definition: filter.c:37
void filter_free(FilterStateData *fstate)
Definition: filter.c:61
bool filter_read_item(FilterStateData *fstate, char **objname, FilterCommandType *comtype, FilterObjectType *objtype)
Definition: filter.c:388
void pg_log_filter_error(FilterStateData *fstate, const char *fmt,...)
Definition: filter.c:155
const char * filter_object_type_name(FilterObjectType fot)
Definition: filter.c:83
FilterObjectType
Definition: filter.h:48
@ FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN
Definition: filter.h:51
@ FILTER_OBJECT_TYPE_SCHEMA
Definition: filter.h:57
@ FILTER_OBJECT_TYPE_INDEX
Definition: filter.h:56
@ FILTER_OBJECT_TYPE_TRIGGER
Definition: filter.h:60
@ FILTER_OBJECT_TYPE_FOREIGN_DATA
Definition: filter.h:54
@ FILTER_OBJECT_TYPE_DATABASE
Definition: filter.h:52
@ FILTER_OBJECT_TYPE_FUNCTION
Definition: filter.h:55
@ FILTER_OBJECT_TYPE_TABLE_DATA
Definition: filter.h:50
@ FILTER_OBJECT_TYPE_NONE
Definition: filter.h:49
@ FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN
Definition: filter.h:59
@ FILTER_OBJECT_TYPE_EXTENSION
Definition: filter.h:53
@ FILTER_OBJECT_TYPE_TABLE
Definition: filter.h:58
FilterCommandType
Definition: filter.h:38
@ FILTER_COMMAND_TYPE_INCLUDE
Definition: filter.h:40
exit(1)

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

Referenced by main().

◆ runPgDump()

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

Definition at line 1582 of file pg_dumpall.c.

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

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

◆ column_inserts

int column_inserts = 0
static

Definition at line 97 of file pg_dumpall.c.

Referenced by main().

◆ connstr

◆ database_exclude_names

SimpleStringList database_exclude_names = {NULL, NULL}
static

Definition at line 124 of file pg_dumpall.c.

Referenced by dumpDatabases(), and main().

◆ database_exclude_patterns

SimpleStringList database_exclude_patterns = {NULL, NULL}
static

Definition at line 123 of file pg_dumpall.c.

Referenced by main().

◆ disable_dollar_quoting

int disable_dollar_quoting = 0
static

Definition at line 98 of file pg_dumpall.c.

Referenced by main().

◆ disable_triggers

int disable_triggers = 0
static

Definition at line 99 of file pg_dumpall.c.

Referenced by main().

◆ dosync

bool dosync = true
static

Definition at line 94 of file pg_dumpall.c.

Referenced by main().

◆ filename

char* filename = NULL
static

Definition at line 121 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(), filter_init(), first_dir_separator(), get_sock_dir(), GetConfFilesInDir(), hasSuffix(), importFile(), initTrie(), internal_load_library(), is_extension_control_filename(), is_extension_script_filename(), is_xlogfilename(), IsWalSummaryFilename(), last_dir_separator(), libpqrcv_readtimelinehistoryfile(), llvm_compile_module(), lo_export(), lo_import(), lo_import_internal(), lo_import_with_oid(), load_dh_file(), load_external_function(), load_file(), load_libraries(), load_tzoffsets(), log_locus_callback(), logfile_getname(), logfile_open(), logfile_rotate_dest(), LogicalTapeImport(), LogicalTapeSetCreate(), main(), make_incremental_rfile(), make_native_path(), make_outputdirs(), make_rfile(), next_field_expand(), NIImportAffixes(), NIImportDictionary(), NIImportOOAffixes(), open_auth_file(), parse_backup_label(), parse_extension_control_file(), parseIntFromText(), ParseTzFile(), parseVxidFromText(), parseXidFromText(), pg_log_generic_v(), pg_stat_file(), PLy_traceback(), process_file(), process_psqlrc_file(), process_queued_fetch_requests(), progress_update_filename(), read_binary_file(), read_dictionary(), read_dump_filters(), read_dumpall_filters(), read_extension_script_file(), read_pg_version_file(), read_restore_filters(), read_text_file(), read_whole_file(), readstoplist(), regcomp_auth_token(), run_diff(), runPgDump(), sendFileWithContent(), set_input(), set_stack_entry_location(), SetOutput(), setup_run_file(), shell_construct_command(), shell_run_command(), should_allow_existing_directory(), slurp_file(), splitTzLine(), SysLogger_Start(), tar_get_file_name(), 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 100 of file pg_dumpall.c.

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

◆ inserts

int inserts = 0
static

Definition at line 101 of file pg_dumpall.c.

Referenced by main().

◆ load_via_partition_root

int load_via_partition_root = 0
static

Definition at line 113 of file pg_dumpall.c.

Referenced by main().

◆ no_comments

int no_comments = 0
static

Definition at line 105 of file pg_dumpall.c.

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

◆ no_publications

int no_publications = 0
static

Definition at line 106 of file pg_dumpall.c.

Referenced by main().

◆ no_role_passwords

int no_role_passwords = 0
static

Definition at line 111 of file pg_dumpall.c.

Referenced by dumpRoles(), and main().

◆ no_security_labels

int no_security_labels = 0
static

Definition at line 107 of file pg_dumpall.c.

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

◆ no_subscriptions

int no_subscriptions = 0
static

Definition at line 108 of file pg_dumpall.c.

Referenced by main().

◆ no_table_access_method

int no_table_access_method = 0
static

Definition at line 102 of file pg_dumpall.c.

Referenced by main().

◆ no_tablespaces

int no_tablespaces = 0
static

Definition at line 103 of file pg_dumpall.c.

Referenced by main().

◆ no_toast_compression

int no_toast_compression = 0
static

Definition at line 109 of file pg_dumpall.c.

Referenced by main().

◆ no_unlogged_table_data

int no_unlogged_table_data = 0
static

Definition at line 110 of file pg_dumpall.c.

Referenced by main().

◆ on_conflict_do_nothing

int on_conflict_do_nothing = 0
static

Definition at line 114 of file pg_dumpall.c.

Referenced by main().

◆ OPF

◆ output_clean

bool output_clean = false
static

Definition at line 91 of file pg_dumpall.c.

Referenced by dumpDatabases(), and main().

◆ pg_dump_bin

char pg_dump_bin[MAXPGPATH]
static

Definition at line 87 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ pgdumpopts

PQExpBuffer pgdumpopts
static

Definition at line 89 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ progname

const char* progname
static

Definition at line 88 of file pg_dumpall.c.

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

◆ role_catalog

char role_catalog[10]
static

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

Referenced by dumpTablespaces(), and main().

◆ use_setsessauth

int use_setsessauth = 0
static

Definition at line 104 of file pg_dumpall.c.

Referenced by main().

◆ verbose

bool verbose = false
static

Definition at line 93 of file pg_dumpall.c.

Referenced by main().