Re: deleting a foreign key that has no references - Mailing list pgsql-general

From hubert depesz lubaczewski
Subject Re: deleting a foreign key that has no references
Date
Msg-id 9e4684ce0703191018v2ad74b8fp76950cf5f1c84c9f@mail.gmail.com
Whole thread Raw
In response to Re: deleting a foreign key that has no references  ("Glen W. Mabey" <Glen.Mabey@swri.org>)
List pgsql-general
On 3/19/07, Glen W. Mabey <Glen.Mabey@swri.org> wrote:
> > write a triggers which do that.
> I understand that a trigger should be written, and I have already
> implemented two such triggers, as described above.

no, i think i didn't make myself clear.
let's use this situation:
we have tables:
create table x (id serial primary key, some_text text);
create table y (id serial primary key, x_id int4 not null references x
(id), some_field text);
where table x is your table in which you want to make some deletes,
and table y is some table that has foreign key to it.
now, you add to table x a field:
alter table x add column refcount int4 not null default 0;

and then we add a trigger:
CREATE OR REPLACE FUNCTION some_trg() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
    IF TG_OP = 'INSERT' THEN
        UPDATE x SET refcount = refcount + 1 WHERE id = NEW.x_id;
    ELSIF TG_OP = 'UPDATE' THEN
        IF NEW.x_id <> OLD.x_id THEN
            UPDATE x SET refcount = refcount + 1 WHERE id = NEW.x_id;
            UPDATE x SET refcount = refcount - 1 WHERE id = OLD.x_id;
        END IF;
    ELSIF TG_OP = 'DELETE' THEN
        UPDATE x SET refcount = refcount - 1 WHERE id = OLD.x_id;
    END IF;
    RETURN NULL;
END;
$BODY$
LANGUAGE 'plpgsql';
CREATE TRIGGER some_trg AFTER INSERT OR UPDATE OR DELETE ON y FOR EACH
ROW EXECUTE PROCEDURE some_trg();

then - you have to populate the refcount field with current value, but
this is easily doable, and as far as i know you already are doing it
in your code.

so - the trigger keeps the refcount up to date. it is quite
lightweight, so shouldn't be a problem. and what's more important -
size of the table trigger is on doesn't matter.

simple, and working.

depesz

--
http://www.depesz.com/ - nowy, lepszy depesz

pgsql-general by date:

Previous
From: "Joshua D. Drake"
Date:
Subject: Re: DBD:Pg for Windows (PostgreSQL+Perl)
Next
From: "Joshua D. Drake"
Date:
Subject: Re: DBD:Pg for Windows (PostgreSQL+Perl)