How to duplicate schemas in PostgreSQL

前端 未结 5 1738
日久生厌
日久生厌 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条回答
  •  情深已故
    2021-02-01 04:31

    A bit late to the party but, some sql here could help you along your way:

    get schema oid:

    namespace_id = SELECT oid 
                      FROM pg_namespace 
                     WHERE nspname = '';
    

    get table's oid:

    table_id = SELECT relfilenode 
                    FROM pg_class 
                   WHERE relnamespace = '' AND relname = ''
    

    get foreign key constraints:

    SELECT con.conname, pg_catalog.pg_get_constraintdef(con.oid) AS condef 
      FROM pg_catalog.pg_constraint AS con 
      JOIN pg_class AS cl ON cl.relnamespace = con.connamespace AND cl.relfilenode = con.conrelid 
     WHERE con.conrelid = ''::pg_catalog.oid AND con.contype = 'f';
    

    A good resource for PostgreSQL system tables can be found here. Additionally, you can learn more about the internal queries pg_dump makes to gather dump information by viewing it's source code.

    Probably the easiest way to see how pg_dump gathers all your data would be to use strace on it, like so:

    $ strace -f -e sendto -s8192 -o pg_dump.trace pg_dump -s -n 
    $ grep -oP '(SET|SELECT)\s.+(?=\\0)' pg_dump.trace
    

    You'll still have to sort through the morass of statements but, it should help you piece together a cloning tool programmatically and avoid having to drop to a shell to invoke pg_dump.

提交回复
热议问题