Re: Trigger and Recursive Relation ?

From: "Nikolay Samokhvalov" <samokhvalov(at)gmail(dot)com>
To: "Postgres Novice" <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Trigger and Recursive Relation ?
Date: 2006-08-01 20:26:25
Message-ID: e431ff4c0608011326x2aca3bc0k53eca0acab32435b@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs pgsql-novice

On 8/1/06, Greg Steele <gsteele(at)apt-cafm(dot)com> wrote:
> CREATE TABLE recursive(
> id int PRIMARY KEY,
> parent int,
> FOREIGN KEY (parent) REFERENCES recursive ON DELETE CASCADE
> );
>
>
> CREATE OR REPLACE FUNCTION delete_on_recursive_trigger_fx() RETURNS trigger
> AS
> $$
> BEGIN
>
> UPDATE recursive
> SET parent = OLD.parent
> WHERE parent = OLD.id;
>
> RETURN OLD;
> END;
> $$
> Language 'plpgsql';
>
>
> CREATE TRIGGER delete_on_recursive_trigger
> BEFORE DELETE ON recursive
> FOR EACH ROW
> EXECUTE PROCEDURE delete_on_recursive_trigger_fx();
>
> INSERT INTO recursive(id, parent) values(1, null);
> INSERT INTO recursive(id, parent) values(2, 1);
> INSERT INTO recursive(id, parent) values(3, 2);
> INSERT INTO recursive(id, parent) values(4, 3);
>
> --only 1/2 of the records are deleted!
> DELETE FROM recursive;

good puzzle :-)
you have two things:
1. 'ON DELETE CASCADE' in FK defiinition
2. BEFORE trigger that changes FK values of some rows.

I guess that Postgres deletes one row, but before it changes "parent"
values in other rows, then it invokes 'CASCADE' logic and deletes
another rows, but doing so it tries to find, which rows have
corresponding "parent" values and... Well, you've created something
tricky :-)
You'd better get rid of CASCADE option.

--
Best regards,
Nikolay

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Nikolay Samokhvalov 2006-08-01 20:52:32 Fwd: [NOVICE] Trigger and Recursive Relation ?
Previous Message Greg Steele 2006-08-01 19:31:15 Trigger and Recursive Relation ?

Browse pgsql-novice by date

  From Date Subject
Next Message Nikolay Samokhvalov 2006-08-01 20:52:32 Fwd: [NOVICE] Trigger and Recursive Relation ?
Previous Message Nikolay Samokhvalov 2006-08-01 19:58:22 Re: GRANT role TO PUBLIC- not working?