Thread: Trigger triggered from a foreign key

Trigger triggered from a foreign key

From
Victor Sterpu
Date:
I have this trigger that works fine. The trigger prevents the deletion 
of the last record.
But I want skip this trigger execution when the delete is done from a 
external key.
How can I do this?

This is the fk
ALTER TABLE focgdepartment  ADD CONSTRAINT fk_focgdep_idfocg FOREIGN KEY (idfocg)      REFERENCES focg (id) MATCH
SIMPLE     ON UPDATE NO ACTION ON DELETE CASCADE;
 

This is the trigger
CREATE FUNCTION check_focgdepartment_delete_restricted() RETURNS trigger 
AS $check_focgdepartment_delete_restricted$
BEGIN    IF ( (SELECT count(*) FROM focgdepartment WHERE idfocg = 
OLD.idfocg)=1)    THEN RAISE EXCEPTION 'Last record can not be deleted';    END IF;    RETURN OLD;
END;
$check_focgdepartment_delete_restricted$
LANGUAGE plpgsql;
CREATE TRIGGER focgdepartment_delete_restricted BEFORE DELETE ON 
focgdepartment FOR EACH ROW EXECUTE PROCEDURE 
check_focgdepartment_delete_restricted();


Thank you



Re: Trigger triggered from a foreign key

From
"David Johnston"
Date:
> -----Original Message-----
> From: pgsql-sql-owner@postgresql.org [mailto:pgsql-sql-
> owner@postgresql.org] On Behalf Of Victor Sterpu
> Sent: Friday, October 19, 2012 2:15 PM
> To: pgsql-sql@postgresql.org
> Subject: [SQL] Trigger triggered from a foreign key
> 
> I have this trigger that works fine. The trigger prevents the deletion of
the
> last record.
> But I want skip this trigger execution when the delete is done from a
external
> key.
> How can I do this?
> 

I do not think this is possible; there is no "stack" context to examine to
determine how a DELETE was issued.

The trigger itself would seem to be possibly exhibit concurrency issues,
meaning that in certain circumstances the last record could be deleted.  You
may want to add explicit locking to avoid that possibility.  That or figure
out a better way to accomplish whatever it is you are trying to do.

David J.





Re: Trigger triggered from a foreign key

From
Jasen Betts
Date:
On 2012-10-19, Victor Sterpu <victor@caido.ro> wrote:
> I have this trigger that works fine. The trigger prevents the deletion 
> of the last record.
> But I want skip this trigger execution when the delete is done from a 
> external key.
> How can I do this?

perhaps you have to use a rule instead of a trigger?

-- 
⚂⚃ 100% natural