Re: trigger howto question

From: Richard Huxton <dev(at)archonet(dot)com>
To: Furesz Peter <spam(at)srv(dot)hu>
Cc: postgres levlista <pgsql-general(at)postgresql(dot)org>
Subject: Re: trigger howto question
Date: 2007-01-16 19:19:44
Message-ID: 45AD2550.1010305@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Furesz Peter wrote:
> Hello,
>
> I have a table named foobar and I don't want to allow from DELETE or
> UPDATE
> its rows.
>
> I have a table as described below:
> foobar(foobar_id, value, is_deleted);
>
> I don't want to allow directly delete or modify the table's rows. I plan to
> make an on before update or delete trigger and
> on delete action I update the actual row is_deleted flag, on UPDATE
> action I
> also update the is_deleted flag and I insert a new row with the new values.
> Everything is ok, but when I capture the delete action I am execute an
> update what triggering the trigger again and I got an unwanted row.

The trick is to remember that only the trigger can be setting the
is_deleted flag, not other queries (or at least that's what I think you
want).

> CREATE TRIGGER "tr_foobar" BEFORE UPDATE OR DELETE ON "public"."foobar"
> FOR
> EACH ROW
> EXECUTE PROCEDURE "public"."tr_foobar_func"();
>
> BEGIN
> IF TG_OP='DELETE' THEN
> UPDATE foobar SET is_deleted=TRUE WHERE foobar_id=OLD.foobar;
> RETURN NULL;
> ELSEIF TG_OP='UPDATE' THEN
^^^^^^^^^^^^^^^^^^^^^^^^^^
ELSEIF TG_OP='UPDATE' AND is_deleted=FALSE THEN
> INSERT INTO foobar(value) VALUES(NEW.value);
> NEW.is_deleted=TRUE;
> NEW.value=OLD.value;
> RETURN NEW;
> END IF;
> END;

Does that do what you want?

--
Richard Huxton
Archonet Ltd

In response to

Browse pgsql-general by date

  From Date Subject
Next Message gkl12799 2007-01-16 19:24:18 find columns that contain a single value for all rows
Previous Message John DeSoi 2007-01-16 18:54:06 Re: Dynamic loading of Perl Code in Postgres functions