Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use pg_dump result as input for pg_restore

Tags:

postgresql

I need to clone a database (only schema) on the same server. I would like to use the input from pg_dump and pipe it to pg_restore. I know this can be done with psql but psql doesn't have a "-c clean" option.

Is this possible but with pg_restore ?

 pg_dump --schema public dbName | psql dbNameTest
like image 751
johnlemon Avatar asked Jun 19 '12 14:06

johnlemon


People also ask

Is pg_dump backwards compatible?

restores to earlier versions not working.

What is pg_dump and Pg_restore?

The pg_dump and pg_restore command line tools are used to export and import PostgreSQL databases. They create PostgreSQL backups and migrate PostgreSQL databases between servers.

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.


2 Answers

The following comes close:

pg_dump --schema-only --format c dbName | \
  pg_restore --schema-only --clean --dbname=dbNameTest

Except it doesn't work if the dbNameTest doesn't exist yet. The following does the job (although it complains if the dbNameTest already exists. I can live with that)

createdb dbNameTest
pg_dump --schema-only --format c dbName | \
  pg_restore --schema-only --clean --dbname=dbNameTest

A oneliner with short options would be:

createdb dbNameTest ; pg_dump -s -F c dbName | pg_restore -s -c -d dbNameTest

A sh script pg_copy_schema would go something like:

#!/bin/sh
if [ -z "$2" ] ; then echo "Usage: `basename $0` original-db new-db" ; exit 1 ; fi
echo "Copying schema of $1 to $2"
createdb "$2" 2> /dev/null
pg_dump --schema-only --format c "$1" | pg_restore --schema-only --clean --dbname="$2"
like image 122
artm Avatar answered Oct 11 '22 12:10

artm


http://www.postgresql.org/docs/9.1/static/app-pgdump.html

You need to use -F combined with -c , -d, or -t option with pg_dump in order to use it with pg_restore. You can't use pg_restore with a plain-text SQL dump.

like image 22
Dondi Michael Stroma Avatar answered Oct 11 '22 12:10

Dondi Michael Stroma