How to duplicate schemas in PostgreSQL

前端 未结 5 1646
日久生厌
日久生厌 2021-02-01 04:09

I have a database with schema public and schema_A. I need to create a new schema schema_b with the same structure than schema_a

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 04:21

    I will share a solution for my problem which was the same with a small addition. I needed to clone a schema, create a new database user and assign ownership of all objects in the new schema to that user.

    For the following example let's assume that the reference schema is called ref_schema and the target schema new_schema. The reference schema and all the objects within are owned by a user called ref_user.

    1. dump the reference schema with pg_dump:

    pg_dump -n ref_schema -f dump.sql database_name
    

    2. create a new database user with the name new_user:

    CREATE USER new_user
    

    3. rename the schema ref_schema to new_schema:

    ALTER SCHEMA ref_schema RENAME TO new_schema
    

    4. change ownership of all objects in the renamed schema to the new user

    REASSIGN OWNED BY ref_user TO new_user
    

    5. restore the original reference schema from the dump

    psql -f dump.sql database_name
    

    I hope someone finds this helpful.

提交回复
热议问题