我需要能够以某种方式从我的开发数据库中获取一组表到我的生产数据库中。我刚刚从开发数据库创建了一个转储文件,并在生产数据库上使用了 pg_restore。现在的问题是我需要在生产数据库中保留一个表(称为用户),同时替换其他表
我想我已经从这个命令中正确地转储了
pg_dump -Fc --no-acl --no-owner -h localhost -U <USER> --exclude-table=users* --data-only <DB NAME> > test.dump
但我无法让恢复部分工作。我尝试了以下命令
pg_restore -Fc --no-acl --no-owner -h <PROD HOST> -U <USER> -d <DB NAME> -p <PORT> <FILE LOCATION>
但是我得到以下错误
pg_restore: [archiver (db)] Error while PROCESSING TOC:
pg_restore: [archiver (db)] Error from TOC entry 2009; 0 121384 TABLE DATA idx_descs Jason
pg_restore: [archiver (db)] COPY failed for table "idx_descs": ERROR: duplicate key value violates unique constraint "idx_descs_pkey"
DETAIL: Key (id)=(6) already exists.
CONTEXT: COPY idx_descs, line 1
似乎对于我试图覆盖的表,它只是试图附加数据并遇到麻烦,因为现在有重复的主键。任何想法如何做到这一点?谢谢
最佳答案
所以您需要重新分配主键?
你可以尝试恢复到一个临时表(例如,在失败的情况下:idx_desc_temp),然后做类似的事情:
with t as ( select * from idx_descs_temp )
insert into idx_descs
select id + 100000 [or whatever], [other fields] from t;
之后您需要重置序列(如果适用——填写序列名称....):
select setval( 'idx_descs_id_seq'::regclass, 100000 + [suitable increment]);
如果您有大量表,您可以尝试使用系统目录实现自动化。
请注意,您还必须重新编号外键引用。首先在生产数据库中移动数据可能会减少痛苦。如果您使用的是 ORM,您还可以通过应用程序 API 实现自动化。
关于postgresql如何备份和覆盖特定表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23000857/