English 中文(简体)
PostgreSQL, update existing rows with pg_restore
原标题:

I need to sync two PostgreSQL databases (some tables from development db to production db) sometimes.

So I came up with this script:

[...]
pg_dump -a -F tar -t table1 -t table2 -U user1 dbname1 | 
pg_restore -a -U user2 -d dbname2
[...]

The problem is that this works just for newly added rows. When I edit non-PK column I get constraint error and row isn t updated. For each dumped row I need to check if it exists in destination database (by PK) and if so delete it before INSERT/COPY.

Thanks for advices.

问题回答

Do this:

pg_dump -t table1 production_database > /tmp/old_production_database_table1.sql
pg_dump -t table1 devel_database > /tmp/devel_database_table1.sql
psql production_database
truncate table1
i /tmp/devel_database_table1.sql
i /tmp/old_production_database_table1.sql

You ll get a lot of duplicate primary key errors on second i, but it ll do what you want: all rows from devel will be updated, all rows not in devel will not be updated nor deleted.

If you have any references to table1 then you ll have to drop them before and recreate them after importing. Especially check for on delete cascade, set null or set default references to table1 - you d loose data in other tables if you have those.





相关问题
摘录数据

我如何将Excel板的数据输入我的Django应用? I m将PosgreSQL数据库作为数据库。

Postgres dump of only parts of tables for a dev snapshot

On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 ...

How to join attributes in sql select statement?

I want to join few attributes in select statement as one for example select id, (name + + surname + + age) as info from users this doesn t work, how to do it? I m using postgreSQL.

What text encoding to use?

I need to setup my PostgreSQL DB s text encoding to handle non-American English characters that you d find showing up in languages such as German, Spanish, and French. What character encoding should ...

SQL LIKE condition to check for integer?

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A": SELECT * ...

热门标签