PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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_perm.h"
#include "common/file_utils.h"
#include "common/hashfn_unstable.h"
#include "common/logging.h"
#include "common/string.h"
#include "connectdb.h"
#include "dumputils.h"
#include "fe_utils/option_utils.h"
#include "fe_utils/string_utils.h"
#include "filter.h"
#include "getopt_long.h"
#include "pg_backup_archiver.h"
#include "lib/simplehash.h"
Include dependency graph for pg_dumpall.c:

Go to the source code of this file.

Data Structures

struct  RoleNameEntry
 

Macros

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

Functions

static void help (void)
 
static void dropRoles (PGconn *conn)
 
static void dumpRoles (PGconn *conn)
 
static void dumpRoleMembership (PGconn *conn)
 
static void dumpRoleGUCPrivs (PGconn *conn)
 
static void dropTablespaces (PGconn *conn)
 
static void dumpTablespaces (PGconn *conn)
 
static void dropDBs (PGconn *conn)
 
static void dumpUserConfig (PGconn *conn, const char *username)
 
static void dumpDatabases (PGconn *conn)
 
static void dumpTimestamp (const char *msg)
 
static int runPgDump (const char *dbname, const char *create_opts, char *dbfile)
 
static void buildShSecLabels (PGconn *conn, const char *catalog_name, Oid objectId, const char *objtype, const char *objname, PQExpBuffer buffer)
 
static void executeCommand (PGconn *conn, const char *query)
 
static void check_for_invalid_global_names (PGconn *conn, SimpleStringList *database_exclude_names)
 
static void expand_dbname_patterns (PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
 
static void read_dumpall_filters (const char *filename, SimpleStringList *pattern)
 
static ArchiveFormat parseDumpFormat (const char *format)
 
static int createDumpId (void)
 
int main (int argc, char *argv[])
 

Variables

static char pg_dump_bin [MAXPGPATH]
 
static PQExpBuffer pgdumpopts
 
static const charconnstr = ""
 
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_policies = 0
 
static int no_publications = 0
 
static int no_security_labels = 0
 
static int no_data = 0
 
static int no_schema = 0
 
static int no_statistics = 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 with_statistics = 0
 
static int server_version
 
static int load_via_partition_root = 0
 
static int on_conflict_do_nothing = 0
 
static int statistics_only = 0
 
static int sequence_data = 0
 
static char role_catalog [10]
 
static FILEOPF
 
static charfilename = NULL
 
static SimpleStringList database_exclude_patterns = {NULL, NULL}
 
static SimpleStringList database_exclude_names = {NULL, NULL}
 
static charrestrict_key
 
static Archivefout = NULL
 
static int dumpIdVal = 0
 
static ArchiveFormat archDumpFormat = archNull
 
static const CatalogId nilCatalogId = {0, 0}
 

Macro Definition Documentation

◆ PG_AUTHID

#define PG_AUTHID   "pg_authid"

Definition at line 129 of file pg_dumpall.c.

◆ PG_ROLES

#define PG_ROLES   "pg_roles "

Definition at line 130 of file pg_dumpall.c.

◆ PGDUMP_VERSIONSTR

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

Definition at line 44 of file pg_dumpall.c.

◆ SH_DECLARE

#define SH_DECLARE

Definition at line 63 of file pg_dumpall.c.

◆ SH_DEFINE

#define SH_DEFINE

Definition at line 64 of file pg_dumpall.c.

◆ SH_ELEMENT_TYPE

#define SH_ELEMENT_TYPE   RoleNameEntry

Definition at line 54 of file pg_dumpall.c.

◆ SH_EQUAL

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

Definition at line 58 of file pg_dumpall.c.

◆ SH_GET_HASH

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

Definition at line 60 of file pg_dumpall.c.

◆ SH_HASH_KEY

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

Definition at line 57 of file pg_dumpall.c.

◆ SH_KEY

#define SH_KEY   rolename

Definition at line 56 of file pg_dumpall.c.

◆ SH_KEY_TYPE

#define SH_KEY_TYPE   char *

Definition at line 55 of file pg_dumpall.c.

◆ SH_PREFIX

#define SH_PREFIX   rolename

Definition at line 53 of file pg_dumpall.c.

◆ SH_RAW_ALLOCATOR

#define SH_RAW_ALLOCATOR   pg_malloc0

Definition at line 62 of file pg_dumpall.c.

◆ SH_SCOPE

#define SH_SCOPE   static inline

Definition at line 61 of file pg_dumpall.c.

◆ SH_STORE_HASH

#define SH_STORE_HASH

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

2222{
2224 PGresult *res;
2225
2226 buildShSecLabelQuery(catalog_name, objectId, sql);
2227 res = executeQuery(conn, sql->data);
2228 emitShSecLabels(conn, res, buffer, objtype, objname);
2229
2230 PQclear(res);
2231 destroyPQExpBuffer(sql);
2232}
PGresult * executeQuery(PGconn *conn, const char *query)
Definition connectdb.c:278
void buildShSecLabelQuery(const char *catalog_name, Oid objectId, PQExpBuffer sql)
Definition dumputils.c:678
void emitShSecLabels(PGconn *conn, PGresult *res, PQExpBuffer buffer, const char *objtype, const char *objname)
Definition dumputils.c:696
#define PQclear
PQExpBuffer createPQExpBuffer(void)
Definition pqexpbuffer.c:72
void destroyPQExpBuffer(PQExpBuffer str)
static int fb(int x)
PGconn * conn
Definition streamutil.c:52

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

Referenced by dumpRoles(), and dumpTablespaces().

◆ check_for_invalid_global_names()

static void check_for_invalid_global_names ( PGconn conn,
SimpleStringList database_exclude_names 
)
static

Definition at line 2270 of file pg_dumpall.c.

2272{
2273 PGresult *res;
2274 int i;
2275 PQExpBuffer names;
2276 int count = 0;
2277
2278 res = executeQuery(conn,
2279 "SELECT datname AS objname, 'database' AS objtype "
2280 "FROM pg_catalog.pg_database "
2281 "WHERE datallowconn AND datconnlimit != -2 "
2282 "UNION ALL "
2283 "SELECT rolname AS objname, 'role' AS objtype "
2284 "FROM pg_catalog.pg_roles "
2285 "UNION ALL "
2286 "SELECT spcname AS objname, 'tablespace' AS objtype "
2287 "FROM pg_catalog.pg_tablespace");
2288
2289 names = createPQExpBuffer();
2290
2291 for (i = 0; i < PQntuples(res); i++)
2292 {
2293 char *objname = PQgetvalue(res, i, 0);
2294 char *objtype = PQgetvalue(res, i, 1);
2295
2296 /* Skip excluded databases since they won't be in map.dat */
2297 if (strcmp(objtype, "database") == 0 &&
2299 continue;
2300
2301 if (strpbrk(objname, "\n\r"))
2302 {
2303 appendPQExpBuffer(names, " %s: \"", objtype);
2304 for (char *p = objname; *p; p++)
2305 {
2306 if (*p == '\n')
2307 appendPQExpBufferStr(names, "\\n");
2308 else if (*p == '\r')
2309 appendPQExpBufferStr(names, "\\r");
2310 else
2311 appendPQExpBufferChar(names, *p);
2312 }
2313 appendPQExpBufferStr(names, "\"\n");
2314 count++;
2315 }
2316 }
2317
2318 PQclear(res);
2319
2320 if (count > 0)
2321 pg_fatal("database, role, or tablespace names contain a newline or carriage return character, which is not supported in non-plain-text dumps:\n%s",
2322 names->data);
2323
2324 destroyPQExpBuffer(names);
2325}
int i
Definition isn.c:77
#define PQgetvalue
#define PQntuples
#define pg_fatal(...)
static SimpleStringList database_exclude_names
Definition pg_dumpall.c:136
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferChar(PQExpBuffer str, char ch)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
bool simple_string_list_member(SimpleStringList *list, const char *val)
Definition simple_list.c:87

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), conn, createPQExpBuffer(), PQExpBufferData::data, database_exclude_names, destroyPQExpBuffer(), executeQuery(), fb(), i, pg_fatal, PQclear, PQgetvalue, PQntuples, and simple_string_list_member().

Referenced by main().

◆ createDumpId()

static int createDumpId ( void  )
static

Definition at line 2439 of file pg_dumpall.c.

2440{
2441 return ++dumpIdVal;
2442}
static int dumpIdVal
Definition pg_dumpall.c:140

References dumpIdVal.

Referenced by dropDBs(), dropRoles(), dropTablespaces(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpTablespaces(), dumpUserConfig(), and main().

◆ dropDBs()

static void dropDBs ( PGconn conn)
static

Definition at line 1815 of file pg_dumpall.c.

1816{
1817 PGresult *res;
1818 int i;
1819
1820 /*
1821 * Skip databases marked not datallowconn, since we'd be unable to connect
1822 * to them anyway. This must agree with dumpDatabases().
1823 */
1824 res = executeQuery(conn,
1825 "SELECT datname "
1826 "FROM pg_database d "
1827 "WHERE datallowconn AND datconnlimit != -2 "
1828 "ORDER BY datname");
1829
1830 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1831 fprintf(OPF, "--\n-- Drop databases (except postgres and template1)\n--\n\n");
1832
1833 for (i = 0; i < PQntuples(res); i++)
1834 {
1835 char *dbname = PQgetvalue(res, i, 0);
1837
1838 /*
1839 * Skip "postgres" and "template1"; dumpDatabases() will deal with
1840 * them specially. Also, be sure to skip "template0", even if for
1841 * some reason it's not marked !datallowconn.
1842 */
1843 if (strcmp(dbname, "template1") != 0 &&
1844 strcmp(dbname, "template0") != 0 &&
1845 strcmp(dbname, "postgres") != 0)
1846 {
1847 if (archDumpFormat == archNull)
1848 {
1849 appendPQExpBuffer(delQry, "DROP DATABASE %s%s;\n",
1850 if_exists ? "IF EXISTS " : "",
1851 fmtId(dbname));
1852 fprintf(OPF, "%s", delQry->data);
1853 }
1854 else
1855 {
1856 appendPQExpBuffer(delQry, "DROP DATABASE IF EXISTS %s;\n",
1857 fmtId(dbname));
1858
1860 nilCatalogId, /* catalog ID */
1861 createDumpId(), /* dump ID */
1862 ARCHIVE_OPTS(.tag = psprintf("DATABASE %s", fmtId(dbname)),
1863 .description = "DROP_GLOBAL",
1864 .section = SECTION_PRE_DATA,
1865 .createStmt = delQry->data));
1866 }
1867
1869 }
1870 }
1871
1872 PQclear(res);
1873
1874 if (archDumpFormat == archNull)
1875 fprintf(OPF, "\n\n");
1876}
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
@ SECTION_PRE_DATA
Definition pg_backup.h:58
@ archNull
Definition pg_backup.h:44
TocEntry * ArchiveEntry(Archive *AHX, CatalogId catalogId, DumpId dumpId, ArchiveOpts *opts)
#define ARCHIVE_OPTS(...)
static const CatalogId nilCatalogId
Definition pg_dumpall.c:142
static int if_exists
Definition pg_dumpall.c:105
static ArchiveFormat archDumpFormat
Definition pg_dumpall.c:141
static int createDumpId(void)
static FILE * OPF
Definition pg_dumpall.c:132
static Archive * fout
Definition pg_dumpall.c:139
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
char * dbname
Definition streamutil.c:49
const char * fmtId(const char *rawid)
const char * description

References appendPQExpBuffer(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, conn, createDumpId(), createPQExpBuffer(), dbname, description, destroyPQExpBuffer(), executeQuery(), fb(), fmtId(), fout, fprintf, i, if_exists, nilCatalogId, OPF, PQclear, PQgetvalue, PQntuples, psprintf(), and SECTION_PRE_DATA.

Referenced by main().

◆ dropRoles()

static void dropRoles ( PGconn conn)
static

Definition at line 946 of file pg_dumpall.c.

947{
949 PGresult *res;
950 int i_rolname;
951 int i;
952
953 if (server_version >= 90600)
955 "SELECT rolname "
956 "FROM %s "
957 "WHERE rolname !~ '^pg_' "
958 "ORDER BY 1", role_catalog);
959 else
961 "SELECT rolname "
962 "FROM %s "
963 "ORDER BY 1", role_catalog);
964
965 res = executeQuery(conn, buf->data);
966
967 i_rolname = PQfnumber(res, "rolname");
968
969 if (PQntuples(res) > 0 && archDumpFormat == archNull)
970 fprintf(OPF, "--\n-- Drop roles\n--\n\n");
971
972 for (i = 0; i < PQntuples(res); i++)
973 {
974 const char *rolename;
976
977 rolename = PQgetvalue(res, i, i_rolname);
978
980 {
981 appendPQExpBuffer(delQry, "DROP ROLE %s%s;\n",
982 if_exists ? "IF EXISTS " : "",
983 fmtId(rolename));
984 fprintf(OPF, "%s", delQry->data);
985 }
986 else
987 {
988 appendPQExpBuffer(delQry, "DROP ROLE IF EXISTS %s;\n",
989 fmtId(rolename));
990
992 nilCatalogId, /* catalog ID */
993 createDumpId(), /* dump ID */
994 ARCHIVE_OPTS(.tag = psprintf("ROLE %s", fmtId(rolename)),
995 .description = "DROP_GLOBAL",
996 .section = SECTION_PRE_DATA,
997 .createStmt = delQry->data));
998 }
999
1001 }
1002
1003 PQclear(res);
1005
1006 if (archDumpFormat == archNull)
1007 fprintf(OPF, "\n\n");
1008}
int PQfnumber(const PGresult *res, const char *field_name)
Definition fe-exec.c:3606
static int server_version
Definition pg_dumpall.c:122
static char role_catalog[10]
Definition pg_dumpall.c:128
static char buf[DEFAULT_XLOG_SEG_SIZE]
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)

References appendPQExpBuffer(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, buf, conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), fb(), fmtId(), fout, fprintf, i, if_exists, nilCatalogId, OPF, PQclear, PQfnumber(), PQgetvalue, PQntuples, printfPQExpBuffer(), psprintf(), role_catalog, SECTION_PRE_DATA, and server_version.

Referenced by main().

◆ dropTablespaces()

static void dropTablespaces ( PGconn conn)
static

Definition at line 1608 of file pg_dumpall.c.

1609{
1610 PGresult *res;
1611 int i;
1612
1613 /*
1614 * Get all tablespaces except built-in ones (which we assume are named
1615 * pg_xxx)
1616 */
1617 res = executeQuery(conn, "SELECT spcname "
1618 "FROM pg_catalog.pg_tablespace "
1619 "WHERE spcname !~ '^pg_' "
1620 "ORDER BY 1");
1621
1622 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1623 fprintf(OPF, "--\n-- Drop tablespaces\n--\n\n");
1624
1625 for (i = 0; i < PQntuples(res); i++)
1626 {
1627 char *spcname = PQgetvalue(res, i, 0);
1629
1630 if (archDumpFormat == archNull)
1631 {
1632 appendPQExpBuffer(delQry, "DROP TABLESPACE %s%s;\n",
1633 if_exists ? "IF EXISTS " : "",
1634 fmtId(spcname));
1635 fprintf(OPF, "%s", delQry->data);
1636 }
1637 else
1638 {
1639 appendPQExpBuffer(delQry, "DROP TABLESPACE IF EXISTS %s;\n",
1640 fmtId(spcname));
1642 nilCatalogId, /* catalog ID */
1643 createDumpId(), /* dump ID */
1644 ARCHIVE_OPTS(.tag = psprintf("TABLESPACE %s", fmtId(spcname)),
1645 .description = "DROP_GLOBAL",
1646 .section = SECTION_PRE_DATA,
1647 .createStmt = delQry->data));
1648 }
1649
1651 }
1652
1653 PQclear(res);
1654
1655 if (archDumpFormat == archNull)
1656 fprintf(OPF, "\n\n");
1657}

References appendPQExpBuffer(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), fb(), fmtId(), fout, fprintf, i, if_exists, nilCatalogId, OPF, PQclear, PQgetvalue, PQntuples, psprintf(), and SECTION_PRE_DATA.

Referenced by main().

◆ dumpDatabases()

static void dumpDatabases ( PGconn conn)
static

Definition at line 1988 of file pg_dumpall.c.

1989{
1990 PGresult *res;
1991 int i;
1992 char db_subdir[MAXPGPATH];
1993 char dbfilepath[MAXPGPATH];
1994 FILE *map_file = NULL;
1995
1996 /*
1997 * Skip databases marked not datallowconn, since we'd be unable to connect
1998 * to them anyway. This must agree with dropDBs().
1999 *
2000 * We arrange for template1 to be processed first, then we process other
2001 * DBs in alphabetical order. If we just did them all alphabetically, we
2002 * might find ourselves trying to drop the "postgres" database while still
2003 * connected to it. This makes trying to run the restore script while
2004 * connected to "template1" a bad idea, but there's no fixed order that
2005 * doesn't have some failure mode with --clean.
2006 */
2007 res = executeQuery(conn,
2008 "SELECT datname, oid "
2009 "FROM pg_database d "
2010 "WHERE datallowconn AND datconnlimit != -2 "
2011 "ORDER BY (datname <> 'template1'), datname");
2012
2013 if (PQntuples(res) > 0 && archDumpFormat == archNull)
2014 fprintf(OPF, "--\n-- Databases\n--\n\n");
2015
2016 /*
2017 * If directory/tar/custom format is specified, create a subdirectory
2018 * under the main directory and each database dump file or subdirectory
2019 * will be created in that subdirectory by pg_dump.
2020 */
2021 if (archDumpFormat != archNull)
2022 {
2024
2025 snprintf(db_subdir, MAXPGPATH, "%s/databases", filename);
2026
2027 /* Create a subdirectory with 'databases' name under main directory. */
2029 pg_fatal("could not create directory \"%s\": %m", db_subdir);
2030
2031 snprintf(map_file_path, MAXPGPATH, "%s/map.dat", filename);
2032
2033 /* Create a map file (to store dboid and dbname) */
2035 if (!map_file)
2036 pg_fatal("could not open file \"%s\": %m", map_file_path);
2037
2039 "#################################################################\n"
2040 "# map.dat\n"
2041 "#\n"
2042 "# This file maps oids to database names\n"
2043 "#\n"
2044 "# pg_restore will restore all the databases listed here, unless\n"
2045 "# otherwise excluded. You can also inhibit restoration of a\n"
2046 "# database by removing the line or commenting out the line with\n"
2047 "# a # mark.\n"
2048 "#################################################################\n");
2049 }
2050
2051 for (i = 0; i < PQntuples(res); i++)
2052 {
2053 char *dbname = PQgetvalue(res, i, 0);
2054 char *sanitized;
2055 char *oid = PQgetvalue(res, i, 1);
2056 const char *create_opts = "";
2057 int ret;
2058
2059 /* Skip template0, even if it's not marked !datallowconn. */
2060 if (strcmp(dbname, "template0") == 0)
2061 continue;
2062
2063 /* Skip any explicitly excluded database */
2065 {
2066 pg_log_info("excluding database \"%s\"", dbname);
2067 continue;
2068 }
2069
2070 pg_log_info("dumping database \"%s\"", dbname);
2071
2073
2074 if (archDumpFormat == archNull)
2075 fprintf(OPF, "--\n-- Database \"%s\" dump\n--\n\n", sanitized);
2076
2077 free(sanitized);
2078
2079 /*
2080 * We assume that "template1" and "postgres" already exist in the
2081 * target installation. dropDBs() won't have removed them, for fear
2082 * of removing the DB the restore script is initially connected to. If
2083 * --clean was specified, tell pg_dump to drop and recreate them;
2084 * otherwise we'll merely restore their contents. Other databases
2085 * should simply be created.
2086 */
2087 if (strcmp(dbname, "template1") == 0 || strcmp(dbname, "postgres") == 0)
2088 {
2089 if (output_clean)
2090 create_opts = "--clean --create";
2091 /* Since pg_dump won't emit a \connect command, we must */
2092 else if (archDumpFormat == archNull)
2093 fprintf(OPF, "\\connect %s\n\n", dbname);
2094 else
2095 create_opts = "";
2096 }
2097 else
2098 create_opts = "--create";
2099
2101 fclose(OPF);
2102
2103 /*
2104 * If this is not a plain format dump, then append dboid and dbname to
2105 * the map.dat file.
2106 */
2107 if (archDumpFormat != archNull)
2108 {
2110 snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\".dmp", db_subdir, oid);
2111 else if (archDumpFormat == archTar)
2112 snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\".tar", db_subdir, oid);
2113 else
2114 snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\"", db_subdir, oid);
2115
2116 /* Put one line entry for dboid and dbname in map file. */
2117 fprintf(map_file, "%s %s\n", oid, dbname);
2118 }
2119
2121 if (ret != 0)
2122 pg_fatal("pg_dump failed on database \"%s\", exiting", dbname);
2123
2125 {
2127 if (!OPF)
2128 pg_fatal("could not re-open the output file \"%s\": %m",
2129 filename);
2130 }
2131 }
2132
2133 /* Close map file */
2134 if (archDumpFormat != archNull)
2136
2137 PQclear(res);
2138}
#define PG_BINARY_A
Definition c.h:1338
#define PG_BINARY_W
Definition c.h:1340
char * sanitize_line(const char *str, bool want_hyphen)
Definition dumputils.c:52
int pg_dir_create_mode
Definition file_perm.c:18
#define pg_log_info(...)
Definition logging.h:124
@ archTar
Definition pg_backup.h:43
@ archCustom
Definition pg_backup.h:42
#define MAXPGPATH
static int runPgDump(const char *dbname, const char *create_opts, char *dbfile)
static bool output_clean
Definition pg_dumpall.c:96
static char * filename
Definition pg_dumpall.c:133
#define snprintf
Definition port.h:260
#define free(a)
#define mkdir(a, b)
Definition win32_port.h:80

References archCustom, archDumpFormat, archNull, archTar, conn, database_exclude_names, dbname, executeQuery(), fb(), filename, fprintf, free, i, MAXPGPATH, mkdir, OPF, output_clean, PG_BINARY_A, PG_BINARY_W, pg_dir_create_mode, pg_fatal, pg_log_info, PQclear, PQgetvalue, PQntuples, runPgDump(), sanitize_line(), simple_string_list_member(), and snprintf.

Referenced by main().

◆ dumpRoleGUCPrivs()

static void dumpRoleGUCPrivs ( PGconn conn)
static

Definition at line 1542 of file pg_dumpall.c.

1543{
1544 PGresult *res;
1545 int i;
1546
1547 /*
1548 * Get all parameters that have non-default acls defined.
1549 */
1550 res = executeQuery(conn, "SELECT parname, "
1551 "pg_catalog.pg_get_userbyid(" CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS parowner, "
1552 "paracl, "
1553 "pg_catalog.acldefault('p', " CppAsString2(BOOTSTRAP_SUPERUSERID) ") AS acldefault "
1554 "FROM pg_catalog.pg_parameter_acl "
1555 "ORDER BY 1");
1556
1557 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1558 fprintf(OPF, "--\n-- Role privileges on configuration parameters\n--\n\n");
1559
1560 for (i = 0; i < PQntuples(res); i++)
1561 {
1563 char *parname = PQgetvalue(res, i, 0);
1564 char *parowner = PQgetvalue(res, i, 1);
1565 char *paracl = PQgetvalue(res, i, 2);
1566 char *acldefault = PQgetvalue(res, i, 3);
1567 char *fparname;
1568
1569 /* needed for buildACLCommands() */
1571
1572 if (!buildACLCommands(fparname, NULL, NULL, "PARAMETER",
1575 {
1576 pg_log_error("could not parse ACL list (%s) for parameter \"%s\"",
1577 paracl, parname);
1578 PQfinish(conn);
1579 exit_nicely(1);
1580 }
1581
1582 if (archDumpFormat == archNull)
1583 fprintf(OPF, "%s", buf->data);
1584 else
1586 nilCatalogId, /* catalog ID */
1587 createDumpId(), /* dump ID */
1588 ARCHIVE_OPTS(.tag = psprintf("ROLE %s", fmtId(parowner)),
1589 .description = "ROLE PROPERTIES",
1590 .section = SECTION_PRE_DATA,
1591 .createStmt = buf->data));
1592
1593 free(fparname);
1595 }
1596
1597 PQclear(res);
1598
1599 if (archDumpFormat == archNull)
1600 fprintf(OPF, "\n\n");
1601}
Acl * acldefault(ObjectType objtype, Oid ownerId)
Definition acl.c:816
#define CppAsString2(x)
Definition c.h:461
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:104
void PQfinish(PGconn *conn)
char * pg_strdup(const char *in)
Definition fe_memutils.c:85
#define pg_log_error(...)
Definition logging.h:106
void exit_nicely(int code)

References acldefault(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, buf, buildACLCommands(), conn, CppAsString2, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), exit_nicely(), fb(), fmtId(), fout, fprintf, free, i, nilCatalogId, OPF, pg_log_error, pg_strdup(), PQclear, PQfinish(), PQgetvalue, PQntuples, psprintf(), SECTION_PRE_DATA, and server_version.

Referenced by main().

◆ dumpRoleMembership()

static void dumpRoleMembership ( PGconn conn)
static

Definition at line 1265 of file pg_dumpall.c.

1266{
1270 PGresult *res;
1271 int start = 0,
1272 end,
1273 total;
1274 bool dump_grantors;
1275 bool dump_grant_options;
1276 int i_role;
1277 int i_member;
1278 int i_grantor;
1279 int i_roleid;
1280 int i_memberid;
1281 int i_grantorid;
1282 int i_admin_option;
1283 int i_inherit_option;
1284 int i_set_option;
1285
1286 /*
1287 * Previous versions of PostgreSQL didn't used to track the grantor very
1288 * carefully in the backend, and the grantor could be any user even if
1289 * they didn't have ADMIN OPTION on the role, or a user that no longer
1290 * existed. To avoid dump and restore failures, don't dump the grantor
1291 * when talking to an old server version.
1292 *
1293 * Also, in older versions the roleid and/or member could be role OIDs
1294 * that no longer exist. If we find such cases, print a warning and skip
1295 * the entry.
1296 */
1297 dump_grantors = (server_version >= 160000);
1298
1299 /*
1300 * Previous versions of PostgreSQL also did not have grant-level options.
1301 */
1302 dump_grant_options = (server_version >= 160000);
1303
1304 /* Generate and execute query. */
1305 printfPQExpBuffer(buf, "SELECT ur.rolname AS role, "
1306 "um.rolname AS member, "
1307 "ug.rolname AS grantor, "
1308 "a.roleid AS roleid, "
1309 "a.member AS memberid, "
1310 "a.grantor AS grantorid, "
1311 "a.admin_option");
1313 appendPQExpBufferStr(buf, ", a.inherit_option, a.set_option");
1314 appendPQExpBuffer(buf, " FROM pg_auth_members a "
1315 "LEFT JOIN %s ur on ur.oid = a.roleid "
1316 "LEFT JOIN %s um on um.oid = a.member "
1317 "LEFT JOIN %s ug on ug.oid = a.grantor "
1318 "WHERE NOT (ur.rolname ~ '^pg_' AND um.rolname ~ '^pg_')"
1319 "ORDER BY 1,2,3", role_catalog, role_catalog, role_catalog);
1320 res = executeQuery(conn, buf->data);
1321 i_role = PQfnumber(res, "role");
1322 i_member = PQfnumber(res, "member");
1323 i_grantor = PQfnumber(res, "grantor");
1324 i_roleid = PQfnumber(res, "roleid");
1325 i_memberid = PQfnumber(res, "memberid");
1326 i_grantorid = PQfnumber(res, "grantorid");
1327 i_admin_option = PQfnumber(res, "admin_option");
1328 i_inherit_option = PQfnumber(res, "inherit_option");
1329 i_set_option = PQfnumber(res, "set_option");
1330
1331 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1332 fprintf(OPF, "--\n-- Role memberships\n--\n\n");
1333
1334 /*
1335 * We can't dump these GRANT commands in arbitrary order, because a role
1336 * that is named as a grantor must already have ADMIN OPTION on the role
1337 * for which it is granting permissions, except for the bootstrap
1338 * superuser, who can always be named as the grantor.
1339 *
1340 * We handle this by considering these grants role by role. For each role,
1341 * we initially consider the only allowable grantor to be the bootstrap
1342 * superuser. Every time we grant ADMIN OPTION on the role to some user,
1343 * that user also becomes an allowable grantor. We make repeated passes
1344 * over the grants for the role, each time dumping those whose grantors
1345 * are allowable and which we haven't done yet. Eventually this should let
1346 * us dump all the grants.
1347 */
1348 total = PQntuples(res);
1349 while (start < total)
1350 {
1351 char *role = PQgetvalue(res, start, i_role);
1352 int i;
1353 bool *done;
1354 int remaining;
1355 int prev_remaining = 0;
1357
1358 /* If we hit a null roleid, we're done (nulls sort to the end). */
1359 if (PQgetisnull(res, start, i_role))
1360 {
1361 /* translator: %s represents a numeric role OID */
1362 pg_log_warning("ignoring role grant for missing role with OID %s",
1363 PQgetvalue(res, start, i_roleid));
1364 break;
1365 }
1366
1367 /* All memberships for a single role should be adjacent. */
1368 for (end = start; end < total; ++end)
1369 {
1370 char *otherrole;
1371
1372 otherrole = PQgetvalue(res, end, i_role);
1373 if (strcmp(role, otherrole) != 0)
1374 break;
1375 }
1376
1377 remaining = end - start;
1378 done = pg_malloc0_array(bool, remaining);
1379
1380 /*
1381 * We use a hashtable to track the member names that have been granted
1382 * admin option. Usually a hashtable is overkill, but sometimes not.
1383 */
1385
1386 /*
1387 * Make repeated passes over the grants for this role until all have
1388 * been dumped.
1389 */
1390 while (remaining > 0)
1391 {
1392 /*
1393 * We should make progress on every iteration, because a notional
1394 * graph whose vertices are grants and whose edges point from
1395 * grantors to members should be connected and acyclic. If we fail
1396 * to make progress, either we or the server have messed up.
1397 */
1399 {
1400 pg_log_error("could not find a legal dump ordering for memberships in role \"%s\"",
1401 role);
1402 PQfinish(conn);
1403 exit_nicely(1);
1404 }
1406
1407 /* Make one pass over the grants for this role. */
1408 for (i = start; i < end; ++i)
1409 {
1410 char *member;
1411 char *grantorid;
1412 char *grantor = NULL;
1414 char *set_option = "true";
1415 char *admin_option;
1416 bool found;
1417
1418 /* If we already did this grant, don't do it again. */
1419 if (done[i - start])
1420 continue;
1421
1422 /* Complain about, then ignore, entries for unknown members. */
1423 if (PQgetisnull(res, i, i_member))
1424 {
1425 /* translator: %s represents a numeric role OID */
1426 pg_log_warning("ignoring role grant to missing role with OID %s",
1427 PQgetvalue(res, i, i_memberid));
1428 done[i - start] = true;
1429 --remaining;
1430 continue;
1431 }
1432 member = PQgetvalue(res, i, i_member);
1433
1434 /* If the grantor is unknown, complain and dump without it. */
1437 {
1438 if (PQgetisnull(res, i, i_grantor))
1439 {
1440 /* translator: %s represents a numeric role OID */
1441 pg_log_warning("grant of role \"%s\" to \"%s\" has invalid grantor OID %s",
1442 role, member, grantorid);
1443 pg_log_warning_detail("This grant will be dumped without GRANTED BY.");
1444 dump_this_grantor = false;
1445 }
1446 else
1447 grantor = PQgetvalue(res, i, i_grantor);
1448 }
1449
1453
1454 /*
1455 * If we're not dumping the grantor or if the grantor is the
1456 * bootstrap superuser, it's fine to dump this now. Otherwise,
1457 * it's got to be someone who has already been granted ADMIN
1458 * OPTION.
1459 */
1460 if (dump_this_grantor &&
1462 rolename_lookup(ht, grantor) == NULL)
1463 continue;
1464
1465 /* Remember that we did this so that we don't do it again. */
1466 done[i - start] = true;
1467 --remaining;
1468
1469 /*
1470 * If ADMIN OPTION is being granted, remember that grants
1471 * listing this member as the grantor can now be dumped.
1472 */
1473 if (*admin_option == 't')
1474 rolename_insert(ht, member, &found);
1475
1476 /* Generate the actual GRANT statement. */
1479 appendPQExpBuffer(querybuf, "GRANT %s", fmtId(role));
1480 appendPQExpBuffer(querybuf, " TO %s", fmtId(member));
1481 if (*admin_option == 't')
1482 appendPQExpBufferStr(optbuf, "ADMIN OPTION");
1484 {
1485 char *inherit_option;
1486
1487 if (optbuf->data[0] != '\0')
1490 appendPQExpBuffer(optbuf, "INHERIT %s",
1491 *inherit_option == 't' ?
1492 "TRUE" : "FALSE");
1493 }
1494 if (*set_option != 't')
1495 {
1496 if (optbuf->data[0] != '\0')
1498 appendPQExpBufferStr(optbuf, "SET FALSE");
1499 }
1500 if (optbuf->data[0] != '\0')
1501 appendPQExpBuffer(querybuf, " WITH %s", optbuf->data);
1503 appendPQExpBuffer(querybuf, " GRANTED BY %s", fmtId(grantor));
1505
1506 if (archDumpFormat == archNull)
1507 fprintf(OPF, "%s", querybuf->data);
1508 else
1510 nilCatalogId, /* catalog ID */
1511 createDumpId(), /* dump ID */
1512 ARCHIVE_OPTS(.tag = psprintf("ROLE %s", fmtId(role)),
1513 .description = "ROLE PROPERTIES",
1514 .section = SECTION_PRE_DATA,
1515 .createStmt = querybuf->data));
1516 }
1517 }
1518
1520 pg_free(done);
1521 start = end;
1522 }
1523
1524 PQclear(res);
1528
1529 if (archDumpFormat == archNull)
1530 fprintf(OPF, "\n\n");
1531}
void set_option(char *arg)
Definition args.c:261
void pg_free(void *ptr)
#define pg_malloc0_array(type, count)
Definition fe_memutils.h:57
return str start
int remaining
Definition informix.c:692
#define PQgetisnull
#define pg_log_warning_detail(...)
Definition logging.h:118
#define pg_log_warning(...)
Definition pgfnames.c:24
#define atooid(x)
void resetPQExpBuffer(PQExpBuffer str)

References appendPQExpBuffer(), appendPQExpBufferStr(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, atooid, buf, conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), exit_nicely(), fb(), fmtId(), fout, fprintf, i, nilCatalogId, OPF, pg_free(), pg_log_error, pg_log_warning, pg_log_warning_detail, pg_malloc0_array, PQclear, PQfinish(), PQfnumber(), PQgetisnull, PQgetvalue, PQntuples, printfPQExpBuffer(), psprintf(), remaining, resetPQExpBuffer(), role_catalog, SECTION_PRE_DATA, server_version, set_option(), and start.

Referenced by main().

◆ dumpRoles()

static void dumpRoles ( PGconn conn)
static

Definition at line 1014 of file pg_dumpall.c.

1015{
1019 PGresult *res;
1020 int i_oid,
1021 i_rolname,
1022 i_rolsuper,
1034 int i;
1035
1036 /*
1037 * Notes: rolconfig is dumped later, and pg_authid must be used for
1038 * extracting rolcomment regardless of role_catalog.
1039 */
1040 if (server_version >= 90600)
1042 "SELECT oid, rolname, rolsuper, rolinherit, "
1043 "rolcreaterole, rolcreatedb, "
1044 "rolcanlogin, rolconnlimit, rolpassword, "
1045 "rolvaliduntil, rolreplication, rolbypassrls, "
1046 "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
1047 "rolname = current_user AS is_current_user "
1048 "FROM %s "
1049 "WHERE rolname !~ '^pg_' "
1050 "ORDER BY 2", role_catalog);
1051 else if (server_version >= 90500)
1053 "SELECT oid, rolname, rolsuper, rolinherit, "
1054 "rolcreaterole, rolcreatedb, "
1055 "rolcanlogin, rolconnlimit, rolpassword, "
1056 "rolvaliduntil, rolreplication, rolbypassrls, "
1057 "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
1058 "rolname = current_user AS is_current_user "
1059 "FROM %s "
1060 "ORDER BY 2", role_catalog);
1061 else
1063 "SELECT oid, rolname, rolsuper, rolinherit, "
1064 "rolcreaterole, rolcreatedb, "
1065 "rolcanlogin, rolconnlimit, rolpassword, "
1066 "rolvaliduntil, rolreplication, "
1067 "false as rolbypassrls, "
1068 "pg_catalog.shobj_description(oid, 'pg_authid') as rolcomment, "
1069 "rolname = current_user AS is_current_user "
1070 "FROM %s "
1071 "ORDER BY 2", role_catalog);
1072
1073 res = executeQuery(conn, buf->data);
1074
1075 i_oid = PQfnumber(res, "oid");
1076 i_rolname = PQfnumber(res, "rolname");
1077 i_rolsuper = PQfnumber(res, "rolsuper");
1078 i_rolinherit = PQfnumber(res, "rolinherit");
1079 i_rolcreaterole = PQfnumber(res, "rolcreaterole");
1080 i_rolcreatedb = PQfnumber(res, "rolcreatedb");
1081 i_rolcanlogin = PQfnumber(res, "rolcanlogin");
1082 i_rolconnlimit = PQfnumber(res, "rolconnlimit");
1083 i_rolpassword = PQfnumber(res, "rolpassword");
1084 i_rolvaliduntil = PQfnumber(res, "rolvaliduntil");
1085 i_rolreplication = PQfnumber(res, "rolreplication");
1086 i_rolbypassrls = PQfnumber(res, "rolbypassrls");
1087 i_rolcomment = PQfnumber(res, "rolcomment");
1088 i_is_current_user = PQfnumber(res, "is_current_user");
1089
1090 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1091 fprintf(OPF, "--\n-- Roles\n--\n\n");
1092
1093 for (i = 0; i < PQntuples(res); i++)
1094 {
1095 const char *rolename;
1096 Oid auth_oid;
1097
1098 auth_oid = atooid(PQgetvalue(res, i, i_oid));
1099 rolename = PQgetvalue(res, i, i_rolname);
1100
1101 if (strncmp(rolename, "pg_", 3) == 0)
1102 {
1103 pg_log_warning("role name starting with \"pg_\" skipped (%s)",
1104 rolename);
1105 continue;
1106 }
1107
1111
1112 if (binary_upgrade)
1113 {
1114 appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_authid.oid\n");
1116 "SELECT pg_catalog.binary_upgrade_set_next_pg_authid_oid('%u'::pg_catalog.oid);\n\n",
1117 auth_oid);
1118 }
1119
1120 /*
1121 * We dump CREATE ROLE followed by ALTER ROLE to ensure that the role
1122 * will acquire the right properties even if it already exists (ie, it
1123 * won't hurt for the CREATE to fail). This is particularly important
1124 * for the role we are connected as, since even with --clean we will
1125 * have failed to drop it. binary_upgrade cannot generate any errors,
1126 * so we assume the current role is already created.
1127 */
1128 if (!binary_upgrade ||
1129 strcmp(PQgetvalue(res, i, i_is_current_user), "f") == 0)
1130 appendPQExpBuffer(buf, "CREATE ROLE %s;\n", fmtId(rolename));
1131 appendPQExpBuffer(buf, "ALTER ROLE %s WITH", fmtId(rolename));
1132
1133 if (strcmp(PQgetvalue(res, i, i_rolsuper), "t") == 0)
1134 appendPQExpBufferStr(buf, " SUPERUSER");
1135 else
1136 appendPQExpBufferStr(buf, " NOSUPERUSER");
1137
1138 if (strcmp(PQgetvalue(res, i, i_rolinherit), "t") == 0)
1139 appendPQExpBufferStr(buf, " INHERIT");
1140 else
1141 appendPQExpBufferStr(buf, " NOINHERIT");
1142
1143 if (strcmp(PQgetvalue(res, i, i_rolcreaterole), "t") == 0)
1144 appendPQExpBufferStr(buf, " CREATEROLE");
1145 else
1146 appendPQExpBufferStr(buf, " NOCREATEROLE");
1147
1148 if (strcmp(PQgetvalue(res, i, i_rolcreatedb), "t") == 0)
1149 appendPQExpBufferStr(buf, " CREATEDB");
1150 else
1151 appendPQExpBufferStr(buf, " NOCREATEDB");
1152
1153 if (strcmp(PQgetvalue(res, i, i_rolcanlogin), "t") == 0)
1154 appendPQExpBufferStr(buf, " LOGIN");
1155 else
1156 appendPQExpBufferStr(buf, " NOLOGIN");
1157
1158 if (strcmp(PQgetvalue(res, i, i_rolreplication), "t") == 0)
1159 appendPQExpBufferStr(buf, " REPLICATION");
1160 else
1161 appendPQExpBufferStr(buf, " NOREPLICATION");
1162
1163 if (strcmp(PQgetvalue(res, i, i_rolbypassrls), "t") == 0)
1164 appendPQExpBufferStr(buf, " BYPASSRLS");
1165 else
1166 appendPQExpBufferStr(buf, " NOBYPASSRLS");
1167
1168 if (strcmp(PQgetvalue(res, i, i_rolconnlimit), "-1") != 0)
1169 appendPQExpBuffer(buf, " CONNECTION LIMIT %s",
1170 PQgetvalue(res, i, i_rolconnlimit));
1171
1172
1174 {
1175 appendPQExpBufferStr(buf, " PASSWORD ");
1177 }
1178
1179 if (!PQgetisnull(res, i, i_rolvaliduntil))
1180 appendPQExpBuffer(buf, " VALID UNTIL '%s'",
1182
1183 appendPQExpBufferStr(buf, ";\n");
1184
1185 if (!no_comments && !PQgetisnull(res, i, i_rolcomment))
1186 {
1187 appendPQExpBuffer(comment_buf, "COMMENT ON ROLE %s IS ", fmtId(rolename));
1190 }
1191
1192 if (!no_security_labels)
1193 buildShSecLabels(conn, "pg_authid", auth_oid,
1194 "ROLE", rolename,
1195 seclabel_buf);
1196
1197 if (archDumpFormat == archNull)
1198 {
1199 fprintf(OPF, "%s", buf->data);
1200 fprintf(OPF, "%s", comment_buf->data);
1201
1202 if (seclabel_buf->data[0] != '\0')
1203 fprintf(OPF, "%s", seclabel_buf->data);
1204 }
1205 else
1206 {
1207 char *tag = psprintf("ROLE %s", fmtId(rolename));
1208
1210 nilCatalogId, /* catalog ID */
1211 createDumpId(), /* dump ID */
1212 ARCHIVE_OPTS(.tag = tag,
1213 .description = "ROLE",
1214 .section = SECTION_PRE_DATA,
1215 .createStmt = buf->data));
1216 if (comment_buf->data[0] != '\0')
1218 nilCatalogId, /* catalog ID */
1219 createDumpId(), /* dump ID */
1220 ARCHIVE_OPTS(.tag = tag,
1221 .description = "COMMENT",
1222 .section = SECTION_PRE_DATA,
1223 .createStmt = comment_buf->data));
1224
1225 if (seclabel_buf->data[0] != '\0')
1227 nilCatalogId, /* catalog ID */
1228 createDumpId(), /* dump ID */
1229 ARCHIVE_OPTS(.tag = tag,
1230 .description = "SECURITY LABEL",
1231 .section = SECTION_PRE_DATA,
1232 .createStmt = seclabel_buf->data));
1233 }
1234 }
1235
1236 /*
1237 * Dump configuration settings for roles after all roles have been dumped.
1238 * We do it this way because config settings for roles could mention the
1239 * names of other roles.
1240 */
1241 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1242 fprintf(OPF, "\n--\n-- User Configurations\n--\n");
1243
1244 for (i = 0; i < PQntuples(res); i++)
1246
1247 PQclear(res);
1248
1249 if (archDumpFormat == archNull)
1250 fprintf(OPF, "\n\n");
1251
1255}
static int no_role_passwords
Definition pg_dumpall.c:120
static int binary_upgrade
Definition pg_dumpall.c:101
static void dumpUserConfig(PGconn *conn, const char *username)
static int no_comments
Definition pg_dumpall.c:110
static int no_security_labels
Definition pg_dumpall.c:113
static void buildShSecLabels(PGconn *conn, const char *catalog_name, Oid objectId, const char *objtype, const char *objname, PQExpBuffer buffer)
unsigned int Oid
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)

References appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, atooid, binary_upgrade, buf, buildShSecLabels(), conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), dumpUserConfig(), executeQuery(), fb(), fmtId(), fout, fprintf, i, nilCatalogId, no_comments, no_role_passwords, no_security_labels, OPF, pg_log_warning, PQclear, PQfnumber(), PQgetisnull, PQgetvalue, PQntuples, printfPQExpBuffer(), psprintf(), resetPQExpBuffer(), role_catalog, SECTION_PRE_DATA, and server_version.

Referenced by main().

◆ dumpTablespaces()

static void dumpTablespaces ( PGconn conn)
static

Definition at line 1663 of file pg_dumpall.c.

1664{
1665 PGresult *res;
1668 int i;
1669
1670 /*
1671 * Get all tablespaces except built-in ones (which we assume are named
1672 * pg_xxx)
1673 */
1674 res = executeQuery(conn, "SELECT oid, spcname, "
1675 "pg_catalog.pg_get_userbyid(spcowner) AS spcowner, "
1676 "pg_catalog.pg_tablespace_location(oid), "
1677 "spcacl, acldefault('t', spcowner) AS acldefault, "
1678 "array_to_string(spcoptions, ', '),"
1679 "pg_catalog.shobj_description(oid, 'pg_tablespace') "
1680 "FROM pg_catalog.pg_tablespace "
1681 "WHERE spcname !~ '^pg_' "
1682 "ORDER BY 1");
1683
1684 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1685 fprintf(OPF, "--\n-- Tablespaces\n--\n\n");
1686
1687 for (i = 0; i < PQntuples(res); i++)
1688 {
1690 Oid spcoid = atooid(PQgetvalue(res, i, 0));
1691 char *spcname = PQgetvalue(res, i, 1);
1692 char *spcowner = PQgetvalue(res, i, 2);
1693 char *spclocation = PQgetvalue(res, i, 3);
1694 char *spcacl = PQgetvalue(res, i, 4);
1695 char *acldefault = PQgetvalue(res, i, 5);
1696 char *spcoptions = PQgetvalue(res, i, 6);
1697 char *spccomment = PQgetvalue(res, i, 7);
1698 char *fspcname;
1699
1700 /* needed for buildACLCommands() */
1702
1705
1706 if (binary_upgrade)
1707 {
1708 appendPQExpBufferStr(buf, "\n-- For binary upgrade, must preserve pg_tablespace oid\n");
1709 appendPQExpBuffer(buf, "SELECT pg_catalog.binary_upgrade_set_next_pg_tablespace_oid('%u'::pg_catalog.oid);\n", spcoid);
1710 }
1711
1712 appendPQExpBuffer(buf, "CREATE TABLESPACE %s", fspcname);
1713 appendPQExpBuffer(buf, " OWNER %s", fmtId(spcowner));
1714
1715 appendPQExpBufferStr(buf, " LOCATION ");
1716
1717 /*
1718 * In-place tablespaces use a relative path, and need to be dumped
1719 * with an empty string as location.
1720 */
1723 else
1725
1726 appendPQExpBufferStr(buf, ";\n");
1727
1728 if (spcoptions && spcoptions[0] != '\0')
1729 appendPQExpBuffer(buf, "ALTER TABLESPACE %s SET (%s);\n",
1731
1732 /* tablespaces can't have initprivs */
1733
1734 if (!skip_acls &&
1735 !buildACLCommands(fspcname, NULL, NULL, "TABLESPACE",
1738 {
1739 pg_log_error("could not parse ACL list (%s) for tablespace \"%s\"",
1740 spcacl, spcname);
1741 PQfinish(conn);
1742 exit_nicely(1);
1743 }
1744
1745 if (!no_comments && spccomment && spccomment[0] != '\0')
1746 {
1747 appendPQExpBuffer(comment_buf, "COMMENT ON TABLESPACE %s IS ", fspcname);
1750 }
1751
1752 if (!no_security_labels)
1753 buildShSecLabels(conn, "pg_tablespace", spcoid,
1754 "TABLESPACE", spcname,
1755 seclabel_buf);
1756
1757 if (archDumpFormat == archNull)
1758 {
1759 fprintf(OPF, "%s", buf->data);
1760
1761 if (comment_buf->data[0] != '\0')
1762 fprintf(OPF, "%s", comment_buf->data);
1763
1764 if (seclabel_buf->data[0] != '\0')
1765 fprintf(OPF, "%s", seclabel_buf->data);
1766 }
1767 else
1768 {
1769 char *tag = psprintf("TABLESPACE %s", fmtId(fspcname));
1770
1772 nilCatalogId, /* catalog ID */
1773 createDumpId(), /* dump ID */
1774 ARCHIVE_OPTS(.tag = tag,
1775 .description = "TABLESPACE",
1776 .section = SECTION_PRE_DATA,
1777 .createStmt = buf->data));
1778
1779 if (comment_buf->data[0] != '\0')
1781 nilCatalogId, /* catalog ID */
1782 createDumpId(), /* dump ID */
1783 ARCHIVE_OPTS(.tag = tag,
1784 .description = "COMMENT",
1785 .section = SECTION_PRE_DATA,
1786 .createStmt = comment_buf->data));
1787
1788 if (seclabel_buf->data[0] != '\0')
1790 nilCatalogId, /* catalog ID */
1791 createDumpId(), /* dump ID */
1792 ARCHIVE_OPTS(.tag = tag,
1793 .description = "SECURITY LABEL",
1794 .section = SECTION_PRE_DATA,
1795 .createStmt = seclabel_buf->data));
1796 }
1797
1798 free(fspcname);
1800 }
1801
1802 PQclear(res);
1805
1806 if (archDumpFormat == archNull)
1807 fprintf(OPF, "\n\n");
1808}
static bool skip_acls
Definition pg_dumpall.c:97
#define is_absolute_path(filename)
Definition port.h:104

References acldefault(), appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, atooid, binary_upgrade, buf, buildACLCommands(), buildShSecLabels(), conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), exit_nicely(), fb(), fmtId(), fout, fprintf, free, i, is_absolute_path, nilCatalogId, no_comments, no_security_labels, OPF, pg_log_error, pg_strdup(), PQclear, PQfinish(), PQgetvalue, PQntuples, psprintf(), resetPQExpBuffer(), SECTION_PRE_DATA, server_version, and skip_acls.

Referenced by main().

◆ dumpTimestamp()

static void dumpTimestamp ( const char msg)
static

Definition at line 2332 of file pg_dumpall.c.

2333{
2334 char buf[64];
2335 time_t now = time(NULL);
2336
2337 if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
2338 fprintf(OPF, "-- %s %s\n\n", msg, buf);
2339}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1607
#define PGDUMP_STRFTIME_FMT
Definition dumputils.h:34

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

Referenced by main().

◆ dumpUserConfig()

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

Definition at line 1883 of file pg_dumpall.c.

1884{
1886 PGresult *res;
1887
1888 printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1889 "WHERE setdatabase = 0 AND setrole = "
1890 "(SELECT oid FROM %s WHERE rolname = ",
1891 role_catalog);
1894
1895 res = executeQuery(conn, buf->data);
1896
1897 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1898 {
1899 char *sanitized;
1900
1902 fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", sanitized);
1903 free(sanitized);
1904 }
1905
1906 for (int i = 0; i < PQntuples(res); i++)
1907 {
1910 "ROLE", username, NULL, NULL,
1911 buf);
1912
1913 if (archDumpFormat == archNull)
1914 fprintf(OPF, "%s", buf->data);
1915 else
1917 nilCatalogId, /* catalog ID */
1918 createDumpId(), /* dump ID */
1919 ARCHIVE_OPTS(.tag = psprintf("ROLE %s", fmtId(username)),
1920 .description = "ROLE PROPERTIES",
1921 .section = SECTION_PRE_DATA,
1922 .createStmt = buf->data));
1923 }
1924
1925 PQclear(res);
1926
1928}
void makeAlterConfigCommand(PGconn *conn, const char *configitem, const char *type, const char *name, const char *type2, const char *name2, PQExpBuffer buf)
Definition dumputils.c:865
static char * username
Definition initdb.c:153

References appendPQExpBufferChar(), appendStringLiteralConn(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, buf, conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), fb(), fmtId(), fout, fprintf, free, i, makeAlterConfigCommand(), nilCatalogId, OPF, PQclear, PQgetvalue, PQntuples, printfPQExpBuffer(), psprintf(), resetPQExpBuffer(), role_catalog, sanitize_line(), SECTION_PRE_DATA, and username.

Referenced by dumpRoles().

◆ executeCommand()

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

Definition at line 2238 of file pg_dumpall.c.

2239{
2240 PGresult *res;
2241
2242 pg_log_info("executing %s", query);
2243
2244 res = PQexec(conn, query);
2245 if (!res ||
2247 {
2248 pg_log_error("query failed: %s", PQerrorMessage(conn));
2249 pg_log_error_detail("Query was: %s", query);
2250 PQfinish(conn);
2251 exit_nicely(1);
2252 }
2253
2254 PQclear(res);
2255}
char * PQerrorMessage(const PGconn *conn)
PGresult * PQexec(PGconn *conn, const char *query)
Definition fe-exec.c:2279
#define PQresultStatus
@ PGRES_COMMAND_OK
Definition libpq-fe.h:131
#define pg_log_error_detail(...)
Definition logging.h:109

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

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

◆ expand_dbname_patterns()

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

Definition at line 1935 of file pg_dumpall.c.

1938{
1939 PQExpBuffer query;
1940 PGresult *res;
1941
1942 if (patterns->head == NULL)
1943 return; /* nothing to do */
1944
1945 query = createPQExpBuffer();
1946
1947 /*
1948 * The loop below runs multiple SELECTs, which might sometimes result in
1949 * duplicate entries in the name list, but we don't care, since all we're
1950 * going to do is test membership of the list.
1951 */
1952
1953 for (SimpleStringListCell *cell = patterns->head; cell; cell = cell->next)
1954 {
1955 int dotcnt;
1956
1958 "SELECT datname FROM pg_catalog.pg_database n\n");
1959 processSQLNamePattern(conn, query, cell->val, false,
1960 false, NULL, "datname", NULL, NULL, NULL,
1961 &dotcnt);
1962
1963 if (dotcnt > 0)
1964 {
1965 pg_log_error("improper qualified name (too many dotted names): %s",
1966 cell->val);
1967 PQfinish(conn);
1968 exit_nicely(1);
1969 }
1970
1971 res = executeQuery(conn, query->data);
1972 for (int i = 0; i < PQntuples(res); i++)
1973 {
1974 simple_string_list_append(names, PQgetvalue(res, i, 0));
1975 }
1976
1977 PQclear(res);
1978 resetPQExpBuffer(query);
1979 }
1980
1981 destroyPQExpBuffer(query);
1982}
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)

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

Referenced by main().

◆ help()

static void help ( void  )
static

Definition at line 865 of file pg_dumpall.c.

866{
867 printf(_("%s exports a PostgreSQL database cluster as an SQL script or to other formats.\n\n"), progname);
868 printf(_("Usage:\n"));
869 printf(_(" %s [OPTION]...\n"), progname);
870
871 printf(_("\nGeneral options:\n"));
872 printf(_(" -f, --file=FILENAME output file name\n"));
873 printf(_(" -F, --format=c|d|t|p output file format (custom, directory, tar,\n"
874 " plain text (default))\n"));
875 printf(_(" -v, --verbose verbose mode\n"));
876 printf(_(" -V, --version output version information, then exit\n"));
877 printf(_(" --lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock\n"));
878 printf(_(" -?, --help show this help, then exit\n"));
879 printf(_("\nOptions controlling the output content:\n"));
880 printf(_(" -a, --data-only dump only the data, not the schema or statistics\n"));
881 printf(_(" -c, --clean clean (drop) databases before recreating\n"));
882 printf(_(" -E, --encoding=ENCODING dump the data in encoding ENCODING\n"));
883 printf(_(" -g, --globals-only dump only global objects, no databases\n"));
884 printf(_(" -O, --no-owner skip restoration of object ownership\n"));
885 printf(_(" -r, --roles-only dump only roles, no databases or tablespaces\n"));
886 printf(_(" -s, --schema-only dump only the schema, no data or statistics\n"));
887 printf(_(" -S, --superuser=NAME superuser user name to use in the dump\n"));
888 printf(_(" -t, --tablespaces-only dump only tablespaces, no databases or roles\n"));
889 printf(_(" -x, --no-privileges do not dump privileges (grant/revoke)\n"));
890 printf(_(" --binary-upgrade for use by upgrade utilities only\n"));
891 printf(_(" --column-inserts dump data as INSERT commands with column names\n"));
892 printf(_(" --disable-dollar-quoting disable dollar quoting, use SQL standard quoting\n"));
893 printf(_(" --disable-triggers disable triggers during data-only restore\n"));
894 printf(_(" --exclude-database=PATTERN exclude databases whose name matches PATTERN\n"));
895 printf(_(" --extra-float-digits=NUM override default setting for extra_float_digits\n"));
896 printf(_(" --filter=FILENAME exclude databases based on expressions in FILENAME\n"));
897 printf(_(" --if-exists use IF EXISTS when dropping objects\n"));
898 printf(_(" --inserts dump data as INSERT commands, rather than COPY\n"));
899 printf(_(" --load-via-partition-root load partitions via the root table\n"));
900 printf(_(" --no-comments do not dump comment commands\n"));
901 printf(_(" --no-data do not dump data\n"));
902 printf(_(" --no-policies do not dump row security policies\n"));
903 printf(_(" --no-publications do not dump publications\n"));
904 printf(_(" --no-role-passwords do not dump passwords for roles\n"));
905 printf(_(" --no-schema do not dump schema\n"));
906 printf(_(" --no-security-labels do not dump security label assignments\n"));
907 printf(_(" --no-statistics do not dump statistics\n"));
908 printf(_(" --no-subscriptions do not dump subscriptions\n"));
909 printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
910 printf(_(" --no-table-access-method do not dump table access methods\n"));
911 printf(_(" --no-tablespaces do not dump tablespace assignments\n"));
912 printf(_(" --no-toast-compression do not dump TOAST compression methods\n"));
913 printf(_(" --no-unlogged-table-data do not dump unlogged table data\n"));
914 printf(_(" --on-conflict-do-nothing add ON CONFLICT DO NOTHING to INSERT commands\n"));
915 printf(_(" --quote-all-identifiers quote all identifiers, even if not key words\n"));
916 printf(_(" --restrict-key=RESTRICT_KEY use provided string as psql \\restrict key\n"));
917 printf(_(" --rows-per-insert=NROWS number of rows per INSERT; implies --inserts\n"));
918 printf(_(" --sequence-data include sequence data in dump\n"));
919 printf(_(" --statistics dump the statistics\n"));
920 printf(_(" --statistics-only dump only the statistics, not schema or data\n"));
921 printf(_(" --use-set-session-authorization\n"
922 " use SET SESSION AUTHORIZATION commands instead of\n"
923 " ALTER OWNER commands to set ownership\n"));
924
925 printf(_("\nConnection options:\n"));
926 printf(_(" -d, --dbname=CONNSTR connect using connection string\n"));
927 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
928 printf(_(" -l, --database=DBNAME alternative default database\n"));
929 printf(_(" -p, --port=PORT database server port number\n"));
930 printf(_(" -U, --username=NAME connect as specified database user\n"));
931 printf(_(" -w, --no-password never prompt for password\n"));
932 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
933 printf(_(" --role=ROLENAME do SET ROLE before dump\n"));
934
935 printf(_("\nIf -f/--file is not used, then the SQL script will be written to the standard\n"
936 "output.\n\n"));
937 printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
938 printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
939}
#define _(x)
Definition elog.c:95
const char * progname
Definition main.c:44
#define printf(...)
Definition port.h:266

References _, fb(), printf, and progname.

Referenced by main().

◆ main()

int main ( int  argc,
char argv[] 
)

Definition at line 145 of file pg_dumpall.c.

146{
147 static struct option long_options[] = {
148 {"data-only", no_argument, NULL, 'a'},
149 {"clean", no_argument, NULL, 'c'},
150 {"encoding", required_argument, NULL, 'E'},
151 {"file", required_argument, NULL, 'f'},
152 {"globals-only", no_argument, NULL, 'g'},
153 {"host", required_argument, NULL, 'h'},
154 {"dbname", required_argument, NULL, 'd'},
155 {"database", required_argument, NULL, 'l'},
156 {"no-owner", no_argument, NULL, 'O'},
157 {"port", required_argument, NULL, 'p'},
158 {"roles-only", no_argument, NULL, 'r'},
159 {"schema-only", no_argument, NULL, 's'},
160 {"superuser", required_argument, NULL, 'S'},
161 {"tablespaces-only", no_argument, NULL, 't'},
162 {"username", required_argument, NULL, 'U'},
163 {"verbose", no_argument, NULL, 'v'},
164 {"no-password", no_argument, NULL, 'w'},
165 {"password", no_argument, NULL, 'W'},
166 {"no-privileges", no_argument, NULL, 'x'},
167 {"no-acl", no_argument, NULL, 'x'},
168 {"format", required_argument, NULL, 'F'},
169
170 /*
171 * the following options don't have an equivalent short option letter
172 */
173 {"attribute-inserts", no_argument, &column_inserts, 1},
174 {"binary-upgrade", no_argument, &binary_upgrade, 1},
175 {"column-inserts", no_argument, &column_inserts, 1},
176 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
177 {"disable-triggers", no_argument, &disable_triggers, 1},
178 {"exclude-database", required_argument, NULL, 6},
179 {"extra-float-digits", required_argument, NULL, 5},
180 {"if-exists", no_argument, &if_exists, 1},
181 {"inserts", no_argument, &inserts, 1},
182 {"lock-wait-timeout", required_argument, NULL, 2},
183 {"no-table-access-method", no_argument, &no_table_access_method, 1},
184 {"no-tablespaces", no_argument, &no_tablespaces, 1},
185 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
186 {"load-via-partition-root", no_argument, &load_via_partition_root, 1},
187 {"role", required_argument, NULL, 3},
188 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
189 {"no-comments", no_argument, &no_comments, 1},
190 {"no-data", no_argument, &no_data, 1},
191 {"no-policies", no_argument, &no_policies, 1},
192 {"no-publications", no_argument, &no_publications, 1},
193 {"no-role-passwords", no_argument, &no_role_passwords, 1},
194 {"no-schema", no_argument, &no_schema, 1},
195 {"no-security-labels", no_argument, &no_security_labels, 1},
196 {"no-subscriptions", no_argument, &no_subscriptions, 1},
197 {"no-statistics", no_argument, &no_statistics, 1},
198 {"no-sync", no_argument, NULL, 4},
199 {"no-toast-compression", no_argument, &no_toast_compression, 1},
200 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
201 {"on-conflict-do-nothing", no_argument, &on_conflict_do_nothing, 1},
202 {"rows-per-insert", required_argument, NULL, 7},
203 {"statistics", no_argument, &with_statistics, 1},
204 {"statistics-only", no_argument, &statistics_only, 1},
205 {"filter", required_argument, NULL, 8},
206 {"sequence-data", no_argument, &sequence_data, 1},
207 {"restrict-key", required_argument, NULL, 9},
208
209 {NULL, 0, NULL, 0}
210 };
211
212 char *pghost = NULL;
213 char *pgport = NULL;
214 char *pguser = NULL;
215 char *pgdb = NULL;
216 char *use_role = NULL;
217 const char *dumpencoding = NULL;
218 const char *format_name = "p";
219 trivalue prompt_password = TRI_DEFAULT;
220 bool data_only = false;
221 bool globals_only = false;
222 bool roles_only = false;
223 bool schema_only = false;
224 bool tablespaces_only = false;
225 PGconn *conn;
226 int encoding;
227 int c,
228 ret;
229 int optindex;
230 DumpOptions dopt;
231
232 pg_logging_init(argv[0]);
234 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
235 progname = get_progname(argv[0]);
236
237 if (argc > 1)
238 {
239 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
240 {
241 help();
242 exit_nicely(0);
243 }
244 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
245 {
246 puts("pg_dumpall (PostgreSQL) " PG_VERSION);
247 exit_nicely(0);
248 }
249 }
250
251 if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
252 pg_dump_bin)) < 0)
253 {
254 char full_path[MAXPGPATH];
255
256 if (find_my_exec(argv[0], full_path) < 0)
258
259 if (ret == -1)
260 pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
261 "pg_dump", progname, full_path);
262 else
263 pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
264 "pg_dump", full_path, progname);
265 }
266
268 InitDumpOptions(&dopt);
269
270 while ((c = getopt_long(argc, argv, "acd:E:f:F:gh:l:Op:rsS:tU:vwWx", long_options, &optindex)) != -1)
271 {
272 switch (c)
273 {
274 case 'a':
275 data_only = true;
277 break;
278
279 case 'c':
280 output_clean = true;
281 break;
282
283 case 'd':
285 break;
286
287 case 'E':
291 break;
292
293 case 'f':
297 break;
298 case 'F':
300 break;
301 case 'g':
302 globals_only = true;
303 break;
304
305 case 'h':
307 break;
308
309 case 'l':
311 break;
312
313 case 'O':
315 break;
316
317 case 'p':
319 break;
320
321 case 'r':
322 roles_only = true;
323 break;
324
325 case 's':
326 schema_only = true;
328 break;
329
330 case 'S':
333 break;
334
335 case 't':
336 tablespaces_only = true;
337 break;
338
339 case 'U':
340 pguser = pg_strdup(optarg);
342 break;
343
344 case 'v':
345 verbose = true;
348 break;
349
350 case 'w':
351 prompt_password = TRI_NO;
353 break;
354
355 case 'W':
356 prompt_password = TRI_YES;
358 break;
359
360 case 'x':
361 skip_acls = true;
363 break;
364
365 case 0:
366 break;
367
368 case 2:
369 appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
371 break;
372
373 case 3:
374 use_role = pg_strdup(optarg);
375 appendPQExpBufferStr(pgdumpopts, " --role ");
376 appendShellString(pgdumpopts, use_role);
377 break;
378
379 case 4:
380 dosync = false;
381 appendPQExpBufferStr(pgdumpopts, " --no-sync");
382 break;
383
384 case 5:
385 appendPQExpBufferStr(pgdumpopts, " --extra-float-digits ");
387 break;
388
389 case 6:
391 break;
392
393 case 7:
394 appendPQExpBufferStr(pgdumpopts, " --rows-per-insert ");
396 break;
397
398 case 8:
400 break;
401
402 case 9:
404 appendPQExpBufferStr(pgdumpopts, " --restrict-key ");
406 break;
407
408 default:
409 /* getopt_long already emitted a complaint */
410 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
411 exit_nicely(1);
412 }
413 }
414
415 /* Complain if any arguments remain */
416 if (optind < argc)
417 {
418 pg_log_error("too many command-line arguments (first is \"%s\")",
419 argv[optind]);
420 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
421 exit_nicely(1);
422 }
423
424 /* --exclude-database is incompatible with global *-only options */
426 globals_only, "-g/--globals-only",
427 roles_only, "-r/--roles-only",
428 tablespaces_only, "-t/--tablespaces-only");
429
430 /* *-only options are incompatible with each other */
431 check_mut_excl_opts(data_only, "-a/--data-only",
432 globals_only, "-g/--globals-only",
433 roles_only, "-r/--roles-only",
434 schema_only, "-s/--schema-only",
435 statistics_only, "--statistics-only",
436 tablespaces_only, "-t/--tablespaces-only");
437
438 /* --no-* and *-only for same thing are incompatible */
439 check_mut_excl_opts(data_only, "-a/--data-only",
440 no_data, "--no-data");
441 check_mut_excl_opts(schema_only, "-s/--schema-only",
442 no_schema, "--no-schema");
443 check_mut_excl_opts(statistics_only, "--statistics-only",
444 no_statistics, "--no-statistics");
445
446 /* --statistics and --no-statistics are incompatible */
447 check_mut_excl_opts(with_statistics, "--statistics",
448 no_statistics, "--no-statistics");
449
450 /* --statistics is incompatible with *-only (except --statistics-only) */
451 check_mut_excl_opts(with_statistics, "--statistics",
452 data_only, "-a/--data-only",
453 globals_only, "-g/--globals-only",
454 roles_only, "-r/--roles-only",
455 schema_only, "-s/--schema-only",
456 tablespaces_only, "-t/--tablespaces-only");
457
458 if (if_exists && !output_clean)
459 pg_fatal("option %s requires option %s",
460 "--if-exists", "-c/--clean");
461
462 /* Get format for dump. */
464
465 /*
466 * If a non-plain format is specified, a file name is also required as the
467 * path to the main directory.
468 */
469 if (archDumpFormat != archNull &&
470 (!filename || strcmp(filename, "") == 0))
471 {
472 pg_log_error("option %s=d|c|t requires option %s",
473 "-F/--format", "-f/--file");
474 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
475 exit_nicely(1);
476 }
477
478 /* restrict-key is only supported with --format=plain */
480 pg_fatal("option %s can only be used with %s=plain",
481 "--restrict-key", "--format");
482
483 /* --clean and -g/--globals-only cannot be used together in non-text dump */
485 pg_fatal("options %s and %s cannot be used together in non-text dump",
486 "--clean", "-g/--globals-only");
487
488 /*
489 * If password values are not required in the dump, switch to using
490 * pg_roles which is equally useful, just more likely to have unrestricted
491 * access than pg_authid.
492 */
495 else
497
498 /* Add long options to the pg_dump argument list */
499 if (binary_upgrade)
500 appendPQExpBufferStr(pgdumpopts, " --binary-upgrade");
501 if (column_inserts)
502 appendPQExpBufferStr(pgdumpopts, " --column-inserts");
504 appendPQExpBufferStr(pgdumpopts, " --disable-dollar-quoting");
506 appendPQExpBufferStr(pgdumpopts, " --disable-triggers");
507 if (inserts)
508 appendPQExpBufferStr(pgdumpopts, " --inserts");
510 appendPQExpBufferStr(pgdumpopts, " --no-table-access-method");
511 if (no_tablespaces)
512 appendPQExpBufferStr(pgdumpopts, " --no-tablespaces");
514 appendPQExpBufferStr(pgdumpopts, " --quote-all-identifiers");
516 appendPQExpBufferStr(pgdumpopts, " --load-via-partition-root");
517 if (use_setsessauth)
518 appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
519 if (no_comments)
520 appendPQExpBufferStr(pgdumpopts, " --no-comments");
521 if (no_data)
522 appendPQExpBufferStr(pgdumpopts, " --no-data");
523 if (no_policies)
524 appendPQExpBufferStr(pgdumpopts, " --no-policies");
525 if (no_publications)
526 appendPQExpBufferStr(pgdumpopts, " --no-publications");
528 appendPQExpBufferStr(pgdumpopts, " --no-security-labels");
529 if (no_schema)
530 appendPQExpBufferStr(pgdumpopts, " --no-schema");
531 if (no_statistics)
532 appendPQExpBufferStr(pgdumpopts, " --no-statistics");
534 appendPQExpBufferStr(pgdumpopts, " --no-subscriptions");
536 appendPQExpBufferStr(pgdumpopts, " --no-toast-compression");
538 appendPQExpBufferStr(pgdumpopts, " --no-unlogged-table-data");
539 if (with_statistics)
540 appendPQExpBufferStr(pgdumpopts, " --statistics");
542 appendPQExpBufferStr(pgdumpopts, " --on-conflict-do-nothing");
543 if (statistics_only)
544 appendPQExpBufferStr(pgdumpopts, " --statistics-only");
545 if (sequence_data)
546 appendPQExpBufferStr(pgdumpopts, " --sequence-data");
547
548 /*
549 * Open the output file if required, otherwise use stdout. If required,
550 * then create new directory.
551 */
553 {
555
556 /* Create new directory or accept the empty existing directory. */
558 }
559 else if (filename)
560 {
562 if (!OPF)
563 pg_fatal("could not open output file \"%s\": %m",
564 filename);
565 }
566 else
567 OPF = stdout;
568
569 /*
570 * If you don't provide a restrict key, one will be appointed for you.
571 */
572 if (!restrict_key)
574 if (!restrict_key)
575 pg_fatal("could not generate restrict key");
577 pg_fatal("invalid restrict key");
578
579 /*
580 * If there was a database specified on the command line, use that,
581 * otherwise try to connect to database "postgres", and failing that
582 * "template1".
583 */
584 if (pgdb)
585 {
587 prompt_password, false,
589
590 if (!conn)
591 pg_fatal("could not connect to database \"%s\"", pgdb);
592 }
593 else
594 {
595 conn = ConnectDatabase("postgres", connstr, pghost, pgport, pguser,
596 prompt_password, false,
598 if (!conn)
599 conn = ConnectDatabase("template1", connstr, pghost, pgport, pguser,
600 prompt_password, true,
602
603 if (!conn)
604 {
605 pg_log_error("could not connect to databases \"postgres\" or \"template1\"\n"
606 "Please specify an alternative database.");
607 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
608 exit_nicely(1);
609 }
610 }
611
612 /*
613 * Get a list of database names that match the exclude patterns
614 */
617
618 /*
619 * Set the client encoding if requested.
620 */
621 if (dumpencoding)
622 {
624 pg_fatal("invalid client encoding \"%s\" specified",
626 }
627
628 /*
629 * Force standard_conforming_strings on, just in case we are dumping from
630 * an old server that has it disabled. Without this, literals in views,
631 * expressions, etc, would be incorrect for modern servers.
632 */
633 executeCommand(conn, "SET standard_conforming_strings = on");
634
635 /*
636 * Get the active encoding, so we know how to escape strings.
637 */
640
641 /* Set the role if requested */
642 if (use_role)
643 {
645
646 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
647 executeCommand(conn, query->data);
648 destroyPQExpBuffer(query);
649 }
650
651 /* Force quoting of all identifiers if requested. */
653 executeCommand(conn, "SET quote_all_identifiers = true");
654
655 /* create a archive file for global commands. */
657 {
660 const char *encname;
661 pg_compress_specification compression_spec = {0};
662
663 /*
664 * Check that no global object names contain newlines or carriage
665 * returns, which would break the map.dat file format. This is only
666 * needed for servers older than v19, which started prohibiting such
667 * names.
668 */
669 if (server_version < 190000)
671
672 /* Set file path for global sql commands. */
673 snprintf(global_path, MAXPGPATH, "%s/toc.glo", filename);
674
675 /* Open the output file */
676 fout = CreateArchive(global_path, archCustom, compression_spec,
678
679 /* Make dump options accessible right away */
680 SetArchiveOptions(fout, &dopt, NULL);
681
682 ((ArchiveHandle *) fout)->connection = conn;
683 ((ArchiveHandle *) fout)->public.numWorkers = 1;
684
685 /* Register the cleanup hook */
687
688 /* Let the archiver know how noisy to be */
690
691 /*
692 * We allow the server to be back to 9.2, and up to any minor release
693 * of our own major version. (See also version check in
694 * pg_dumpall.c.)
695 */
696 fout->minRemoteVersion = 90200;
697 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
698 fout->numWorkers = 1;
699
700 /* Dump default_transaction_read_only. */
701 appendPQExpBufferStr(qry, "SET default_transaction_read_only = off;\n\n");
703 nilCatalogId, /* catalog ID */
704 createDumpId(), /* dump ID */
705 ARCHIVE_OPTS(.tag = "default_transaction_read_only",
706 .description = "default_transaction_read_only",
707 .section = SECTION_PRE_DATA,
708 .createStmt = qry->data));
709 resetPQExpBuffer(qry);
710
711 /* Put the correct encoding into the archive */
713
714 appendPQExpBufferStr(qry, "SET client_encoding = ");
716 appendPQExpBufferStr(qry, ";\n");
718 nilCatalogId, /* catalog ID */
719 createDumpId(), /* dump ID */
720 ARCHIVE_OPTS(.tag = "client_encoding",
721 .description = "client_encoding",
722 .section = SECTION_PRE_DATA,
723 .createStmt = qry->data));
724 resetPQExpBuffer(qry);
725
726 /* Put the correct escape string behavior into the archive. */
727 appendPQExpBuffer(qry, "SET standard_conforming_strings = 'on';\n");
729 nilCatalogId, /* catalog ID */
730 createDumpId(), /* dump ID */
731 ARCHIVE_OPTS(.tag = "standard_conforming_strings",
732 .description = "standard_conforming_strings",
733 .section = SECTION_PRE_DATA,
734 .createStmt = qry->data));
736 }
737 else
738 {
739 fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
740
741 if (verbose)
742 dumpTimestamp("Started on");
743
744 /*
745 * Enter restricted mode to block any unexpected psql meta-commands. A
746 * malicious source might try to inject a variety of things via bogus
747 * responses to queries. While we cannot prevent such sources from
748 * affecting the destination at restore time, we can block psql
749 * meta-commands so that the client machine that runs psql with the
750 * dump output remains unaffected.
751 */
752 fprintf(OPF, "\\restrict %s\n\n", restrict_key);
753
754 /*
755 * We used to emit \connect postgres here, but that served no purpose
756 * other than to break things for installations without a postgres
757 * database. Everything we're restoring here is a global, so
758 * whichever database we're connected to at the moment is fine.
759 */
760
761 /* Restore will need to write to the target cluster */
762 fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
763
764 /* Replicate encoding and standard_conforming_strings in output */
765 fprintf(OPF, "SET client_encoding = '%s';\n",
767 fprintf(OPF, "SET standard_conforming_strings = on;\n");
768 fprintf(OPF, "\n");
769 }
770
772 {
773 /*
774 * If asked to --clean, do that first. We can avoid detailed
775 * dependency analysis because databases never depend on each other,
776 * and tablespaces never depend on each other. Roles could have
777 * grants to each other, but DROP ROLE will clean those up silently.
778 *
779 * For non-text formats, pg_dumpall unconditionally process --clean
780 * option. In contrast, pg_restore only applies it if the user
781 * explicitly provides the flag. This discrepancy resolves corner
782 * cases where pg_restore requires cleanup instructions that may be
783 * missing from a standard pg_dumpall output.
784 */
786 {
788 dropDBs(conn);
789
790 if (!roles_only && !no_tablespaces)
792
793 if (!tablespaces_only)
795 }
796
797 /*
798 * Now create objects as requested. Be careful that option logic here
799 * is the same as for drops above.
800 */
801 if (!tablespaces_only)
802 {
803 /* Dump roles (users) */
805
806 /* Dump role memberships */
808
809 /* Dump role GUC privileges */
810 if (server_version >= 150000 && !skip_acls)
812 }
813
814 /* Dump tablespaces */
815 if (!roles_only && !no_tablespaces)
817 }
818
820 {
821 /*
822 * Exit restricted mode just before dumping the databases. pg_dump
823 * will handle entering restricted mode again as appropriate.
824 */
825 fprintf(OPF, "\\unrestrict %s\n\n", restrict_key);
826 }
827
830
832 {
833 PQfinish(conn);
834
835 if (verbose)
836 dumpTimestamp("Completed on");
837 fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
838
839 if (filename)
840 {
841 fclose(OPF);
842
843 /* sync the resulting file, errors are not fatal */
844 if (dosync)
845 (void) fsync_fname(filename, false);
846 }
847 }
848 else
849 {
850 RestoreOptions *ropt;
851
852 ropt = NewRestoreOptions();
853 SetArchiveOptions(fout, &dopt, ropt);
854
855 /* Mark which entries should be output */
858 }
859
860 exit_nicely(0);
861}
void on_exit_close_archive(Archive *AHX)
Definition parallel.c:330
#define Assert(condition)
Definition c.h:906
#define PG_TEXTDOMAIN(domain)
Definition c.h:1266
int find_my_exec(const char *argv0, char *retpath)
Definition exec.c:161
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition exec.c:430
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition exec.c:311
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, const char *progname, const char **connstr, int *server_version, char *password, char *override_dbname)
Definition connectdb.c:40
char * generate_restrict_key(void)
Definition dumputils.c:973
bool valid_restrict_key(const char *restrict_key)
Definition dumputils.c:997
void create_or_open_dir(const char *dirname)
Definition dumputils.c:940
void fsync_fname(const char *fname, bool isdir)
Definition fd.c:757
int PQclientEncoding(const PGconn *conn)
int PQsetClientEncoding(PGconn *conn, const char *encoding)
@ DATA_DIR_SYNC_METHOD_FSYNC
Definition file_utils.h:29
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition getopt_long.c:60
#define no_argument
Definition getopt_long.h:25
#define required_argument
Definition getopt_long.h:26
static char * encoding
Definition initdb.c:139
void pg_logging_increase_verbosity(void)
Definition logging.c:185
void pg_logging_init(const char *argv0)
Definition logging.c:83
void pg_logging_set_level(enum pg_log_level new_level)
Definition logging.c:176
#define pg_log_error_hint(...)
Definition logging.h:112
@ PG_LOG_WARNING
Definition logging.h:38
#define check_mut_excl_opts(set, opt,...)
void ProcessArchiveRestoreOptions(Archive *AHX)
RestoreOptions * NewRestoreOptions(void)
#define appendStringLiteralAH(buf, str, AH)
Definition pg_backup.h:344
void CloseArchive(Archive *AHX)
Archive * CreateArchive(const char *FileSpec, const ArchiveFormat fmt, const pg_compress_specification compression_spec, bool dosync, ArchiveMode mode, SetupWorkerPtrType setupDumpWorker, DataDirSyncMethod sync_method)
@ archModeWrite
Definition pg_backup.h:51
void SetArchiveOptions(Archive *AH, DumpOptions *dopt, RestoreOptions *ropt)
void InitDumpOptions(DumpOptions *opts)
static void dumpTimestamp(const char *msg)
static int on_conflict_do_nothing
Definition pg_dumpall.c:124
static void dropTablespaces(PGconn *conn)
static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
static PQExpBuffer pgdumpopts
Definition pg_dumpall.c:94
static int statistics_only
Definition pg_dumpall.c:125
static int no_table_access_method
Definition pg_dumpall.c:107
static int no_unlogged_table_data
Definition pg_dumpall.c:119
static void check_for_invalid_global_names(PGconn *conn, SimpleStringList *database_exclude_names)
#define PG_AUTHID
Definition pg_dumpall.c:129
static int no_policies
Definition pg_dumpall.c:111
static int disable_triggers
Definition pg_dumpall.c:104
static bool dosync
Definition pg_dumpall.c:99
static const char * connstr
Definition pg_dumpall.c:95
static SimpleStringList database_exclude_patterns
Definition pg_dumpall.c:135
static void dumpTablespaces(PGconn *conn)
static void dumpRoleMembership(PGconn *conn)
static char pg_dump_bin[MAXPGPATH]
Definition pg_dumpall.c:93
static int no_publications
Definition pg_dumpall.c:112
static int sequence_data
Definition pg_dumpall.c:126
static char * restrict_key
Definition pg_dumpall.c:138
static void dumpDatabases(PGconn *conn)
static ArchiveFormat parseDumpFormat(const char *format)
static int disable_dollar_quoting
Definition pg_dumpall.c:103
static int no_tablespaces
Definition pg_dumpall.c:108
static int no_toast_compression
Definition pg_dumpall.c:118
#define PG_ROLES
Definition pg_dumpall.c:130
static int inserts
Definition pg_dumpall.c:106
static void executeCommand(PGconn *conn, const char *query)
static bool verbose
Definition pg_dumpall.c:98
static void dumpRoleGUCPrivs(PGconn *conn)
static int no_statistics
Definition pg_dumpall.c:116
static void dumpRoles(PGconn *conn)
static void help(void)
Definition pg_dumpall.c:865
static int use_setsessauth
Definition pg_dumpall.c:109
static int no_data
Definition pg_dumpall.c:114
static int load_via_partition_root
Definition pg_dumpall.c:123
static int column_inserts
Definition pg_dumpall.c:102
static void read_dumpall_filters(const char *filename, SimpleStringList *pattern)
static void dropRoles(PGconn *conn)
Definition pg_dumpall.c:946
static void dropDBs(PGconn *conn)
static int no_schema
Definition pg_dumpall.c:115
static int no_subscriptions
Definition pg_dumpall.c:117
static int with_statistics
Definition pg_dumpall.c:121
#define PGDUMP_VERSIONSTR
Definition pg_dumpall.c:44
PGDLLIMPORT int optind
Definition getopt.c:51
PGDLLIMPORT char * optarg
Definition getopt.c:53
#define pg_encoding_to_char
Definition pg_wchar.h:630
static const char * pghost
Definition pgbench.c:295
static const char * pgport
Definition pgbench.c:296
#define sprintf
Definition port.h:262
const char * get_progname(const char *argv0)
Definition path.c:652
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
char * c
bool quote_all_identifiers
Definition ruleutils.c:339
void setFmtEncoding(int encoding)
void appendShellString(PQExpBuffer buf, const char *str)
int minRemoteVersion
Definition pg_backup.h:237
int maxRemoteVersion
Definition pg_backup.h:238
int numWorkers
Definition pg_backup.h:240
int verbose
Definition pg_backup.h:232
SimpleStringListCell * head
Definition simple_list.h:42
char * username
Definition pg_backup.h:90
ConnParams cparams
Definition pg_backup.h:173
trivalue
Definition vacuumlo.c:35
@ TRI_YES
Definition vacuumlo.c:38
@ TRI_DEFAULT
Definition vacuumlo.c:36
@ TRI_NO
Definition vacuumlo.c:37

References appendPQExpBuffer(), appendPQExpBufferStr(), appendShellString(), appendStringLiteralAH, archCustom, archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archModeWrite, archNull, Assert, binary_upgrade, check_for_invalid_global_names(), check_mut_excl_opts, CloseArchive(), column_inserts, conn, ConnectDatabase(), connstr, _dumpOptions::cparams, create_or_open_dir(), CreateArchive(), createDumpId(), createPQExpBuffer(), PQExpBufferData::data, DATA_DIR_SYNC_METHOD_FSYNC, database_exclude_names, database_exclude_patterns, description, destroyPQExpBuffer(), disable_dollar_quoting, disable_triggers, dosync, dropDBs(), dropRoles(), dropTablespaces(), dumpDatabases(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpTablespaces(), dumpTimestamp(), encoding, executeCommand(), exit_nicely(), expand_dbname_patterns(), fb(), filename, find_my_exec(), find_other_exec(), fmtId(), fout, fprintf, fsync_fname(), generate_restrict_key(), get_progname(), getopt_long(), SimpleStringList::head, help(), if_exists, InitDumpOptions(), inserts, load_via_partition_root, MAXPGPATH, Archive::maxRemoteVersion, Archive::minRemoteVersion, NewRestoreOptions(), nilCatalogId, no_argument, no_comments, no_data, no_policies, no_publications, no_role_passwords, no_schema, no_security_labels, no_statistics, no_subscriptions, no_table_access_method, no_tablespaces, no_toast_compression, no_unlogged_table_data, Archive::numWorkers, on_conflict_do_nothing, on_exit_close_archive(), OPF, optarg, optind, output_clean, parseDumpFormat(), 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(), PQsetClientEncoding(), ProcessArchiveRestoreOptions(), progname, quote_all_identifiers, read_dumpall_filters(), required_argument, resetPQExpBuffer(), restrict_key, role_catalog, SECTION_PRE_DATA, sequence_data, server_version, set_pglocale_pgservice(), SetArchiveOptions(), setFmtEncoding(), simple_string_list_append(), skip_acls, snprintf, sprintf, statistics_only, strlcpy(), TRI_DEFAULT, TRI_NO, TRI_YES, use_setsessauth, _connParams::username, valid_restrict_key(), Archive::verbose, verbose, and with_statistics.

◆ parseDumpFormat()

static ArchiveFormat parseDumpFormat ( const char format)
static

Definition at line 2406 of file pg_dumpall.c.

2407{
2409
2410 if (pg_strcasecmp(format, "c") == 0)
2412 else if (pg_strcasecmp(format, "custom") == 0)
2414 else if (pg_strcasecmp(format, "d") == 0)
2416 else if (pg_strcasecmp(format, "directory") == 0)
2418 else if (pg_strcasecmp(format, "p") == 0)
2420 else if (pg_strcasecmp(format, "plain") == 0)
2422 else if (pg_strcasecmp(format, "t") == 0)
2424 else if (pg_strcasecmp(format, "tar") == 0)
2426 else
2427 pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
2428 format);
2429
2430 return archDumpFormat;
2431}
enum _archiveFormat ArchiveFormat
@ archDirectory
Definition pg_backup.h:45
static char format
int pg_strcasecmp(const char *s1, const char *s2)

References archCustom, archDirectory, archDumpFormat, archNull, archTar, format, pg_fatal, and pg_strcasecmp().

Referenced by main().

◆ read_dumpall_filters()

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

Definition at line 2351 of file pg_dumpall.c.

2352{
2354 char *objname;
2356 FilterObjectType objtype;
2357
2359
2360 while (filter_read_item(&fstate, &objname, &comtype, &objtype))
2361 {
2363 {
2364 pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
2365 "include",
2366 filter_object_type_name(objtype));
2367 exit_nicely(1);
2368 }
2369
2370 switch (objtype)
2371 {
2373 break;
2384 pg_log_filter_error(&fstate, _("unsupported filter object"));
2385 exit_nicely(1);
2386 break;
2387
2389 simple_string_list_append(pattern, objname);
2390 break;
2391 }
2392
2393 if (objname)
2394 free(objname);
2395 }
2396
2398}
void filter_init(FilterStateData *fstate, const char *filename, exit_function f_exit)
Definition filter.c:36
void filter_free(FilterStateData *fstate)
Definition filter.c:60
const char * filter_object_type_name(FilterObjectType fot)
Definition filter.c:82
bool filter_read_item(FilterStateData *fstate, char **objname, FilterCommandType *comtype, FilterObjectType *objtype)
Definition filter.c:392
void pg_log_filter_error(FilterStateData *fstate, const char *fmt,...)
Definition filter.c:154
FilterObjectType
Definition filter.h:48
@ FILTER_OBJECT_TYPE_TABLE_DATA_AND_CHILDREN
Definition filter.h:51
@ FILTER_OBJECT_TYPE_SCHEMA
Definition filter.h:57
@ FILTER_OBJECT_TYPE_INDEX
Definition filter.h:56
@ FILTER_OBJECT_TYPE_TRIGGER
Definition filter.h:60
@ FILTER_OBJECT_TYPE_FOREIGN_DATA
Definition filter.h:54
@ FILTER_OBJECT_TYPE_DATABASE
Definition filter.h:52
@ FILTER_OBJECT_TYPE_FUNCTION
Definition filter.h:55
@ FILTER_OBJECT_TYPE_TABLE_DATA
Definition filter.h:50
@ FILTER_OBJECT_TYPE_NONE
Definition filter.h:49
@ FILTER_OBJECT_TYPE_TABLE_AND_CHILDREN
Definition filter.h:59
@ FILTER_OBJECT_TYPE_EXTENSION
Definition filter.h:53
@ FILTER_OBJECT_TYPE_TABLE
Definition filter.h:58
FilterCommandType
Definition filter.h:38
@ FILTER_COMMAND_TYPE_INCLUDE
Definition filter.h:40

References _, exit_nicely(), fb(), 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,
char dbfile 
)
static

Definition at line 2146 of file pg_dumpall.c.

2147{
2149 PQExpBufferData cmd;
2150 int ret;
2151
2153 initPQExpBuffer(&cmd);
2154
2155 /*
2156 * If this is not a plain format dump, then append file name and dump
2157 * format to the pg_dump command to get archive dump.
2158 */
2159 if (archDumpFormat != archNull)
2160 {
2161 printfPQExpBuffer(&cmd, "\"%s\" %s -f %s %s", pg_dump_bin,
2163
2165 appendPQExpBufferStr(&cmd, " --format=directory ");
2166 else if (archDumpFormat == archCustom)
2167 appendPQExpBufferStr(&cmd, " --format=custom ");
2168 else if (archDumpFormat == archTar)
2169 appendPQExpBufferStr(&cmd, " --format=tar ");
2170 }
2171 else
2172 {
2173 printfPQExpBuffer(&cmd, "\"%s\" %s %s", pg_dump_bin,
2175
2176 /*
2177 * If we have a filename, use the undocumented plain-append pg_dump
2178 * format.
2179 */
2180 if (filename)
2181 appendPQExpBufferStr(&cmd, " -Fa ");
2182 else
2183 appendPQExpBufferStr(&cmd, " -Fp ");
2184 }
2185
2186 /*
2187 * Append the database name to the already-constructed stem of connection
2188 * string.
2189 */
2190 appendPQExpBuffer(&connstrbuf, "%s dbname=", connstr);
2192
2193 appendShellString(&cmd, connstrbuf.data);
2194
2195 pg_log_info("running \"%s\"", cmd.data);
2196
2197 fflush(NULL);
2198
2199 ret = system(cmd.data);
2200
2201 termPQExpBuffer(&cmd);
2203
2204 return ret;
2205}
void initPQExpBuffer(PQExpBuffer str)
Definition pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
void appendConnStrVal(PQExpBuffer buf, const char *str)

References appendConnStrVal(), appendPQExpBuffer(), appendPQExpBufferStr(), appendShellString(), archCustom, archDirectory, archDumpFormat, archNull, archTar, connstr, PQExpBufferData::data, dbname, fb(), filename, initPQExpBuffer(), pg_dump_bin, pg_log_info, pgdumpopts, printfPQExpBuffer(), and termPQExpBuffer().

Referenced by dumpDatabases().

Variable Documentation

◆ archDumpFormat

◆ binary_upgrade

int binary_upgrade = 0
static

Definition at line 101 of file pg_dumpall.c.

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

◆ column_inserts

int column_inserts = 0
static

Definition at line 102 of file pg_dumpall.c.

Referenced by main().

◆ connstr

◆ database_exclude_names

SimpleStringList database_exclude_names = {NULL, NULL}
static

Definition at line 136 of file pg_dumpall.c.

136{NULL, NULL};

Referenced by check_for_invalid_global_names(), dumpDatabases(), and main().

◆ database_exclude_patterns

SimpleStringList database_exclude_patterns = {NULL, NULL}
static

Definition at line 135 of file pg_dumpall.c.

135{NULL, NULL};

Referenced by main().

◆ disable_dollar_quoting

int disable_dollar_quoting = 0
static

Definition at line 103 of file pg_dumpall.c.

Referenced by main().

◆ disable_triggers

int disable_triggers = 0
static

Definition at line 104 of file pg_dumpall.c.

Referenced by main(), and main().

◆ dosync

bool dosync = true
static

Definition at line 99 of file pg_dumpall.c.

Referenced by main().

◆ dumpIdVal

int dumpIdVal = 0
static

Definition at line 140 of file pg_dumpall.c.

Referenced by createDumpId().

◆ filename

char* filename = NULL
static

Definition at line 133 of file pg_dumpall.c.

Referenced by _fileExistsInDirectory(), _PrintFileData(), _PrintFileData(), _tarPositionTo(), _tarWriteHeader(), adjust_data_dir(), 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(), decide_file_action(), dir_close(), dir_get_file_name(), dir_open_for_write(), dispell_init(), dsynonym_init(), dumpDatabases(), dxsyn_init(), ecpg_postprocess_result(), errfinish(), errsave_finish(), execute_extension_script(), execute_sql_string(), expand_tilde(), exportFile(), exportFile(), extract_directory(), extract_link(), file_acquire_sample_rows(), file_exists_in_directory(), file_fdw_validator(), fileAnalyzeForeignTable(), fileBeginForeignScan(), fileExplainForeignScan(), fileGetOptions(), fill_hba_line(), fill_ident_line(), filter_init(), first_dir_separator(), get_sock_dir(), GetConfFilesInDir(), getFileContentType(), hasSuffix(), importFile(), 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_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(), 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(), parse_relfilenumber(), parse_snapshot_filename(), parseIntFromText(), ParseTzFile(), parseVxidFromText(), parseXidFromText(), pg_log_generic_v(), pg_stat_file(), PLy_traceback(), process_file(), 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_restore_filters(), read_text_file(), read_whole_file(), readstoplist(), reconstruct_from_incremental_file(), regcomp_auth_token(), run_diff(), runPgDump(), sendFileWithContent(), set_backtrace(), set_input(), set_stack_entry_location(), SetOutput(), setup_run_file(), shell_construct_command(), shell_run_command(), should_allow_existing_directory(), slurp_file(), splitTzLine(), SysLogger_Start(), tar_get_file_name(), tarCreateHeader(), tarOpen(), test_slru_scan_cb(), thesaurusRead(), tokenize_auth_file(), TrimExtension(), tsearch_readline_begin(), UpdateLastRemovedPtr(), verify_plain_backup_directory(), verify_tar_backup(), write_auto_conf_file(), WriteRecoveryConfig(), writeTimeLineHistoryFile(), and XLogRecordSaveFPWs().

◆ fout

Archive* fout = NULL
static

Definition at line 139 of file pg_dumpall.c.

Referenced by _print_horizontal_line(), append_depends_on_extension(), appendNamedArgument(), appendReloptionsArrayAH(), asciidoc_escaped_print(), binary_upgrade_set_type_oids_by_rel(), binary_upgrade_set_type_oids_by_type_oid(), BuildArchiveDependencies(), buildMatViewRefreshDependencies(), checkExtensionMembership(), collectBinaryUpgradeClassOids(), collectComments(), collectRoleNames(), collectSecLabels(), collectSequences(), convertTSFunction(), createViewAsClause(), csv_escaped_print(), csv_print_field(), determineNotNullFlags(), do_field(), do_header(), dropDBs(), dropRoles(), dropTablespaces(), dumpAccessMethod(), dumpACL(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpCast(), dumpCollation(), dumpComment(), dumpCommentExtended(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpDatabase(), dumpDefaultACL(), dumpDomain(), dumpDumpableObject(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpIndex(), dumpIndexAttach(), dumpLO(), dumpLOs(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpPublicationNamespace(), dumpPublicationTable(), dumpRangeType(), dumpRelationStats(), dumpRelationStats_dumper(), dumpRoleGUCPrivs(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStatisticsExt(), dumpStatisticsExtStats(), dumpSubscription(), dumpSubscriptionTable(), dumpTable(), dumpTableAttach(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTransform(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpType(), dumpUndefinedType(), dumpUserConfig(), dumpUserMappings(), exec_command_echo(), ExecuteSqlQueryForSingleRow(), expand_extension_name_patterns(), expand_foreign_server_name_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fetchAttributeStats(), flagInhAttrs(), format_aggregate_signature(), format_function_signature(), get_language_name(), get_next_possible_free_pg_type_oid(), get_synchronized_snapshot(), getAccessMethods(), getAdditionalACLs(), getAggregates(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getLOs(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPartitioningInfo(), getPolicies(), getProcLangs(), getPublicationNamespaces(), getPublications(), getPublicationTables(), getRelationStatistics(), getRules(), getSchemaData(), getSubscriptionRelations(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), html_escaped_print(), is_superuser(), IsPagerNeeded(), latex_escaped_print(), main(), main(), openQueryOutputFile(), output_row(), PQprint(), PQprintTuples(), print_aligned_text(), print_aligned_vertical(), print_aligned_vertical_line(), print_asciidoc_text(), print_asciidoc_vertical(), print_csv_text(), print_csv_vertical(), print_html_text(), print_html_vertical(), print_latex_longtable_text(), print_latex_text(), print_latex_vertical(), print_separator(), print_troff_ms_text(), print_troff_ms_vertical(), print_unaligned_text(), print_unaligned_vertical(), printQuery(), PrintQueryStatus(), PrintQueryTuples(), printTable(), processExtensionTables(), refreshMatViewData(), selectDumpableAccessMethod(), selectDumpableCast(), selectDumpableNamespace(), selectDumpableObject(), selectDumpableProcLang(), selectDumpablePublicationObject(), selectDumpableStatisticsObject(), selectDumpableTable(), selectDumpableType(), setQFout(), and troff_ms_escaped_print().

◆ if_exists

int if_exists = 0
static

Definition at line 105 of file pg_dumpall.c.

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

◆ inserts

int inserts = 0
static

Definition at line 106 of file pg_dumpall.c.

Referenced by main().

◆ load_via_partition_root

int load_via_partition_root = 0
static

Definition at line 123 of file pg_dumpall.c.

Referenced by main().

◆ nilCatalogId

const CatalogId nilCatalogId = {0, 0}
static

◆ no_comments

int no_comments = 0
static

Definition at line 110 of file pg_dumpall.c.

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

◆ no_data

int no_data = 0
static

Definition at line 114 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_policies

int no_policies = 0
static

Definition at line 111 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_publications

int no_publications = 0
static

Definition at line 112 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_role_passwords

int no_role_passwords = 0
static

Definition at line 120 of file pg_dumpall.c.

Referenced by dumpRoles(), and main().

◆ no_schema

int no_schema = 0
static

Definition at line 115 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_security_labels

int no_security_labels = 0
static

Definition at line 113 of file pg_dumpall.c.

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

◆ no_statistics

int no_statistics = 0
static

Definition at line 116 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_subscriptions

int no_subscriptions = 0
static

Definition at line 117 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_table_access_method

int no_table_access_method = 0
static

Definition at line 107 of file pg_dumpall.c.

Referenced by main().

◆ no_tablespaces

int no_tablespaces = 0
static

Definition at line 108 of file pg_dumpall.c.

Referenced by main().

◆ no_toast_compression

int no_toast_compression = 0
static

Definition at line 118 of file pg_dumpall.c.

Referenced by main().

◆ no_unlogged_table_data

int no_unlogged_table_data = 0
static

Definition at line 119 of file pg_dumpall.c.

Referenced by main().

◆ on_conflict_do_nothing

int on_conflict_do_nothing = 0
static

Definition at line 124 of file pg_dumpall.c.

Referenced by main().

◆ OPF

◆ output_clean

bool output_clean = false
static

Definition at line 96 of file pg_dumpall.c.

Referenced by dumpDatabases(), and main().

◆ pg_dump_bin

char pg_dump_bin[MAXPGPATH]
static

Definition at line 93 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ pgdumpopts

PQExpBuffer pgdumpopts
static

Definition at line 94 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ restrict_key

char* restrict_key
static

Definition at line 138 of file pg_dumpall.c.

Referenced by main(), and valid_restrict_key().

◆ role_catalog

char role_catalog[10]
static

Definition at line 128 of file pg_dumpall.c.

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

◆ sequence_data

int sequence_data = 0
static

Definition at line 126 of file pg_dumpall.c.

Referenced by main().

◆ server_version

◆ skip_acls

bool skip_acls = false
static

Definition at line 97 of file pg_dumpall.c.

Referenced by dumpTablespaces(), and main().

◆ statistics_only

int statistics_only = 0
static

Definition at line 125 of file pg_dumpall.c.

Referenced by main(), and main().

◆ use_setsessauth

int use_setsessauth = 0
static

Definition at line 109 of file pg_dumpall.c.

Referenced by main(), and main().

◆ verbose

bool verbose = false
static

Definition at line 98 of file pg_dumpall.c.

Referenced by main().

◆ with_statistics

int with_statistics = 0
static

Definition at line 121 of file pg_dumpall.c.

Referenced by main(), and main().