Re: foreign keys with on delete cascade and triggers

From: Dirk Jagdmann <jagdmann(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: foreign keys with on delete cascade and triggers
Date: 2006-01-12 11:49:27
Message-ID: 5d0f60990601120349x11df4f30yfcbfbb7e2adae227@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hello Tom,

> If you want the whole transaction rolled back, raise an error instead
> of returning NULL.

You're right, that's working. But now I have a slightly different problem.

I assume that the trigger which watches the cascaded deletions first
deletes the row in the monitored table and then deletes any dependant
foreign keys. Thus the "foreign key tree" is deleted in a top-down
manner. This hinders any triggers on delete queries in cascaded tables
to query the referenced table any longer, since the referenced row is
already deleted. The following code shows what I mean:

create table a ( i serial primary key, name text );
create table b ( f int references a on delete cascade );
create or replace function f() returns trigger as $$
DECLARE
n text;
BEGIN
SELECT name INTO n from a where i=OLD.f;
IF FOUND THEN
RAISE NOTICE '% deleted me', n;
END IF;
RETURN OLD;
END;
$$ language plpgsql;
create trigger b_del before delete on b for each row execute procedure f();
insert into a(name) values('Dirk');
insert into b select currval('a_i_seq');
insert into a(name) values('Tom');
insert into b select currval('a_i_seq');
delete from b where f=1; -- will raise the notice
delete from a where i=2; -- wont raise anything

If the "foreign key tree" would be deleted in a bottom-up (or
depth-first) manner the second delete would be able to retrieve the
row in table a.

Now I'd like to know if the current order of deletions in PostgreSQL
is intended in the top-down way or if that could be changed?

--
---> Dirk Jagdmann
----> http://cubic.org/~doj
-----> http://llg.cubic.org

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2006-01-12 15:46:37 Re: foreign keys with on delete cascade and triggers
Previous Message Rainer Leo 2006-01-12 08:43:59 error code invalid_input_syntax