From: | "hubert depesz lubaczewski" <depesz(at)gmail(dot)com> |
---|---|
To: | "Glen W(dot) Mabey" <Glen(dot)Mabey(at)swri(dot)org> |
Cc: | postgresql-general <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: deleting a foreign key that has no references |
Date: | 2007-03-19 17:18:06 |
Message-ID: | 9e4684ce0703191018v2ad74b8fp76950cf5f1c84c9f@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 3/19/07, Glen W. Mabey <Glen(dot)Mabey(at)swri(dot)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
From | Date | Subject | |
---|---|---|---|
Next Message | Joshua D. Drake | 2007-03-19 17:20:32 | Re: DBD:Pg for Windows (PostgreSQL+Perl) |
Previous Message | Joshua D. Drake | 2007-03-19 17:14:16 | Re: DBD:Pg for Windows (PostgreSQL+Perl) |