SET CONSTRAINTS ALL DEFERRED not working as expected in PostgreSQL 9.3

*爱你&永不变心* 提交于 2019-11-30 01:44:45

问题


If I define tables a and b as follows:

CREATE TABLE a(i integer);
ALTER TABLE a ADD CONSTRAINT pkey_a PRIMARY KEY (i);
CREATE TABLE b(j integer);
ALTER TABLE b add CONSTRAINT fkey_ij FOREIGN KEY (j)
      REFERENCES a (i) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE;
INSERT INTO a(i) VALUES(1);

And then do the following:

START TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO b(j) VALUES(2);
INSERT INTO a(i) VALUES(2);
COMMIT;

It produces the error below. Why is SET CONSTRAINTS not having the desired effect?

ERROR: insert or update on table "b" violates foreign key constraint "fkey_ij"
SQL state: 23503 Detail: Key (j)=(2) is not present in table "a".


回答1:


For starters, only DEFERRABLE constraints can be deferred.

But that won't help your case because, FK constraints cannot be bent this way at all. Per documentation:

Referential actions other than the NO ACTION check cannot be deferred, even if the constraint is declared deferrable.

Reverse the sequence of your INSERT statements.

Related:

  • Constraint defined DEFERRABLE INITIALLY IMMEDIATE is still DEFERRED?


来源:https://stackoverflow.com/questions/28680817/set-constraints-all-deferred-not-working-as-expected-in-postgresql-9-3

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