Can a function detect the trigger event type?

北城以北 提交于 2019-12-19 04:12:16

问题


I am using a function

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

with a trigger,

    CREATE TRIGGER mycheck BEFORE INSERT OR UPDATE ON t
       FOR EACH ROW EXECUTE PROCEDURE myfunc();

My problem now is to express in the body of myfunc() a condition about events, a plpgsql like

    IF TRIGGER_EVENT_WAS_INSERT THEN ...doThis... END IF;

How to express this condition? (see that I have "INSERT OR UPDATE" trigger event)


I am using PostgreSQL v9.1.


回答1:


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.



来源:https://stackoverflow.com/questions/23743766/can-a-function-detect-the-trigger-event-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!