简体   繁体   English

PostgreSQL,使用pg_restore更新现有行

[英]PostgreSQL, update existing rows with pg_restore

I need to sync two PostgreSQL databases (some tables from development db to production db) sometimes. 有时我需要同步两个PostgreSQL数据库(一些表从开发数据库到生产数据库)。

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. 当我编辑非PK列时,出现约束错误,并且行未更新。 For each dumped row I need to check if it exists in destination database (by PK) and if so delete it before INSERT/COPY. 对于每个转储的行,我需要检查它是否存在于目标数据库中(按PK),如果存在,则在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. 在第二个\\i ,您会收到很多重复的主键错误,但它会做您想要的事情:devel中的所有行都将被更新,devel中所有的行都将不会被更新或删除。

If you have any references to table1 then you'll have to drop them before and recreate them after importing. 如果您有对table1的任何引用,则必须先删除它们,然后在导入后重新创建它们。 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. 特别是检查是否on delete cascadeset nullset default对table1的set default引用-如果有的话,您将丢失其他表中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM