I have a dump, where the data and the structure is in the public schema. I want to restore it into a schema with a custom name - how can I do that?
EDIT V 2:
Near the beginning of a dump file (created with pg_dump databasename
) is a line:
SET search_path = public, pg_catalog;
Just change it to:
SET search_path = your_schema_name, pg_catalog;
Also you'll need to search for
ALTER TABLE public.
and replace with:
ALTER TABLE your_schema_name.
@Tometzky's solution isn't quite right, at least with 9.2's pg_dump
. It'll create the table in the new schema, but pg_dump
schema-qualifies the ALTER TABLE ... OWNER TO
statements, so those will fail:
postgres=# CREATE DATABASE demo;
\cCREATE DATABASE
postgres=# \c demo
You are now connected to database "demo" as user "postgres".
demo=# CREATE TABLE public.test ( dummy text );
CREATE TABLE
demo=# \d
List of relations
Schema | Name | Type | Owner
--------+------+-------+----------
public | test | table | postgres
(1 row)
demo=# \q
$
$ pg_dump -U postgres -f demo.sql demo
$ sed -i 's/^SET search_path = public, pg_catalog;$/SET search_path = testschema, pg_catalog;/' demo.sql
$ grep testschema demo.sql
SET search_path = testschema, pg_catalog;
$ dropdb -U postgres demo
$ createdb -U postgres demo
$ psql -U postgres -c 'CREATE SCHEMA testschema;' demo
CREATE SCHEMA
$ psql -U postgres -f demo.sql -v ON_ERROR_STOP=1 -v QUIET=1 demo
psql:demo.sql:40: ERROR: relation "public.test" does not exist
$ psql demo
demo=> \d testschema.test
Table "testschema.test"
Column | Type | Modifiers
--------+------+-----------
dummy | text |
You will also need to edit the dump to remove the schema-qualification on public.test
or change it to the new schema name. sed
is a useful tool for this.
I could've sworn the correct way to do this was with pg_dump -Fc -n public -f dump.dbbackup
then pg_restore
into a new schema, but I can't seem to find out exactly how right now.
Update: Nope, it looks like sed
is your best bet. See I want to restore the database with a different schema