I want a completely shell-based solution for testing my database by allowing my to restore it to a consistent state by running a terminal command.
I dump my database like so:
pg_dump -F c -b -f -i -h domain.edu -p 5432 -n myschema -U me mydatabase -W -f mydump.sql
Then I want to restore it like so:
pg_restore -h domain.edu -p 5432 -U me -d mydatabase -W mydump.sql
but it doesn't work because I get tons of errors like these:
pg_restore: [archiver (db)] could not execute query: ERROR: constraint "settings_person_id_fkey" for relation "settings" already exists
Command was: ALTER TABLE ONLY settings
ADD CONSTRAINT settings_learner_id_fkey FOREIGN KEY (person_id) REFERENCES pe...
basically there are just a bunch of things that need to be dropped first before being re-added (DROP TABLE <whatever> IF EXISTS
, same with types, etc).
How can I do this with Postgres? I don't want to use the psql
console, only the linux terminal.
Description. pg_restore is a utility for restoring a PostgreSQL database from an archive created by pg_dump in one of the non-plain-text formats. It will issue the commands necessary to reconstruct the database to the state it was in at the time it was saved.
One caveat: pg_dump does not dump roles or other database objects including tablespaces, only a single database. To take backups on your entire PostgreSQL cluster, pg_dumpall is the better choice. pg_dumpall can handle the entire cluster, backing up information on roles, tablespaces, users, permissions, etc…
The only impact of pg_dump are the increased I/O load and the long running transaction it creates. The long transaction will keep autovacuum from reclaimimg dead tuples for the duration of the dump. Normally that is no big problem unless you have very high write activity in the database.
Restoring the data from pg_dump doesn't overwrite the data but it appends the data to the original database. Bookmark this question.
If you want to restore the database to a consistent state, I recommend you to drop and recreate it before restoring the dump:
dropdb -h domain.edu -U me mydatabase
createdb -h domain.edu -U me -T template0 mydatabase # adjust encoding/locale if necessary
pg_restore -h domain.edu -p 5432 -U me -d mydatabase -W mydump.sql
You could use --clean
in pg_dump to first drop objects:
pg_dump --clean
pg_dump --clean -U user database > database.sql
psql -U user -d database -f database.sql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With