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

◆ PG_ROLES

#define PG_ROLES   "pg_roles "

Definition at line 129 of file pg_dumpall.c.

◆ PGDUMP_VERSIONSTR

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

Definition at line 43 of file pg_dumpall.c.

◆ SH_DECLARE

#define SH_DECLARE

Definition at line 62 of file pg_dumpall.c.

◆ SH_DEFINE

#define SH_DEFINE

Definition at line 63 of file pg_dumpall.c.

◆ SH_ELEMENT_TYPE

#define SH_ELEMENT_TYPE   RoleNameEntry

Definition at line 53 of file pg_dumpall.c.

◆ SH_EQUAL

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

Definition at line 57 of file pg_dumpall.c.

◆ SH_GET_HASH

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

Definition at line 59 of file pg_dumpall.c.

◆ SH_HASH_KEY

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

Definition at line 56 of file pg_dumpall.c.

◆ SH_KEY

#define SH_KEY   rolename

Definition at line 55 of file pg_dumpall.c.

◆ SH_KEY_TYPE

#define SH_KEY_TYPE   char *

Definition at line 54 of file pg_dumpall.c.

◆ SH_PREFIX

#define SH_PREFIX   rolename

Definition at line 52 of file pg_dumpall.c.

◆ SH_RAW_ALLOCATOR

#define SH_RAW_ALLOCATOR   pg_malloc0

Definition at line 61 of file pg_dumpall.c.

◆ SH_SCOPE

#define SH_SCOPE   static inline

Definition at line 60 of file pg_dumpall.c.

◆ SH_STORE_HASH

#define SH_STORE_HASH

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

2220{
2222 PGresult *res;
2223
2224 buildShSecLabelQuery(catalog_name, objectId, sql);
2225 res = executeQuery(conn, sql->data);
2226 emitShSecLabels(conn, res, buffer, objtype, objname);
2227
2228 PQclear(res);
2229 destroyPQExpBuffer(sql);
2230}
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 2268 of file pg_dumpall.c.

2270{
2271 PGresult *res;
2272 int i;
2273 PQExpBuffer names;
2274 int count = 0;
2275
2276 res = executeQuery(conn,
2277 "SELECT datname AS objname, 'database' AS objtype "
2278 "FROM pg_catalog.pg_database "
2279 "WHERE datallowconn AND datconnlimit != -2 "
2280 "UNION ALL "
2281 "SELECT rolname AS objname, 'role' AS objtype "
2282 "FROM pg_catalog.pg_roles "
2283 "UNION ALL "
2284 "SELECT spcname AS objname, 'tablespace' AS objtype "
2285 "FROM pg_catalog.pg_tablespace");
2286
2287 names = createPQExpBuffer();
2288
2289 for (i = 0; i < PQntuples(res); i++)
2290 {
2291 char *objname = PQgetvalue(res, i, 0);
2292 char *objtype = PQgetvalue(res, i, 1);
2293
2294 /* Skip excluded databases since they won't be in map.dat */
2295 if (strcmp(objtype, "database") == 0 &&
2297 continue;
2298
2299 if (strpbrk(objname, "\n\r"))
2300 {
2301 appendPQExpBuffer(names, " %s: \"", objtype);
2302 for (char *p = objname; *p; p++)
2303 {
2304 if (*p == '\n')
2305 appendPQExpBufferStr(names, "\\n");
2306 else if (*p == '\r')
2307 appendPQExpBufferStr(names, "\\r");
2308 else
2309 appendPQExpBufferChar(names, *p);
2310 }
2311 appendPQExpBufferStr(names, "\"\n");
2312 count++;
2313 }
2314 }
2315
2316 PQclear(res);
2317
2318 if (count > 0)
2319 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",
2320 names->data);
2321
2322 destroyPQExpBuffer(names);
2323}
int i
Definition isn.c:77
#define PQgetvalue
#define PQntuples
#define pg_fatal(...)
static SimpleStringList database_exclude_names
Definition pg_dumpall.c:135
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 2437 of file pg_dumpall.c.

2438{
2439 return ++dumpIdVal;
2440}
static int dumpIdVal
Definition pg_dumpall.c:139

References dumpIdVal.

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

◆ dropDBs()

static void dropDBs ( PGconn conn)
static

Definition at line 1813 of file pg_dumpall.c.

1814{
1815 PGresult *res;
1816 int i;
1817
1818 /*
1819 * Skip databases marked not datallowconn, since we'd be unable to connect
1820 * to them anyway. This must agree with dumpDatabases().
1821 */
1822 res = executeQuery(conn,
1823 "SELECT datname "
1824 "FROM pg_database d "
1825 "WHERE datallowconn AND datconnlimit != -2 "
1826 "ORDER BY datname");
1827
1828 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1829 fprintf(OPF, "--\n-- Drop databases (except postgres and template1)\n--\n\n");
1830
1831 for (i = 0; i < PQntuples(res); i++)
1832 {
1833 char *dbname = PQgetvalue(res, i, 0);
1835
1836 /*
1837 * Skip "postgres" and "template1"; dumpDatabases() will deal with
1838 * them specially. Also, be sure to skip "template0", even if for
1839 * some reason it's not marked !datallowconn.
1840 */
1841 if (strcmp(dbname, "template1") != 0 &&
1842 strcmp(dbname, "template0") != 0 &&
1843 strcmp(dbname, "postgres") != 0)
1844 {
1845 if (archDumpFormat == archNull)
1846 {
1847 appendPQExpBuffer(delQry, "DROP DATABASE %s%s;\n",
1848 if_exists ? "IF EXISTS " : "",
1849 fmtId(dbname));
1850 fprintf(OPF, "%s", delQry->data);
1851 }
1852 else
1853 {
1854 appendPQExpBuffer(delQry, "DROP DATABASE IF EXISTS %s;\n",
1855 fmtId(dbname));
1856
1858 nilCatalogId, /* catalog ID */
1859 createDumpId(), /* dump ID */
1860 ARCHIVE_OPTS(.tag = psprintf("DATABASE %s", fmtId(dbname)),
1861 .description = "DROP_GLOBAL",
1862 .section = SECTION_PRE_DATA,
1863 .createStmt = delQry->data));
1864 }
1865
1867 }
1868 }
1869
1870 PQclear(res);
1871
1872 if (archDumpFormat == archNull)
1873 fprintf(OPF, "\n\n");
1874}
#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:141
static int if_exists
Definition pg_dumpall.c:104
static ArchiveFormat archDumpFormat
Definition pg_dumpall.c:140
static int createDumpId(void)
static FILE * OPF
Definition pg_dumpall.c:131
static Archive * fout
Definition pg_dumpall.c:138
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 944 of file pg_dumpall.c.

945{
947 PGresult *res;
948 int i_rolname;
949 int i;
950
951 if (server_version >= 90600)
953 "SELECT rolname "
954 "FROM %s "
955 "WHERE rolname !~ '^pg_' "
956 "ORDER BY 1", role_catalog);
957 else
959 "SELECT rolname "
960 "FROM %s "
961 "ORDER BY 1", role_catalog);
962
963 res = executeQuery(conn, buf->data);
964
965 i_rolname = PQfnumber(res, "rolname");
966
967 if (PQntuples(res) > 0 && archDumpFormat == archNull)
968 fprintf(OPF, "--\n-- Drop roles\n--\n\n");
969
970 for (i = 0; i < PQntuples(res); i++)
971 {
972 const char *rolename;
974
975 rolename = PQgetvalue(res, i, i_rolname);
976
978 {
979 appendPQExpBuffer(delQry, "DROP ROLE %s%s;\n",
980 if_exists ? "IF EXISTS " : "",
981 fmtId(rolename));
982 fprintf(OPF, "%s", delQry->data);
983 }
984 else
985 {
986 appendPQExpBuffer(delQry, "DROP ROLE IF EXISTS %s;\n",
987 fmtId(rolename));
988
990 nilCatalogId, /* catalog ID */
991 createDumpId(), /* dump ID */
992 ARCHIVE_OPTS(.tag = psprintf("ROLE %s", fmtId(rolename)),
993 .description = "DROP_GLOBAL",
994 .section = SECTION_PRE_DATA,
995 .createStmt = delQry->data));
996 }
997
999 }
1000
1001 PQclear(res);
1003
1004 if (archDumpFormat == archNull)
1005 fprintf(OPF, "\n\n");
1006}
int PQfnumber(const PGresult *res, const char *field_name)
Definition fe-exec.c:3606
static int server_version
Definition pg_dumpall.c:121
static char role_catalog[10]
Definition pg_dumpall.c:127
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 1606 of file pg_dumpall.c.

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

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

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

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

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

References admin_option, appendPQExpBuffer(), appendPQExpBufferStr(), archDumpFormat, ARCHIVE_OPTS, ArchiveEntry(), archNull, atooid, buf, conn, createDumpId(), createPQExpBuffer(), description, destroyPQExpBuffer(), executeQuery(), exit_nicely(), fb(), fmtId(), fout, fprintf, i, inherit_option, 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 1012 of file pg_dumpall.c.

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

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

2331{
2332 char buf[64];
2333 time_t now = time(NULL);
2334
2335 if (strftime(buf, sizeof(buf), PGDUMP_STRFTIME_FMT, localtime(&now)) != 0)
2336 fprintf(OPF, "-- %s %s\n\n", msg, buf);
2337}
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 1881 of file pg_dumpall.c.

1882{
1884 PGresult *res;
1885
1886 printfPQExpBuffer(buf, "SELECT unnest(setconfig) FROM pg_db_role_setting "
1887 "WHERE setdatabase = 0 AND setrole = "
1888 "(SELECT oid FROM %s WHERE rolname = ",
1889 role_catalog);
1892
1893 res = executeQuery(conn, buf->data);
1894
1895 if (PQntuples(res) > 0 && archDumpFormat == archNull)
1896 {
1897 char *sanitized;
1898
1900 fprintf(OPF, "\n--\n-- User Config \"%s\"\n--\n\n", sanitized);
1901 free(sanitized);
1902 }
1903
1904 for (int i = 0; i < PQntuples(res); i++)
1905 {
1908 "ROLE", username, NULL, NULL,
1909 buf);
1910
1911 if (archDumpFormat == archNull)
1912 fprintf(OPF, "%s", buf->data);
1913 else
1915 nilCatalogId, /* catalog ID */
1916 createDumpId(), /* dump ID */
1917 ARCHIVE_OPTS(.tag = psprintf("ROLE %s", fmtId(username)),
1918 .description = "ROLE PROPERTIES",
1919 .section = SECTION_PRE_DATA,
1920 .createStmt = buf->data));
1921 }
1922
1923 PQclear(res);
1924
1926}
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 2236 of file pg_dumpall.c.

2237{
2238 PGresult *res;
2239
2240 pg_log_info("executing %s", query);
2241
2242 res = PQexec(conn, query);
2243 if (!res ||
2245 {
2246 pg_log_error("query failed: %s", PQerrorMessage(conn));
2247 pg_log_error_detail("Query was: %s", query);
2248 PQfinish(conn);
2249 exit_nicely(1);
2250 }
2251
2252 PQclear(res);
2253}
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:125
#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 1933 of file pg_dumpall.c.

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

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

145{
146 static struct option long_options[] = {
147 {"data-only", no_argument, NULL, 'a'},
148 {"clean", no_argument, NULL, 'c'},
149 {"encoding", required_argument, NULL, 'E'},
150 {"file", required_argument, NULL, 'f'},
151 {"globals-only", no_argument, NULL, 'g'},
152 {"host", required_argument, NULL, 'h'},
153 {"dbname", required_argument, NULL, 'd'},
154 {"database", required_argument, NULL, 'l'},
155 {"no-owner", no_argument, NULL, 'O'},
156 {"port", required_argument, NULL, 'p'},
157 {"roles-only", no_argument, NULL, 'r'},
158 {"schema-only", no_argument, NULL, 's'},
159 {"superuser", required_argument, NULL, 'S'},
160 {"tablespaces-only", no_argument, NULL, 't'},
161 {"username", required_argument, NULL, 'U'},
162 {"verbose", no_argument, NULL, 'v'},
163 {"no-password", no_argument, NULL, 'w'},
164 {"password", no_argument, NULL, 'W'},
165 {"no-privileges", no_argument, NULL, 'x'},
166 {"no-acl", no_argument, NULL, 'x'},
167 {"format", required_argument, NULL, 'F'},
168
169 /*
170 * the following options don't have an equivalent short option letter
171 */
172 {"attribute-inserts", no_argument, &column_inserts, 1},
173 {"binary-upgrade", no_argument, &binary_upgrade, 1},
174 {"column-inserts", no_argument, &column_inserts, 1},
175 {"disable-dollar-quoting", no_argument, &disable_dollar_quoting, 1},
176 {"disable-triggers", no_argument, &disable_triggers, 1},
177 {"exclude-database", required_argument, NULL, 6},
178 {"extra-float-digits", required_argument, NULL, 5},
179 {"if-exists", no_argument, &if_exists, 1},
180 {"inserts", no_argument, &inserts, 1},
181 {"lock-wait-timeout", required_argument, NULL, 2},
182 {"no-table-access-method", no_argument, &no_table_access_method, 1},
183 {"no-tablespaces", no_argument, &no_tablespaces, 1},
184 {"quote-all-identifiers", no_argument, &quote_all_identifiers, 1},
185 {"load-via-partition-root", no_argument, &load_via_partition_root, 1},
186 {"role", required_argument, NULL, 3},
187 {"use-set-session-authorization", no_argument, &use_setsessauth, 1},
188 {"no-comments", no_argument, &no_comments, 1},
189 {"no-data", no_argument, &no_data, 1},
190 {"no-policies", no_argument, &no_policies, 1},
191 {"no-publications", no_argument, &no_publications, 1},
192 {"no-role-passwords", no_argument, &no_role_passwords, 1},
193 {"no-schema", no_argument, &no_schema, 1},
194 {"no-security-labels", no_argument, &no_security_labels, 1},
195 {"no-subscriptions", no_argument, &no_subscriptions, 1},
196 {"no-statistics", no_argument, &no_statistics, 1},
197 {"no-sync", no_argument, NULL, 4},
198 {"no-toast-compression", no_argument, &no_toast_compression, 1},
199 {"no-unlogged-table-data", no_argument, &no_unlogged_table_data, 1},
200 {"on-conflict-do-nothing", no_argument, &on_conflict_do_nothing, 1},
201 {"rows-per-insert", required_argument, NULL, 7},
202 {"statistics", no_argument, &with_statistics, 1},
203 {"statistics-only", no_argument, &statistics_only, 1},
204 {"filter", required_argument, NULL, 8},
205 {"sequence-data", no_argument, &sequence_data, 1},
206 {"restrict-key", required_argument, NULL, 9},
207
208 {NULL, 0, NULL, 0}
209 };
210
211 char *pghost = NULL;
212 char *pgport = NULL;
213 char *pguser = NULL;
214 char *pgdb = NULL;
215 char *use_role = NULL;
216 const char *dumpencoding = NULL;
217 const char *format_name = "p";
218 trivalue prompt_password = TRI_DEFAULT;
219 bool data_only = false;
220 bool globals_only = false;
221 bool roles_only = false;
222 bool tablespaces_only = false;
223 PGconn *conn;
224 int encoding;
225 int c,
226 ret;
227 int optindex;
228 DumpOptions dopt;
229
230 pg_logging_init(argv[0]);
232 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_dump"));
233 progname = get_progname(argv[0]);
234
235 if (argc > 1)
236 {
237 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
238 {
239 help();
240 exit_nicely(0);
241 }
242 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
243 {
244 puts("pg_dumpall (PostgreSQL) " PG_VERSION);
245 exit_nicely(0);
246 }
247 }
248
249 if ((ret = find_other_exec(argv[0], "pg_dump", PGDUMP_VERSIONSTR,
250 pg_dump_bin)) < 0)
251 {
252 char full_path[MAXPGPATH];
253
254 if (find_my_exec(argv[0], full_path) < 0)
256
257 if (ret == -1)
258 pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
259 "pg_dump", progname, full_path);
260 else
261 pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
262 "pg_dump", full_path, progname);
263 }
264
266 InitDumpOptions(&dopt);
267
268 while ((c = getopt_long(argc, argv, "acd:E:f:F:gh:l:Op:rsS:tU:vwWx", long_options, &optindex)) != -1)
269 {
270 switch (c)
271 {
272 case 'a':
273 data_only = true;
275 break;
276
277 case 'c':
278 output_clean = true;
279 break;
280
281 case 'd':
283 break;
284
285 case 'E':
289 break;
290
291 case 'f':
295 break;
296 case 'F':
298 break;
299 case 'g':
300 globals_only = true;
301 break;
302
303 case 'h':
305 break;
306
307 case 'l':
309 break;
310
311 case 'O':
313 break;
314
315 case 'p':
317 break;
318
319 case 'r':
320 roles_only = true;
321 break;
322
323 case 's':
325 break;
326
327 case 'S':
330 break;
331
332 case 't':
333 tablespaces_only = true;
334 break;
335
336 case 'U':
337 pguser = pg_strdup(optarg);
339 break;
340
341 case 'v':
342 verbose = true;
345 break;
346
347 case 'w':
348 prompt_password = TRI_NO;
350 break;
351
352 case 'W':
353 prompt_password = TRI_YES;
355 break;
356
357 case 'x':
358 skip_acls = true;
360 break;
361
362 case 0:
363 break;
364
365 case 2:
366 appendPQExpBufferStr(pgdumpopts, " --lock-wait-timeout ");
368 break;
369
370 case 3:
371 use_role = pg_strdup(optarg);
372 appendPQExpBufferStr(pgdumpopts, " --role ");
373 appendShellString(pgdumpopts, use_role);
374 break;
375
376 case 4:
377 dosync = false;
378 appendPQExpBufferStr(pgdumpopts, " --no-sync");
379 break;
380
381 case 5:
382 appendPQExpBufferStr(pgdumpopts, " --extra-float-digits ");
384 break;
385
386 case 6:
388 break;
389
390 case 7:
391 appendPQExpBufferStr(pgdumpopts, " --rows-per-insert ");
393 break;
394
395 case 8:
397 break;
398
399 case 9:
401 appendPQExpBufferStr(pgdumpopts, " --restrict-key ");
403 break;
404
405 default:
406 /* getopt_long already emitted a complaint */
407 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
408 exit_nicely(1);
409 }
410 }
411
412 /* Complain if any arguments remain */
413 if (optind < argc)
414 {
415 pg_log_error("too many command-line arguments (first is \"%s\")",
416 argv[optind]);
417 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
418 exit_nicely(1);
419 }
420
423 {
424 pg_log_error("option %s cannot be used together with %s, %s, or %s",
425 "--exclude-database",
426 "-g/--globals-only", "-r/--roles-only", "-t/--tablespaces-only");
427 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
428 exit_nicely(1);
429 }
430
431 /* Make sure the user hasn't specified a mix of globals-only options */
433 {
434 pg_log_error("options %s and %s cannot be used together",
435 "-g/--globals-only", "-r/--roles-only");
436 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
437 exit_nicely(1);
438 }
439
441 {
442 pg_log_error("options %s and %s cannot be used together",
443 "-g/--globals-only", "-t/--tablespaces-only");
444 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
445 exit_nicely(1);
446 }
447
448 if (if_exists && !output_clean)
449 pg_fatal("option %s requires option %s",
450 "--if-exists", "-c/--clean");
451
453 {
454 pg_log_error("options %s and %s cannot be used together",
455 "-r/--roles-only", "-t/--tablespaces-only");
456 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
457 exit_nicely(1);
458 }
459
460 /* Get format for dump. */
462
463 /*
464 * If a non-plain format is specified, a file name is also required as the
465 * path to the main directory.
466 */
467 if (archDumpFormat != archNull &&
468 (!filename || strcmp(filename, "") == 0))
469 {
470 pg_log_error("option %s=d|c|t requires option %s",
471 "-F/--format", "-f/--file");
472 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
473 exit_nicely(1);
474 }
475
476 /* restrict-key is only supported with --format=plain */
478 pg_fatal("option %s can only be used with %s=plain",
479 "--restrict-key", "--format");
480
481 /* --clean and -g/--globals-only cannot be used together in non-text dump */
483 pg_fatal("options %s and %s cannot be used together in non-text dump",
484 "--clean", "-g/--globals-only");
485
486 /*
487 * If password values are not required in the dump, switch to using
488 * pg_roles which is equally useful, just more likely to have unrestricted
489 * access than pg_authid.
490 */
493 else
495
496 /* Add long options to the pg_dump argument list */
497 if (binary_upgrade)
498 appendPQExpBufferStr(pgdumpopts, " --binary-upgrade");
499 if (column_inserts)
500 appendPQExpBufferStr(pgdumpopts, " --column-inserts");
502 appendPQExpBufferStr(pgdumpopts, " --disable-dollar-quoting");
504 appendPQExpBufferStr(pgdumpopts, " --disable-triggers");
505 if (inserts)
506 appendPQExpBufferStr(pgdumpopts, " --inserts");
508 appendPQExpBufferStr(pgdumpopts, " --no-table-access-method");
509 if (no_tablespaces)
510 appendPQExpBufferStr(pgdumpopts, " --no-tablespaces");
512 appendPQExpBufferStr(pgdumpopts, " --quote-all-identifiers");
514 appendPQExpBufferStr(pgdumpopts, " --load-via-partition-root");
515 if (use_setsessauth)
516 appendPQExpBufferStr(pgdumpopts, " --use-set-session-authorization");
517 if (no_comments)
518 appendPQExpBufferStr(pgdumpopts, " --no-comments");
519 if (no_data)
520 appendPQExpBufferStr(pgdumpopts, " --no-data");
521 if (no_policies)
522 appendPQExpBufferStr(pgdumpopts, " --no-policies");
523 if (no_publications)
524 appendPQExpBufferStr(pgdumpopts, " --no-publications");
526 appendPQExpBufferStr(pgdumpopts, " --no-security-labels");
527 if (no_schema)
528 appendPQExpBufferStr(pgdumpopts, " --no-schema");
529 if (no_statistics)
530 appendPQExpBufferStr(pgdumpopts, " --no-statistics");
532 appendPQExpBufferStr(pgdumpopts, " --no-subscriptions");
534 appendPQExpBufferStr(pgdumpopts, " --no-toast-compression");
536 appendPQExpBufferStr(pgdumpopts, " --no-unlogged-table-data");
537 if (with_statistics)
538 appendPQExpBufferStr(pgdumpopts, " --statistics");
540 appendPQExpBufferStr(pgdumpopts, " --on-conflict-do-nothing");
541 if (statistics_only)
542 appendPQExpBufferStr(pgdumpopts, " --statistics-only");
543 if (sequence_data)
544 appendPQExpBufferStr(pgdumpopts, " --sequence-data");
545
546 /*
547 * Open the output file if required, otherwise use stdout. If required,
548 * then create new directory.
549 */
551 {
553
554 /* Create new directory or accept the empty existing directory. */
556 }
557 else if (filename)
558 {
560 if (!OPF)
561 pg_fatal("could not open output file \"%s\": %m",
562 filename);
563 }
564 else
565 OPF = stdout;
566
567 /*
568 * If you don't provide a restrict key, one will be appointed for you.
569 */
570 if (!restrict_key)
572 if (!restrict_key)
573 pg_fatal("could not generate restrict key");
575 pg_fatal("invalid restrict key");
576
577 /*
578 * If there was a database specified on the command line, use that,
579 * otherwise try to connect to database "postgres", and failing that
580 * "template1".
581 */
582 if (pgdb)
583 {
585 prompt_password, false,
587
588 if (!conn)
589 pg_fatal("could not connect to database \"%s\"", pgdb);
590 }
591 else
592 {
593 conn = ConnectDatabase("postgres", connstr, pghost, pgport, pguser,
594 prompt_password, false,
596 if (!conn)
597 conn = ConnectDatabase("template1", connstr, pghost, pgport, pguser,
598 prompt_password, true,
600
601 if (!conn)
602 {
603 pg_log_error("could not connect to databases \"postgres\" or \"template1\"\n"
604 "Please specify an alternative database.");
605 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
606 exit_nicely(1);
607 }
608 }
609
610 /*
611 * Get a list of database names that match the exclude patterns
612 */
615
616 /*
617 * Set the client encoding if requested.
618 */
619 if (dumpencoding)
620 {
622 pg_fatal("invalid client encoding \"%s\" specified",
624 }
625
626 /*
627 * Force standard_conforming_strings on, just in case we are dumping from
628 * an old server that has it disabled. Without this, literals in views,
629 * expressions, etc, would be incorrect for modern servers.
630 */
631 executeCommand(conn, "SET standard_conforming_strings = on");
632
633 /*
634 * Get the active encoding, so we know how to escape strings.
635 */
638
639 /* Set the role if requested */
640 if (use_role)
641 {
643
644 appendPQExpBuffer(query, "SET ROLE %s", fmtId(use_role));
645 executeCommand(conn, query->data);
646 destroyPQExpBuffer(query);
647 }
648
649 /* Force quoting of all identifiers if requested. */
651 executeCommand(conn, "SET quote_all_identifiers = true");
652
653 /* create a archive file for global commands. */
655 {
658 const char *encname;
659 pg_compress_specification compression_spec = {0};
660
661 /*
662 * Check that no global object names contain newlines or carriage
663 * returns, which would break the map.dat file format. This is only
664 * needed for servers older than v19, which started prohibiting such
665 * names.
666 */
667 if (server_version < 190000)
669
670 /* Set file path for global sql commands. */
671 snprintf(global_path, MAXPGPATH, "%s/toc.glo", filename);
672
673 /* Open the output file */
674 fout = CreateArchive(global_path, archCustom, compression_spec,
676
677 /* Make dump options accessible right away */
678 SetArchiveOptions(fout, &dopt, NULL);
679
680 ((ArchiveHandle *) fout)->connection = conn;
681 ((ArchiveHandle *) fout)->public.numWorkers = 1;
682
683 /* Register the cleanup hook */
685
686 /* Let the archiver know how noisy to be */
688
689 /*
690 * We allow the server to be back to 9.2, and up to any minor release
691 * of our own major version. (See also version check in
692 * pg_dumpall.c.)
693 */
694 fout->minRemoteVersion = 90200;
695 fout->maxRemoteVersion = (PG_VERSION_NUM / 100) * 100 + 99;
696 fout->numWorkers = 1;
697
698 /* Dump default_transaction_read_only. */
699 appendPQExpBufferStr(qry, "SET default_transaction_read_only = off;\n\n");
701 nilCatalogId, /* catalog ID */
702 createDumpId(), /* dump ID */
703 ARCHIVE_OPTS(.tag = "default_transaction_read_only",
704 .description = "default_transaction_read_only",
705 .section = SECTION_PRE_DATA,
706 .createStmt = qry->data));
707 resetPQExpBuffer(qry);
708
709 /* Put the correct encoding into the archive */
711
712 appendPQExpBufferStr(qry, "SET client_encoding = ");
714 appendPQExpBufferStr(qry, ";\n");
716 nilCatalogId, /* catalog ID */
717 createDumpId(), /* dump ID */
718 ARCHIVE_OPTS(.tag = "client_encoding",
719 .description = "client_encoding",
720 .section = SECTION_PRE_DATA,
721 .createStmt = qry->data));
722 resetPQExpBuffer(qry);
723
724 /* Put the correct escape string behavior into the archive. */
725 appendPQExpBuffer(qry, "SET standard_conforming_strings = 'on';\n");
727 nilCatalogId, /* catalog ID */
728 createDumpId(), /* dump ID */
729 ARCHIVE_OPTS(.tag = "standard_conforming_strings",
730 .description = "standard_conforming_strings",
731 .section = SECTION_PRE_DATA,
732 .createStmt = qry->data));
734 }
735 else
736 {
737 fprintf(OPF, "--\n-- PostgreSQL database cluster dump\n--\n\n");
738
739 if (verbose)
740 dumpTimestamp("Started on");
741
742 /*
743 * Enter restricted mode to block any unexpected psql meta-commands. A
744 * malicious source might try to inject a variety of things via bogus
745 * responses to queries. While we cannot prevent such sources from
746 * affecting the destination at restore time, we can block psql
747 * meta-commands so that the client machine that runs psql with the
748 * dump output remains unaffected.
749 */
750 fprintf(OPF, "\\restrict %s\n\n", restrict_key);
751
752 /*
753 * We used to emit \connect postgres here, but that served no purpose
754 * other than to break things for installations without a postgres
755 * database. Everything we're restoring here is a global, so
756 * whichever database we're connected to at the moment is fine.
757 */
758
759 /* Restore will need to write to the target cluster */
760 fprintf(OPF, "SET default_transaction_read_only = off;\n\n");
761
762 /* Replicate encoding and standard_conforming_strings in output */
763 fprintf(OPF, "SET client_encoding = '%s';\n",
765 fprintf(OPF, "SET standard_conforming_strings = on;\n");
766 fprintf(OPF, "\n");
767 }
768
770 {
771 /*
772 * If asked to --clean, do that first. We can avoid detailed
773 * dependency analysis because databases never depend on each other,
774 * and tablespaces never depend on each other. Roles could have
775 * grants to each other, but DROP ROLE will clean those up silently.
776 *
777 * For non-text formats, pg_dumpall unconditionally process --clean
778 * option. In contrast, pg_restore only applies it if the user
779 * explicitly provides the flag. This discrepancy resolves corner
780 * cases where pg_restore requires cleanup instructions that may be
781 * missing from a standard pg_dumpall output.
782 */
784 {
786 dropDBs(conn);
787
788 if (!roles_only && !no_tablespaces)
790
791 if (!tablespaces_only)
793 }
794
795 /*
796 * Now create objects as requested. Be careful that option logic here
797 * is the same as for drops above.
798 */
799 if (!tablespaces_only)
800 {
801 /* Dump roles (users) */
803
804 /* Dump role memberships */
806
807 /* Dump role GUC privileges */
808 if (server_version >= 150000 && !skip_acls)
810 }
811
812 /* Dump tablespaces */
813 if (!roles_only && !no_tablespaces)
815 }
816
818 {
819 /*
820 * Exit restricted mode just before dumping the databases. pg_dump
821 * will handle entering restricted mode again as appropriate.
822 */
823 fprintf(OPF, "\\unrestrict %s\n\n", restrict_key);
824 }
825
828
830 {
831 PQfinish(conn);
832
833 if (verbose)
834 dumpTimestamp("Completed on");
835 fprintf(OPF, "--\n-- PostgreSQL database cluster dump complete\n--\n\n");
836
837 if (filename)
838 {
839 fclose(OPF);
840
841 /* sync the resulting file, errors are not fatal */
842 if (dosync)
843 (void) fsync_fname(filename, false);
844 }
845 }
846 else
847 {
848 RestoreOptions *ropt;
849
850 ropt = NewRestoreOptions();
851 SetArchiveOptions(fout, &dopt, ropt);
852
853 /* Mark which entries should be output */
856 }
857
858 exit_nicely(0);
859}
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:1252
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:756
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
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:123
static void dropTablespaces(PGconn *conn)
static void expand_dbname_patterns(PGconn *conn, SimpleStringList *patterns, SimpleStringList *names)
static PQExpBuffer pgdumpopts
Definition pg_dumpall.c:93
static int statistics_only
Definition pg_dumpall.c:124
static int no_table_access_method
Definition pg_dumpall.c:106
static int no_unlogged_table_data
Definition pg_dumpall.c:118
static void check_for_invalid_global_names(PGconn *conn, SimpleStringList *database_exclude_names)
#define PG_AUTHID
Definition pg_dumpall.c:128
static int no_policies
Definition pg_dumpall.c:110
static int disable_triggers
Definition pg_dumpall.c:103
static bool dosync
Definition pg_dumpall.c:98
static const char * connstr
Definition pg_dumpall.c:94
static SimpleStringList database_exclude_patterns
Definition pg_dumpall.c:134
static void dumpTablespaces(PGconn *conn)
static void dumpRoleMembership(PGconn *conn)
static char pg_dump_bin[MAXPGPATH]
Definition pg_dumpall.c:92
static int no_publications
Definition pg_dumpall.c:111
static int sequence_data
Definition pg_dumpall.c:125
static char * restrict_key
Definition pg_dumpall.c:137
static void dumpDatabases(PGconn *conn)
static ArchiveFormat parseDumpFormat(const char *format)
static int disable_dollar_quoting
Definition pg_dumpall.c:102
static int no_tablespaces
Definition pg_dumpall.c:107
static int no_toast_compression
Definition pg_dumpall.c:117
#define PG_ROLES
Definition pg_dumpall.c:129
static int inserts
Definition pg_dumpall.c:105
static void executeCommand(PGconn *conn, const char *query)
static bool verbose
Definition pg_dumpall.c:97
static void dumpRoleGUCPrivs(PGconn *conn)
static int no_statistics
Definition pg_dumpall.c:115
static void dumpRoles(PGconn *conn)
static void help(void)
Definition pg_dumpall.c:863
static int use_setsessauth
Definition pg_dumpall.c:108
static int no_data
Definition pg_dumpall.c:113
static int load_via_partition_root
Definition pg_dumpall.c:122
static int column_inserts
Definition pg_dumpall.c:101
static void read_dumpall_filters(const char *filename, SimpleStringList *pattern)
static void dropRoles(PGconn *conn)
Definition pg_dumpall.c:944
static void dropDBs(PGconn *conn)
static int no_schema
Definition pg_dumpall.c:114
static int no_subscriptions
Definition pg_dumpall.c:116
static int with_statistics
Definition pg_dumpall.c:120
#define PGDUMP_VERSIONSTR
Definition pg_dumpall.c:43
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(), 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 2404 of file pg_dumpall.c.

2405{
2407
2408 if (pg_strcasecmp(format, "c") == 0)
2410 else if (pg_strcasecmp(format, "custom") == 0)
2412 else if (pg_strcasecmp(format, "d") == 0)
2414 else if (pg_strcasecmp(format, "directory") == 0)
2416 else if (pg_strcasecmp(format, "p") == 0)
2418 else if (pg_strcasecmp(format, "plain") == 0)
2420 else if (pg_strcasecmp(format, "t") == 0)
2422 else if (pg_strcasecmp(format, "tar") == 0)
2424 else
2425 pg_fatal("unrecognized output format \"%s\"; please specify \"c\", \"d\", \"p\", or \"t\"",
2426 format);
2427
2428 return archDumpFormat;
2429}
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 2349 of file pg_dumpall.c.

2350{
2352 char *objname;
2354 FilterObjectType objtype;
2355
2357
2358 while (filter_read_item(&fstate, &objname, &comtype, &objtype))
2359 {
2361 {
2362 pg_log_filter_error(&fstate, _("%s filter for \"%s\" is not allowed"),
2363 "include",
2364 filter_object_type_name(objtype));
2365 exit_nicely(1);
2366 }
2367
2368 switch (objtype)
2369 {
2371 break;
2382 pg_log_filter_error(&fstate, _("unsupported filter object"));
2383 exit_nicely(1);
2384 break;
2385
2387 simple_string_list_append(pattern, objname);
2388 break;
2389 }
2390
2391 if (objname)
2392 free(objname);
2393 }
2394
2396}
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 2144 of file pg_dumpall.c.

2145{
2147 PQExpBufferData cmd;
2148 int ret;
2149
2151 initPQExpBuffer(&cmd);
2152
2153 /*
2154 * If this is not a plain format dump, then append file name and dump
2155 * format to the pg_dump command to get archive dump.
2156 */
2157 if (archDumpFormat != archNull)
2158 {
2159 printfPQExpBuffer(&cmd, "\"%s\" %s -f %s %s", pg_dump_bin,
2161
2163 appendPQExpBufferStr(&cmd, " --format=directory ");
2164 else if (archDumpFormat == archCustom)
2165 appendPQExpBufferStr(&cmd, " --format=custom ");
2166 else if (archDumpFormat == archTar)
2167 appendPQExpBufferStr(&cmd, " --format=tar ");
2168 }
2169 else
2170 {
2171 printfPQExpBuffer(&cmd, "\"%s\" %s %s", pg_dump_bin,
2173
2174 /*
2175 * If we have a filename, use the undocumented plain-append pg_dump
2176 * format.
2177 */
2178 if (filename)
2179 appendPQExpBufferStr(&cmd, " -Fa ");
2180 else
2181 appendPQExpBufferStr(&cmd, " -Fp ");
2182 }
2183
2184 /*
2185 * Append the database name to the already-constructed stem of connection
2186 * string.
2187 */
2188 appendPQExpBuffer(&connstrbuf, "%s dbname=", connstr);
2190
2191 appendShellString(&cmd, connstrbuf.data);
2192
2193 pg_log_info("running \"%s\"", cmd.data);
2194
2195 fflush(NULL);
2196
2197 ret = system(cmd.data);
2198
2199 termPQExpBuffer(&cmd);
2201
2202 return ret;
2203}
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 100 of file pg_dumpall.c.

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

◆ column_inserts

int column_inserts = 0
static

Definition at line 101 of file pg_dumpall.c.

Referenced by main().

◆ connstr

◆ database_exclude_names

SimpleStringList database_exclude_names = {NULL, NULL}
static

Definition at line 135 of file pg_dumpall.c.

135{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 134 of file pg_dumpall.c.

134{NULL, NULL};

Referenced by main().

◆ disable_dollar_quoting

int disable_dollar_quoting = 0
static

Definition at line 102 of file pg_dumpall.c.

Referenced by main().

◆ disable_triggers

int disable_triggers = 0
static

Definition at line 103 of file pg_dumpall.c.

Referenced by main(), and main().

◆ dosync

bool dosync = true
static

Definition at line 98 of file pg_dumpall.c.

Referenced by main().

◆ dumpIdVal

int dumpIdVal = 0
static

Definition at line 139 of file pg_dumpall.c.

Referenced by createDumpId().

◆ filename

char* filename = NULL
static

Definition at line 132 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 138 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 104 of file pg_dumpall.c.

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

◆ inserts

int inserts = 0
static

Definition at line 105 of file pg_dumpall.c.

Referenced by main().

◆ load_via_partition_root

int load_via_partition_root = 0
static

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

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

◆ no_data

int no_data = 0
static

Definition at line 113 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_policies

int no_policies = 0
static

Definition at line 110 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_publications

int no_publications = 0
static

Definition at line 111 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_role_passwords

int no_role_passwords = 0
static

Definition at line 119 of file pg_dumpall.c.

Referenced by dumpRoles(), and main().

◆ no_schema

int no_schema = 0
static

Definition at line 114 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_security_labels

int no_security_labels = 0
static

Definition at line 112 of file pg_dumpall.c.

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

◆ no_statistics

int no_statistics = 0
static

Definition at line 115 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_subscriptions

int no_subscriptions = 0
static

Definition at line 116 of file pg_dumpall.c.

Referenced by main(), and main().

◆ no_table_access_method

int no_table_access_method = 0
static

Definition at line 106 of file pg_dumpall.c.

Referenced by main().

◆ no_tablespaces

int no_tablespaces = 0
static

Definition at line 107 of file pg_dumpall.c.

Referenced by main().

◆ no_toast_compression

int no_toast_compression = 0
static

Definition at line 117 of file pg_dumpall.c.

Referenced by main().

◆ no_unlogged_table_data

int no_unlogged_table_data = 0
static

Definition at line 118 of file pg_dumpall.c.

Referenced by main().

◆ on_conflict_do_nothing

int on_conflict_do_nothing = 0
static

Definition at line 123 of file pg_dumpall.c.

Referenced by main().

◆ OPF

◆ output_clean

bool output_clean = false
static

Definition at line 95 of file pg_dumpall.c.

Referenced by dumpDatabases(), and main().

◆ pg_dump_bin

char pg_dump_bin[MAXPGPATH]
static

Definition at line 92 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ pgdumpopts

PQExpBuffer pgdumpopts
static

Definition at line 93 of file pg_dumpall.c.

Referenced by main(), and runPgDump().

◆ restrict_key

char* restrict_key
static

Definition at line 137 of file pg_dumpall.c.

Referenced by main(), and valid_restrict_key().

◆ role_catalog

char role_catalog[10]
static

Definition at line 127 of file pg_dumpall.c.

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

◆ sequence_data

int sequence_data = 0
static

Definition at line 125 of file pg_dumpall.c.

Referenced by main().

◆ server_version

◆ skip_acls

bool skip_acls = false
static

Definition at line 96 of file pg_dumpall.c.

Referenced by dumpTablespaces(), and main().

◆ statistics_only

int statistics_only = 0
static

Definition at line 124 of file pg_dumpall.c.

Referenced by main(), and main().

◆ use_setsessauth

int use_setsessauth = 0
static

Definition at line 108 of file pg_dumpall.c.

Referenced by main(), and main().

◆ verbose

bool verbose = false
static

Definition at line 97 of file pg_dumpall.c.

Referenced by main().

◆ with_statistics

int with_statistics = 0
static

Definition at line 120 of file pg_dumpall.c.

Referenced by main(), and main().