Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pg_dump and pg_restore (DROP IF EXISTS)

Tags:

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.

like image 823
lollercoaster Avatar asked Mar 09 '14 20:03

lollercoaster


People also ask

What is pg_dump and Pg_restore?

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.

What is the difference between pg_dump and Pg_dumpall?

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…

Does pg_dump affect performance?

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.

Does pg_dump overwrite?

Restoring the data from pg_dump doesn't overwrite the data but it appends the data to the original database. Bookmark this question.


2 Answers

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
like image 144
MatheusOl Avatar answered Oct 03 '22 22:10

MatheusOl


You could use --clean in pg_dump to first drop objects:

pg_dump --clean

Backup

pg_dump --clean -U user database > database.sql

Restore

psql -U user -d database -f database.sql
like image 41
Cassio Seffrin Avatar answered Oct 03 '22 22:10

Cassio Seffrin