【问题标题】:Puzzling "duplicate key" error (PostgreSQL)令人费解的“重复键”错误(PostgreSQL)
【发布时间】:2011-02-28 02:41:59
【问题描述】:

首先,让我说我了解关系理论,并且我在 MySQL 中的能力与任何人一样,但我完全是 PostgreSQL 菜鸟。

当我尝试将新记录插入到我的 service 表中时 - 仅在生产中 - 我得到了这个:

ActiveRecord::RecordNotUnique (PGError: ERROR:  duplicate key value violates unique constraint "service_pkey"
: INSERT INTO "service" ("created_at", "name", "salon_id", "updated_at") VALUES ('2011-02-28 02:34:20.054269', 'Manicure', 1, '2011-02-28 02:34:20.054269') RETURNING "id"):
  app/controllers/services_controller.rb:46
  app/controllers/services_controller.rb:45:in `create'

我不明白为什么。它不应该为我自动增加PK吗?

这是表定义:

snip=> \d service
                                     Table "public.service"
   Column   |            Type             |                      Modifiers                       
------------+-----------------------------+------------------------------------------------------
 id         | integer                     | not null default nextval('service_id_seq'::regclass)
 name       | character varying(255)      | 
 salon_id   | integer                     | 
 created_at | timestamp without time zone | 
 updated_at | timestamp without time zone | 
Indexes:
    "service_pkey" PRIMARY KEY, btree (id)

这是开发中同一张表的定义,它可以正常工作:

snip_development=> \d service
                                     Table "public.service"
   Column   |            Type             |                      Modifiers                       
------------+-----------------------------+------------------------------------------------------
 id         | integer                     | not null default nextval('service_id_seq'::regclass)
 name       | character varying(255)      | 
 salon_id   | integer                     | 
 created_at | timestamp without time zone | 
 updated_at | timestamp without time zone | 
Indexes:
    "service_pkey" PRIMARY KEY, btree (id)

同样的事情!那么它可能是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 postgresql


    【解决方案1】:

    您可能在表格中加载了数据,但忽略了将service_id_seq 的当前值设置为必要的值。您可以只SELECT * FROM service_id_seq 来检查当前值,并使用setval 函数来重置它。

    例如,SELECT setval('service_id_seq'::regclass, MAX(id)) FROM service; 应将序列重置为表中的当前最大值。

    【讨论】:

    • 我也有同样的问题,我用的是OpenJPA,请问如何解决?
    猜你喜欢
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多