Re: Help creating rules/triggers/functions - Mailing list pgsql-sql

From Jan Wieck
Subject Re: Help creating rules/triggers/functions
Date
Msg-id 200103021534.KAA03563@jupiter.jw.home
Whole thread Raw
In response to Help creating rules/triggers/functions  (Blaise Carrupt <bc@mjtsa.com>)
List pgsql-sql
Blaise Carrupt wrote:
> Hi all !
>
> I use PostgreSQL 7.0.2 on a HP-UX system.
>
> I would like to create a simple function and a simple trigger (or rule) that
> deny a delete from a table if the row is referenced in another table.
>
> I though it should look like this (from my Ingres experience... :) :
>
> create function A_del(int4 i_id)
> BEGIN
>    SELECT id
>      FROM b
>      where a_id = :i_id;
>
>    if rowcount > 0 then
>    RAISE EXCEPTION "not allowed !"
>    end if;
> END
>
       CREATE FUNCTION A_del () RETURNS opaque AS '       DECLARE           nrefs integer;       BEGIN           nrefs
:=count(*) FROM b WHERE a_id = OLD.i_id;           IF nrefs > 0 THEN               RAISE EXCEPTION ''a_id % still
referencedfrom b'', OLD.i_id;           END IF;           RETURN OLD;       END;'       LANGUAGE 'plpgsql';
 
>
> create trigger before delete from A for each row execute procedure A_del(old.id)
       CREATE TRIGGER A_del BEFORE DELETE ON A           FOR EACH ROW EXECUTE PROCEDURE A_del();

>
>
> But it seems to be much more complicated with Postgres (create a C function
> using CurrentTriggerData,...). May I have missed something or is it really much
> more complicated ?
   Alternatively  (IMHO  preferred)  you could use a referential   integrity constraint in  table  B,  which  would
also cover   UPDATE on A and check values inserted/updated into/in B.
 
       CREATE TABLE B ( ...           FOREIGN KEY (i_id) REFERENCES A (a_id)


Jan

--

#======================================================================#
# It's easier to get forgiveness for being wrong than for being right. #
# Let's break this rule - forgive me.                                  #
#================================================== JanWieck@Yahoo.com #



_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com



pgsql-sql by date:

Previous
From: Tom Lane
Date:
Subject: Re: Help needed -> ERROR: record arow has no field description
Next
From: "pgsql-sql"
Date:
Subject: Re: lo_import for storing Blobs