Summary: In this tutorial, you’ll learn how to use the pg_dumpall tool to export the entire database cluster, including all databases, roles, and other global objects.
Introduction to pg_dumpall tool #
pg_dumpall is a command-line tool that allows you to export an entire PostgreSQL database cluster into a file.
Unlike the pg_dump tool, which exports a single database without roles and other global objects, the pg_dumpall exports all databases with global objects, including database roles, tablespaces, and privilege grants for configuration parameters. However, pg_dumpall only supports plain SQL format.
To use the pg_dumpall tool, you follow these steps:
- First, open your terminal.
- Second, execute the
pg_dumpallcommand:
pg_dumpall -h db_host -p db_port -U usernameCode language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)In this syntax:
db_hostis the database host you want to connect to. It defaults to the local PostgreSQL server.db_portis the port on which the PostgreSQL listens. It defaults to the port5432. Sincepg_dumpallreads all databases, you must connect to the PostgreSQL server with a superuser.
If you have multiple databases, pg_dumpall will prompt for a password each time it connects to each database if you use password authentication.
Therefore, using a PostgreSQL password file for using the pg_dumpall to automatically connect to a PostgreSQL server is much more convenient.
After having a dump file, you can restore it using the psql tool.
pg_dumpall examples #
The following command exports all databases on the local PostgreSQL server to a file:
pg_dumpall -U postgres > D:\backup\all.sqlCode language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)You can replace the path to the backup file with your actual one.
To dump only global objects, you use the -g flag:
pg_dumpall -g > D:\backup\globals.sqlCode language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)To restore the dump file to a PostgreSQL server, you use the psql tool:
psql -U postgres -f all.sqlCode language: PostgreSQL SQL dialect and PL/pgSQL (pgsql)Why Use pg_dumpall? #
- Cluster-wide Backup:
pg_dumpallcan back up all databases in a PostgreSQL instance. - Backup Roles and Tablespaces: Besides databases,
pg_dumpallbacks up the user roles and tablespaces. - Simplifies Server Migration:
pg_dumpallcan help transfer entire PostgreSQL clusters between servers.
Summary #
- Use the
pg_dumpalltool to export all databases, including user roles and tablespaces.