Sub topic 7
Restoring custom and directory dumps with pg_restore
This chapter assumes you can use psql and the Linux command line, and that you know what a PostgreSQL role and a transaction are. It also assumes you have made a custom-format or directory-format dump with pg_dump, as covered in the earlier chapters.
What pg_restore does
pg_restore reads an archive written by pg_dump -Fc (custom) or pg_dump -Fd (directory). It can also read -Ft (tar) archives. It cannot read plain SQL dumps, which you restore with psql.
The archive contains a table of contents plus the data for each object. Because of that table of contents, pg_restore can do things psql cannot:
- Restore only some tables or schemas.
- Reorder or skip items.
- Run several restore jobs in parallel.
- Restore in phases.
Without -d, pg_restore does not touch a database. It prints the equivalent SQL script to standard output. This is a handy way to inspect what a restore would do.
pg_restore mydb.dump | lessA basic restore
The simplest restore targets an empty database that already exists.
createdb -U postgres mydb_restored
pg_restore -U postgres -d mydb_restored --no-owner mydb.dump--no-owner skips the ALTER ... OWNER TO commands, so every object is owned by the user running the restore. Use it when the original roles do not exist on the target. Otherwise the restore prints an error for every object whose owner is missing. --no-privileges does the same for GRANT and REVOKE commands.
Directory dumps are restored the same way. You pass the directory name instead of a file:
pg_restore -U postgres -d mydb_restored mydb_dirLetting pg_restore create the database
With --create, pg_restore issues CREATE DATABASE itself and then connects to the new database. The -d option then names a database to connect to first, not the one to restore into. Use an existing maintenance database such as postgres.
pg_restore -U postgres -d postgres --create mydb.dumpThis recreates the database with its original name, owner, and database-level settings. If the database already exists, the command fails. Add --clean --if-exists to drop it first:
pg_restore -U postgres -d postgres --clean --if-exists --create mydb.dumpWithout --create, --clean drops each object inside the target database before recreating it. --if-exists suppresses the "does not exist" errors on a fresh target.
Error handling
By default, pg_restore keeps going after an error. It prints each failure and reports a count at the end. This is useful when a few harmless errors, such as a missing role, should not stop a large restore. It is also dangerous, because a half-restored database can look finished.
You have two options for strict behavior:
| Option | Behavior |
|---|---|
| `--exit-on-error` (`-e`) | Stops at the first error. Earlier changes stay committed. |
| `--single-transaction` (`-1`) | Runs everything in one transaction. Any error rolls back the whole restore. |
pg_restore -U postgres -d mydb_restored --single-transaction --no-owner mydb.dump--single-transaction cannot be combined with -j, because parallel workers use separate connections.
Restoring selected objects
You can restore part of a dump with filter options.
-t tablerestores one table. Repeat the option for more tables.-n schemarestores one schema.--schema-onlyrestores definitions without rows.--data-onlyrestores rows into tables that already exist.
pg_restore -U postgres -d mydb_restored -n sales -t orders mydb.dumpFilters do not pull in dependencies. If orders needs a sequence, a type, or a referenced table that you did not select, the restore of that table can fail or lose its constraints. Restore the dependencies first, or use a list file as described next.
Using a list file
For precise control, write the table of contents to a file, edit it, and feed it back with -L.
pg_restore --list mydb.dump > mydb.listEach line describes one object, for example a table, an index, or a block of table data. Put a semicolon at the start of a line to skip that item. You can also reorder lines, and pg_restore follows your order where dependencies allow. Then restore using the edited list:
pg_restore -U postgres -d mydb_restored -L mydb.list mydb.dumpThe same --list option, piped through head, is a quick check that an archive is readable:
pg_restore --list mydb.dump | head -n 20Restoring in sections
A dump has three sections, and --section restores one at a time.
pre-data: table definitions, types, functions, and other schema objects.data: table rows and sequence values.post-data: indexes, constraints, triggers, and rules.
pg_restore already loads data before it builds indexes and constraints, because that is much faster than loading into indexed tables. Sections are useful when you need to change something between steps, for example inspecting the schema before loading rows.
pg_restore -U postgres -d mydb_restored --section=pre-data mydb.dump
pg_restore -U postgres -d mydb_restored --section=data mydb.dump
pg_restore -U postgres -d mydb_restored --section=post-data mydb.dumpParallel restore
With -j N, pg_restore opens N connections and loads tables and builds indexes concurrently. This works only for custom and directory formats.
pg_restore -U postgres -j 4 -d mydb_restored mydb_dirIndex builds, which dominate restore time on large databases, gain the most. A common starting value for -j is the number of CPU cores or fewer on the target, but disk speed often becomes the limit first. For a custom-format file, pg_restore must be able to seek in the file, so you cannot pipe the archive in through standard input and use -j.
Restoring roles first
A dump references roles by name, but it does not contain them. Restore the globals on the target cluster before the database. The pg_dumpall --globals-only file from the earlier chapter is replayed with psql:
psql -U postgres -d postgres -f globals.sql
pg_restore -U postgres -d postgres --create mydb.dumpWithout the roles, you see errors such as role "app_user" does not exist. Either restore the globals or use --no-owner and --no-privileges and set ownership yourself.
Version and extension gotchas
- Use a
pg_restorethat is the same version as the target server or newer. A newerpg_restorereads archives from olderpg_dumpversions. An older one may refuse an archive from a newerpg_dump. - Extensions are stored as
CREATE EXTENSIONcommands, not as their files. The extension packages, such aspostgis, must be installed on the target server first. They should be a compatible version. - Dump files do not carry the cluster configuration. Settings in
postgresql.conf, along withpg_hba.conf, must be reproduced separately. - Depending on your PostgreSQL version, planner statistics may not be restored. Run
ANALYZEafter a large restore so queries get good plans.
A restore workflow
The diagram shows a typical decision path for restoring a dump.
Putting it together
This sequence performs a parallel, cleaned restore into a new database. It stops if any command fails.
set -e
psql -U postgres -d postgres -v ON_ERROR_STOP=1 -f globals.sql
pg_restore -U postgres -d postgres --clean --if-exists --create \
--exit-on-error -j 4 mydb_dir
psql -U postgres -d mydb -c "ANALYZE"Exercise
You must restore only the table sales.orders from a custom-format dump into an existing database, and the restore must not leave the table half-loaded if anything fails. Which pg_restore options do you use, and what could still go wrong?
Show answer
Use pg_restore -d targetdb -n sales -t orders --single-transaction mydb.dump, so any error rolls back the whole restore. The table filter does not restore dependencies. If orders needs a sequence, a type, or a referenced table that is missing on the target, the restore can fail or lose constraints. Check with pg_restore --list and restore those items first.
Exercise
A restore with -j 4 and --single-transaction is rejected. Why, and which option do you keep if you must be able to roll back everything?
Show answer
Parallel workers use separate database connections, and one transaction cannot span several connections, so the two options cannot be combined. If an all-or-nothing restore matters more than speed, keep --single-transaction and drop -j. If speed matters, keep -j with --exit-on-error and restore into a fresh database that you can drop and recreate on failure.