7

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!)

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Peter Krauss
  • 13,174
  • 24
  • 167
  • 304
  • Hum... I am reading [pgdoc about plpgsql-trigger](http://www.postgresql.org/docs/9.1/static/plpgsql-trigger.html): I will try the `TG_OP` *special variable*. – Peter Krauss May 19 '14 at 17:42

1 Answers1

18

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.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228