postgre数据库记录唯一键,在PostgreSQL中导入数据后,重复的键值违反了唯一约束...

在将Rails应用从MySQL迁移到PostgreSQL后,作者在尝试添加新内容时遇到了`duplicate key value violates unique constraint`错误。问题出现在尝试插入已存在的ID时。解决方案是重置序列值为现有数据的最大值,确保序列从当前最大ID开始递增。对于每个导入的表,需要找到序列字段并运行特定的SQL命令来设置序列。
摘要由CSDN通过智能技术生成

I recently migrated my rails app to PostgreSQL in order to take advantage of fulltext search.

Since the migration coincided with moving to a new webhost, the steps for migration were:

Deploy the application and db:create/db:schema:load on the new server, with appropriate database.yml file

mysqldump data only from existing MySQL production database

import data into PostgreSQL database

The application is running successfully but the issue comes when trying to add new content to the database. For example, when I run the rake task to update my twitter feed:

PG::Error: ERROR: duplicate key value violates unique constraint "twitter_feeds_pkey" DETAIL: Key (id)=(3) already exists.

This also happens for all other models, creating new articles, users etc. In development I can see that posting the insert statement n+1 times will successfully save the record without error.

My question is: How do I tell PostgreSQL to start adding indexes sequentially from the existing data?

I've read the REINDEX page but don't think that is really the operation I'm looking for.

解决方案

If the schema contains serial or sequence columns, you should reset these to the max value that occurs in the corresponding column. (normally you should not import the serials from a file, but give them the freedom to autoincrement.)

For all imported tables you should identify the sequence fields and run the following code on them. (substitute your schema name for "sch", your table name for "mytable" and your id column name for "id")

WITH mx AS ( SELECT MAX(id) AS id FROM sch.mytable)

SELECT setval('sch.mytable_id_seq', mx.id) AS curseq

FROM mx

;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值