Postgres UPSERT 如何因重复的 SERIAL PRIMARY KEY 值而失败?

How can a Postgres UPSERT fail due to a duplicate SERIAL PRIMARY KEY value?

给定 table 定义:

CREATE TABLE devices
(
  id            SERIAL PRIMARY KEY,
  device_id     TEXT   NOT NULL,
  device_name   TEXT   NOT NULL
);

CREATE UNIQUE INDEX devices_by_device_id_unique ON devices (device_id);

还有这个更新:

INSERT INTO devices (device_id, device_name)
VALUES (:device_id, :device_name)
ON CONFLICT (device_id) DO UPDATE
SET device_name = :device_name

怎么会出现以下错误:

org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "devices_pkey"
  Detail: Key (id)=(253) already exists.

由于 id 列是自动生成的,应该不可能尝试插入相同的值两次?

如果您指定 ID 值,序列将不会自动更新:

insert into devices (id, device_id,device_name) values (1,1,'one');
INSERT 0 1
insert into devices (device_id,device_name) values (2,'two');
ERROR:  duplicate key value violates unique constraint "devices_pkey"
DETAIL:  Key (id)=(1) already exists.

您可以将序列重置为当前最大值

SELECT setval(
          pg_get_serial_sequence('public.devices','id'), 
          max(id)) 
FROM public.devices;