令人费解的"重复键"错误(PostgreSQL)

Jas*_*ett 4 postgresql ruby-on-rails ruby-on-rails-3

首先,让我说我理解关系理论,我和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'
Run Code Online (Sandbox Code Playgroud)

我不明白为什么.它不应该为我自动增加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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

一样!那可能是什么呢?

Ano*_*mie 15

您可能使用数据加载了表,但忽略了将当前值设置service_id_seq为必要值.您可以只SELECT * FROM service_id_seq检查当前值,并使用该setval功能重置它.

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