dump db时跳过违反唯一约束

时间:2014-12-27 13:15:21

标签: postgresql pg-dump

我尝试将数据库转储到另一个数据库。表中有一些重复的唯一值。当pg_dump尝试将此项添加到db时,它会抛出错误并退出。错误就像;

ERROR:  duplicate key value violates unique constraint "test_table_pkey"
DETAIL:  Key (pktable)=(col11) already exists.
CONTEXT:  COPY test_table, line 1: "col11  col12"

我的表是;

   Column    |         Type          | Modifiers 
-------------+-----------------------+-----------
 pktable     | text                  | not null
 source      | text                  | not null
Indexes:
    "test_table_pkey" PRIMARY KEY, btree (pktable)

我的命令是;

pg_dump -U postgres -v --data-only <db_name> | psql -U postgres -h <remote_host> -d <db_name>

我想pg_dump跳过重复的唯一值并继续转储操作。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

我认为这条规则可以帮到你:

CREATE RULE "my_table_on_duplicate_ignore" AS ON INSERT TO "my_table"
  WHERE EXISTS(SELECT 1 FROM my_table 
                WHERE (pk_col_1, pk_col_2)=(NEW.pk_col_1, NEW.pk_col_2))
  DO INSTEAD NOTHING;

基本上,如果新插入的行已经在表中,则会触发INSTEAD NOTHING

(基于此:https://stackoverflow.com/a/6176044/1665673