Subject: Trigger violates foreign key constraint

From: Laurenz Albe <[email-masked]>
Date: Mon, 02 Oct 2023 09:03:33 +0200

CREATE TABLE parent (id integer PRIMARY KEY);

CREATE TABLE child (id integer REFERENCES parent ON DELETE CASCADE);

CREATE FUNCTION silly() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NULL; END;';

CREATE TRIGGER silly BEFORE DELETE ON child FOR EACH ROW EXECUTE FUNCTION silly();

INSERT INTO parent VALUES (1);

INSERT INTO child VALUES (1);

DELETE FROM parent WHERE id = 1;

TABLE child;
 id 
════
  1
(1 row)

The trigger function cancels the cascaded delete on "child", and we are left with
a row in "child" that references no row in "parent".

Yours,
Laurenz Albe

---

From: Laurenz Albe <[email-masked]>
Date: Mon, 02 Oct 2023 12:02:17 +0200

Perhaps it would be enough to run "RI_FKey_noaction_del" after
"RI_FKey_cascade_del", although that would impact the performance.

Yours,
Laurenz Albe