Search code examples
sqlforeign-keyspostgresqldeferrable-constraint

deferrable initially deferred in postgresql


I have a cyclic foreign keys on 2 tables, so i use deferrable initially deferred as below:

uni=# create table vorlesungen (vnr integer primary key, gelesenvon integer);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "vorlesungen_pkey" for table "vorlesungen"
CREATE TABLE
uni=# create table professoren (pnr integer primary key, lieblingsvo integer);
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "professoren_pkey" for table "professoren"
CREATE TABLE
uni=# alter table professoren add constraint vfk foreign key (lieblingsvo) references vorlesungen (vnr) deferrable initially deferred;
ALTER TABLE
uni=# alter table vorlesungen add constraint pfk foreign key (gelesenvon) references professoren (pnr) deferrable initially deferred;
ALTER TABLE

so far so good. but now when i want to insert into the tables, i get foreign key violations, although i specified deferrable initially deferred:

uni=# insert into vorlesungen values (1, 1);
ERROR:  insert or update on table "vorlesungen" violates foreign key constraint "pfk"
DETAIL:  Key (gelesenvon)=(1) is not present in table "professoren".

uni=# insert into professoren values (1, 1);
ERROR:  insert or update on table "professoren" violates foreign key constraint "vfk"
DETAIL:  Key (lieblingsvo)=(1) is not present in table "vorlesungen".

whats the problem?


Solution

  • Are you explicitly opening a transaction before the INSERTs? If you do not use BEGIN, each insert is an independent transaction, therefore enforcing the foreign keys at the end of each command.