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

前端 未结 2 688
一向
一向 2021-02-07 20:31

I am new to Postgres and just discovered that I cannot access data of different databases in one SQL query. And also learned the concept of schema in Postgres.

Now, I ha

2条回答
  •  爱一瞬间的悲伤
    2021-02-07 21:11

    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.

提交回复
热议问题