Sub topic 6
Restoring plain SQL dumps with psql
A plain-format dump from pg_dump is a text file of SQL commands. You restore it by running that script with psql, so pg_restore is not involved. This chapter covers how that restore behaves, what goes wrong with it, and how to make it safe and verifiable. It assumes you can use psql, know that a transaction applies all its statements or none, and have read the earlier chapter on pg_dump and dump formats.
What is inside a plain dump
Open a small plain dump with head or less and you will see ordinary SQL in a fixed order:
SETcommands that fix the encoding,standard_conforming_strings, and an emptysearch_path.CREATE EXTENSION,CREATE TYPE,CREATE TABLE, and similar definitions.- Table data as
COPY ... FROM stdin;followed by tab-separated rows and a line containing only\.. - Indexes, constraints, and triggers, created after the data is loaded.
SELECT pg_catalog.setval(...)calls that reset sequences.
The ordering matters. Loading rows before creating indexes and foreign keys is faster. It also means triggers do not fire during the load, and foreign keys are not checked row by row. psql understands the COPY data blocks because the rows come through the same input stream as the commands.
The basic restore
A plain dump does not create the target database unless you asked for that when dumping. The usual sequence is to create an empty database and then run the script.
pg_dump -U postgres -Fp -f mydb.sql mydb
createdb -U postgres mydb_restored
psql -U postgres -d mydb_restored -f mydb.sql-Fp is the default format, so you can leave it out. The restore command above works, but it has a serious flaw that the next section covers.
Why the default behavior is dangerous
By default, psql keeps going after an error. If one statement fails, it prints the error and runs the next statement. A restore can therefore finish with exit status 0 even though tables are missing, data was not loaded, or constraints were never created. The error messages are in your terminal scrollback, and in an automated job nobody reads them.
A typical failure chain looks like this:
CREATE TABLE orders ... OWNER TO app_ownerfails because the roleapp_ownerdoes not exist on the target cluster.- The
COPY ordersblock then fails because the table was never created. - Later
ALTER TABLE ... ADD CONSTRAINTstatements fail because the table is missing. - The script ends, and the database is partially restored.
Two options fix this, and you should use both.
psql -U postgres -d mydb_restored \
-v ON_ERROR_STOP=1 \
--single-transaction \
-f mydb.sql-v ON_ERROR_STOP=1makespsqlstop at the first error. It then exits with status 3, which scripts can check.--single-transaction(short form-1) wraps the whole script inBEGINandCOMMIT. If the script stops on an error, the transaction rolls back and the target database stays empty.
Together they give you an all-or-nothing restore. You fix the cause, then rerun the same command against the same empty database.
Capturing errors and progress
Even with the safety options, keep a log. Send standard error to a file, and use -q to hide the per-command status lines such as CREATE TABLE so that real errors stand out.
psql -U postgres -d mydb_restored -q \
-v ON_ERROR_STOP=1 --single-transaction \
-f mydb.sql 2> restore.err
echo "psql exit status: $?"If you do need a best-effort restore, for example to rescue data from a damaged dump, omit ON_ERROR_STOP and --single-transaction. Then read restore.err completely. Search it with grep -c ERROR restore.err and look at each error before you trust the result.
Common errors and what they mean
| Error message (abbreviated) | Cause | Fix |
|---|---|---|
| `role "app_owner" does not exist` | The dump has `OWNER TO` or `GRANT` for a role missing on the target | Restore globals first with `pg_dumpall --globals-only`, or dump with `--no-owner` and `--no-privileges` |
| `database "mydb_restored" does not exist` | You skipped `createdb` | Create the database, or dump with `-C` |
| `relation "x" already exists` | You restored into a database that already has objects | Restore into an empty database, or dump with `--clean --if-exists` |
| `could not open extension control file` | An extension used by the dump is not installed on the target server | Install the matching OS package, then rerun |
| `invalid byte sequence for encoding` | The client encoding does not match the dump | Set `PGCLIENTENCODING` to the encoding in the dump's `SET client_encoding` line |
| `permission denied to create extension` | The restoring role is not allowed to create that extension | Run as a superuser, or use a trusted extension |
| `CREATE DATABASE cannot run inside a transaction block` | `--single-transaction` used with a dump made with `-C` | Drop `--single-transaction` (see below) |
The ownership error is the most frequent one. It is also a good reason to restore roles before databases, as the previous chapter on pg_dumpall describes.
Dumps that create the database
If you dump with -C (--create), the script contains CREATE DATABASE and a \connect command. You then connect to any existing database, usually postgres, and let the script switch databases itself.
pg_dump -U postgres -C -f mydb_create.sql mydb
psql -U postgres -d postgres -v ON_ERROR_STOP=1 -f mydb_create.sqlCREATE DATABASE cannot run inside a transaction, so --single-transaction does not work here. Without it, a failure after the \connect leaves a partly filled database behind. If that happens, drop the database and rerun. The restored database also keeps the original name, so this approach is a poor fit when you want a copy beside the original. For that case, use createdb and a plain restore.
A related option is --clean --if-exists (-c --if-exists). It adds DROP ... IF EXISTS before each object so you can restore over an existing database. Be careful with it. It deletes objects in the target database, and it does not remove objects that are in the target but not in the dump.
Restoring compressed or piped dumps
A plain dump is large because it is text, so many people compress it. psql cannot read compressed files, but it reads standard input, so you decompress in a pipe.
pg_dump -U postgres mydb | gzip > mydb.sql.gz
createdb -U postgres mydb_restored
gunzip -c mydb.sql.gz | psql -U postgres -d mydb_restored \
-v ON_ERROR_STOP=1 --single-transaction -f -Here -f - tells psql to read the script from standard input. A pipe has a hidden risk. In a shell, the exit status of a pipeline is that of the last command, so a truncated .gz file might not be noticed. Test the archive first with gzip -t mydb.sql.gz. In bash, set -o pipefail makes the pipeline fail if any stage fails.
You can also restore straight from a live server with no file in between:
pg_dump -h old-host -U postgres mydb | \
psql -h new-host -U postgres -d mydb_restored -v ON_ERROR_STOP=1 -1This is convenient for a one-time migration. It gives you no backup file, so it is not a backup.
Restore time and what comes after
A plain restore is single-threaded, because psql runs one statement at a time. For large databases this is the main reason to choose the custom or directory format, where pg_restore -j runs jobs in parallel. A plain script cannot be restored in parallel, and you cannot restore one table from it without editing the file.
Two follow-up steps are easy to forget:
- Planner statistics are not stored in a dump. Run
ANALYZEon the restored database, or queries may use poor plans until autovacuum catches up. - Compare the restored database against the original. At minimum, compare row counts for your biggest tables.
ANALYZE;
SELECT relname, n_live_tup
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC
LIMIT 10;n_live_tup is an estimate and is unreliable right after a restore. For an exact check, run SELECT count(*) on the tables that matter.
A complete, safe restore script
This script puts the pieces together and fails loudly.
#!/usr/bin/env bash
set -euo pipefail
DUMP="$1"
TARGET="$2"
gzip -t "$DUMP"
createdb -U postgres "$TARGET"
if ! gunzip -c "$DUMP" | psql -X -q -U postgres -d "$TARGET" \
-v ON_ERROR_STOP=1 --single-transaction -f - 2> "$TARGET.err"; then
echo "Restore failed, see $TARGET.err" >&2
dropdb -U postgres "$TARGET"
exit 1
fi
psql -X -U postgres -d "$TARGET" -c "ANALYZE;"
echo "Restore of $TARGET complete"Because the restore is one transaction, dropping the target database after a failure is safe. Nothing in it is worth keeping.
Exercise
A colleague runs psql -d mydb_restored -f mydb.sql. The terminal shows several errors, but the command returns exit status 0 and a nightly job reports success. What two options would you add, and what does each one change?
Show answer
Add -v ON_ERROR_STOP=1 and --single-transaction. The first makes psql stop at the first error and exit with status 3, so the job can detect the failure. The second wraps the script in one transaction, so a failure rolls everything back and leaves the target database empty instead of partly restored.
Exercise
You made a dump with pg_dump -C and try to restore it with --single-transaction. It fails with "CREATE DATABASE cannot run inside a transaction block". How do you restore it, and what do you do if the restore fails halfway?
Show answer
Run it without --single-transaction, connected to an existing database such as postgres: psql -d postgres -v ON_ERROR_STOP=1 -f mydb_create.sql. If it fails after the \connect, the new database holds partial data. Drop that database, fix the cause of the error, and run the script again.