Sub topic 2
Backing up roles and other cluster-wide objects
This chapter assumes you know basic SQL and psql, can use the Linux command line, and understand that one PostgreSQL cluster holds several databases. A pg_dump run covers one database only. Roles (user accounts) and tablespaces belong to the whole cluster, so you back them up separately.
Backing up roles and globals
Run pg_dumpall with --globals-only to save roles and tablespace definitions:
pg_dumpall -U postgres --globals-only > globals.sqlReplay this file on the target cluster before you restore any database.
Restoring plain SQL dumps with psql
A plain dump is a text file of SQL statements. Create it with pg_dump and restore it with psql. ON_ERROR_STOP=1 stops at the first error. --single-transaction applies the whole file in one transaction, so a failure leaves nothing half-applied.
pg_dump -U postgres -f mydb.sql mydb
psql -U postgres -d postgres -f globals.sql
createdb -U postgres mydb_restored
psql -U postgres -d mydb_restored -v ON_ERROR_STOP=1 --single-transaction -f mydb.sqlRestoring custom and directory dumps with pg_restore
The custom format (-Fc) and directory format (-Fd) are compressed. Only pg_restore reads them, and it can restore selected objects. --no-owner skips ownership commands, so the restored objects belong to the role running the restore.
pg_dump -U postgres -Fc -f mydb.dump mydb
createdb -U postgres mydb_restored
pg_restore -U postgres -d mydb_restored --no-owner mydb.dumpSpeeding up large dumps and restores with parallel jobs
The -j option runs several jobs at once. Parallel dumps require the directory format.
pg_dump -U postgres -Fd -j 4 -f mydb_dir mydb
createdb -U postgres mydb_restored
pg_restore -U postgres -j 4 -d mydb_restored mydb_dirTaking a physical base backup
pg_dump makes logical copies of data. pg_basebackup copies the cluster's data files directly. Point-in-time recovery needs this kind of base backup. The -Xs flag streams the WAL (write-ahead log) that the backup needs to be consistent. The role must have the REPLICATION attribute.
pg_basebackup -h localhost -U replicator -D /backups/base -Ft -z -Xs -PExercise
Why must you restore the globals file before restoring a database dump that owns objects created by those roles?
Show answer
Each database object records an owner role. If the role does not exist yet, the restore fails or the object lacks its owner. The globals file creates the roles and tablespaces first, so the database restore can refer to them.