Postgres: Best way to move data from public schema of one DB to new schema of another DB

徘徊边缘 提交于 2019-12-04 03:05:16

The simplest way to do that is to rename schemas. However you must be sure you are a sole user of db1 database.

First, hide your schema public in db1:

alter schema public rename to original_public;
create schema public;

Next, do the backup and restore:

$ pg_dump --format custom --file "my_backup" --schema "public" "db2"
$ pg_restore --dbname "db1" "my_backup"

Finally, recreate appropriate schema names:

alter schema public rename to my_schema;
alter schema original_public rename to public;

Another option is to use dblink. It enables accessing data of different databases.

Export "public" from db2 (skipping grants and ownership):

pg_dump -xO -n public db2 > db2.sql

The exported file will set up the search path (somewhere near the top):

SET search_path = public, pg_catalog;

change it to:

CREATE SCHEMA IF NOT EXISTS new_schema;
SET search_path = new_schema, pg_catalog;

Import to db1 as usual:

psql db1 < db2.sql

You'll probably want to move everything from public to a new schema in db1, first.

If the schema is already set up in db1, you can do the transfer in one go:

pg_dump -xO -n public db2 | sed 's/search_path = public/search_path = new_schema/' | psql db1

Wouldn't recommend that without a lot of testing, of course.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!