Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 have two databases

db1 and db2

Both have tables with same name in their public schema.

Now, I want to create a new schema in db1 with name : new_schema

And move data from db2.public to db1.new_schema

What is the easiest way to do this ?

like image 970
Mandeep Singh Avatar asked Jun 06 '14 11:06

Mandeep Singh


People also ask

What is the best way to transfer the data in a PostgreSQL database?

If you really have two distinct PostgreSQL databases, the common way of transferring data from one to another would be to export your tables (with pg_dump -t ) to a file, and import them into the other database (with psql ).

How can I import the schema of a database in PostgreSQL?

In the left pane of the phpPgAdmin window, expand Servers, expand PostgreSQL, and then click the name of the database that you want to import the data into. On the top menu bar, click SQL. The SQL link is located between the Schemas and Find links. Click Choose File.


2 Answers

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.

like image 109
Dmitri Avatar answered Sep 22 '22 08:09

Dmitri


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.

like image 33
klin Avatar answered Sep 23 '22 08:09

klin