Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a function detect the trigger event type?

I am using a function in PostgreSQL 9.1:

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 a condition about events in the body of that function like (pseudocode):

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

How to express this condition?
(Note BEFORE INSERT OR UPDATE in the trigger!)

like image 590
Peter Krauss Avatar asked May 19 '14 17:05

Peter Krauss


People also ask

How do you know if an event is triggered?

$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').

What functions are performed by triggers?

The TRIGGER function retrieves the event, subevent, or name of the object or analytic workspace that caused the execution of a trigger program (that is, a TRIGGER_DEFINE, TRIGGER_AFTER_UPDATE, or TRIGGER_BEFORE_UPDATE program, or any program identified as a trigger program using the TRIGGER command).

How do you call a trigger function?

PL/pgSQL can be used to define trigger functions on data changes or database events. A trigger function is created with the CREATE FUNCTION command, declaring it as a function with no arguments and a return type of trigger (for data change triggers) or event_trigger (for database event triggers).


1 Answers

Yes, TG_OP. The manual:

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.

like image 83
Erwin Brandstetter Avatar answered Oct 11 '22 12:10

Erwin Brandstetter