Automated way to convert a postgresql database to a postgresql schema in a different database?

StackOverflow https://stackoverflow.com/questions/19660525

  •  01-07-2022
  •  | 
  •  

Pregunta

Is there an automated way to take a postgresql database and convert it into a postgresql schema that can be loaded into a new database?

I played around with this and found two ways to do what I want to do, but both are troublesome, in my honest opinion:

  1. Perform a pg_dump on the database using the plain option, as part of a script, then running some sed tomfoolery to make corresponding changes. However, this is begging for pain and bugs.

  2. Transfer all the tables, sequences, data, etc from the database's schema into the new schema name via psql, and then dump/restore only that schema/data.

I'll probably go with option two, but does anyone have a easier way to do this? if we were generating the stuff from scratch, this would be trivial of course, but it's likely we will have to transition existing databases on multiple systems in this manner.

EDIT: Clarification for people reading this later on. I am attempting to essentially take the public schema of Database 'A' and dump/restore it into a new named schema on Database 'B'. Database 'B' may, or may not, be using its public schema for other things, so the transfers needs to take place WITHOUT altering/changing any potential data in the public schema on Database 'B'.

¿Fue útil?

Solución

Since you can't have nested schemas I am assuming you want to take the public schema in db A and put it into a named schema in db B.

Here's the simple way to do this (it may require some effort regarding search_path so that everything is found correctly, particularly regarding functions, but see notes below.

  1. Dump your db from DB A. Restore it into db B

  2. Run the following command on db B:

    ALTER SCHEMA public RENAME TO foobar;
    
  3. You can then alter some users to search for relations and functions in foobar first:

    ALTER USER myuser SET search_path=foobar,public;
    
  4. If you have functions you can:

    ALTER FUNCTION foo(bar int) SET search_path=foobar;
    

I think that covers the basics.

Now if you can't be sure that the public schema is in use, you may want to consult pg_class and pg_namespace to try to determine which schema is involved. You could do this by checking the namespaces of specific tables and try to make sure only one schema is involved. If the same table name occurs in multiple schemas and is the one you are using to detect, then you will need to manually interfere.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top