Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 908
hooch Avatar asked Apr 18 '11 01:04

hooch


People also ask

What is initially deferred deferrable in Oracle?

When you add a DEFERRABLE constraint, you can mark it as INITIALLY IMMEDIATE or INITIALLY DEFERRED. INITIALLY IMMEDIATE means that the constraint is checked whenever you add, update, or delete rows from a table. INITIALLY DEFERRED means that the constraint is only checked when a transaction is committed.

Why do you need deferrable option in case of SQL transactions?

To recap, declaring a constraint deferrable allows transactions to defer validation until commit time.

What is deferrable SQL?

In SQL Server Enterprise, a corrupted transaction can become deferred if data required by rollback (undo) is offline during database startup. A deferred transaction is a transaction that is uncommitted when the roll forward phase finishes and that has encountered an error that prevents it from being rolled back.

What is exclusion constraint in PostgreSQL?

EXCLUSION Constraint − The EXCLUDE constraint ensures that if any two rows are compared on the specified column(s) or expression(s) using the specified operator(s), not all of these comparisons will return TRUE.


1 Answers

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.

like image 80
Diogo Biazus Avatar answered Sep 27 '22 22:09

Diogo Biazus