Postgres unique constraint on index does not work

99封情书 提交于 2019-12-12 05:37:45

问题


On a quite simple table

CREATE TABLE collectionmaster
(
  id character varying(32) NOT NULL,
  version integer,
  publisherid character varying(12),
  title character varying(1024),
  subtitle character varying(1024),
  type character varying(255) NOT NULL,
  CONSTRAINT collectionmaster_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
CREATE INDEX idx_coll_title
  ON collectionmaster
  USING btree
  (title COLLATE pg_catalog."default");

I tried to add a unique check either via unique index

CREATE UNIQUE INDEX idx_uni_coll_title
  ON collectionmaster
  USING btree
  (publisherid COLLATE pg_catalog."default", title COLLATE pg_catalog."default", (COALESCE(subtitle, 'no_sub'::character varying)) COLLATE pg_catalog."default");

or via unique constraint

ALTER TABLE collectionmaster
  ADD CONSTRAINT uni_coll_title UNIQUE(publisherid, title, subtitle);

to intercept accidentally multiple creation by a java service (spring-jpa on hibernate) executed in several threads. But strangely neither of index and constraint works as expected. Eight records are added by eight threads which are not unique according to either constraint or index in separate transaction, but no unique violations are thrown, and all records are inserted into the table. And none of the values are null, as was the problem in other questions here. The constaint was not deferred, index as constraint where valid. Postgres version is 9.2.

I am quite clueless here.

EDIT: These are the results of a query in this table, extracted from pgAdmin (hard to format it nicer here):

"id";"version";"publisherid";"title";"subtitle";"type"
"53b3df625baf40bf885b48daa366fbc8";1;"5109138";"Titel";"Untertitel";"set"
"2673ef9a33f84289995d6f7288f07b46";1;"5109138";"Titel";"Untertitel";"set"
"ef7c385205034fdc89fe39e3eca48408";1;"5109138";"Titel";"Untertitel";"set"
"527922f2f3464f91826dbae2e2b67caf";1;"5109138";"Titel";"Untertitel";"set"
"794638a725324319852d10b828257df7";1;"5109138";"Titel";"Untertitel";"set"
"dbe2201058974d63a2107131f0080233";1;"5109138";"Titel";"Untertitel";"set"
"cbb77c7c1adb415db006853a6f6244ac";1;"5109138";"Titel";"Untertitel";"set"
"0b6606fe015040fbbc85444361ab414c";1;"5109138";"Titel";"Untertitel";"set"

Even on these I can execute

insert into collectionmaster(id, version, publisherid, title, subtitle, type) values('aaa',1,'5109138','Titel','Untertitel','set')

without getting a constraint violation. I can't believe it, too, but this is the problem...


回答1:


Make sure your spring-jpa config spring.jpa.hibernate.ddl-auto is not set to create-drop.

That way, hibernate will always drop & re-create your whole schema, which won't contain your custom unique constraints, nor your indexes.



来源:https://stackoverflow.com/questions/28168611/postgres-unique-constraint-on-index-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!