Can a function detect the trigger event type?

后端 未结 1 1150
时光取名叫无心
时光取名叫无心 2021-01-06 07:26

I am using a function

CREATE FUNCTION myfunc() RETURNS trigger AS $$ ... $$ LANGUAGE plpgsql;

with a trigger,

    CREATE T         


        
相关标签:
1条回答
  • 2021-01-06 08:13

    Yes, TG_OP. Per documentation:

    TG_OP
    Data type text; a string of INSERT, UPDATE, DELETE, or TRUNCATE telling for which operation the trigger was fired.

    Careful what you return in each case. Sometimes you want to RETURN NEW, which is not defined in case of a DELETE or vice versa. If it gets too complex, rather split into multiple triggers, called on separate events.

    Example:

    IF TG_OP = 'DELETE' THEN
       -- do something
       RETURN OLD;  -- depends!
    ELSIF TG_OP = 'UPDATE' THEN  
       -- do something
       RETURN NEW;  -- depends!
    END IF;
    

    More code examples in related answers.

    0 讨论(0)
提交回复
热议问题