I am trying to copy an entire table from one database to another in Postgres. Any suggestions?
Check this python script
python db_copy_table.py "host=192.168.1.1 port=5432 user=admin password=admin dbname=mydb" "host=localhost port=5432 user=admin password=admin dbname=mydb" alarmrules -w "WHERE id=19" -v
Source number of rows = 2
INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister1',true,false);
INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister2',true,false);
First install dblink
Then, you would do something like:
INSERT INTO t2 select * from
dblink('host=1.2.3.4
user=*****
password=******
dbname=D1', 'select * t1') tt(
id int,
col_1 character varying,
col_2 character varying,
col_3 int,
col_4 varchar
);
Here is what worked for me. First dump to a file:
pg_dump -h localhost -U myuser -C -t my_table -d first_db>/tmp/table_dump
then load the dumped file:
psql -U myuser -d second_db</tmp/table_dump
Extract the table and pipe it directly to the target database:
pg_dump -t table_to_copy source_db | psql target_db
Note: If the other database already has the table set up, you should use the -a
flag to import data only, else you may see weird errors like "Out of memory":
pg_dump -a -t my_table my_db | psql target_db
pg_dump
does not work always.
Given that you have the same table ddl in the both dbs you could hack it from stdout and stdin as follows:
# grab the list of cols straight from bash
psql -d "$src_db" -t -c \
"SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_name='"$table_to_copy"'"
# ^^^ filter autogenerated cols if needed
psql -d "$src_db" -c \
"copy ( SELECT col_1 , col2 FROM table_to_copy) TO STDOUT" |\
psql -d "$tgt_db" -c "\copy table_to_copy (col_1 , col2) FROM STDIN"
To move a table from database A to database B at your local setup, use the following command:
pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2