2

I have function, which should be called after update and delete on one table.

At the end of function I have to return "old" if function was called after delete or "new" if procedure was called after update.

I did it like this:

if new is null
then
 return old;
end if;
return new;

But I get error telling me that "new" has not been initialized if function is called after delete. My question is how to recognize if function was called after delete or update?

asked Sep 20, 2018 at 12:18

2 Answers 2

4

Assuming this is a PL/pgSQL function, then - as documented in the manual - a trigger function automatically has access to some special variables. One of them is TG_OP that identifies the trigger operation.

The manual even has an example on how to use it:

IF (TG_OP = 'DELETE') THEN
 -- do something with the OLD record
ELSIF (TG_OP = 'UPDATE') THEN
 -- do something with the NEW record
ELSIF (TG_OP = 'INSERT') THEN
 -- do something entirely different
END IF;
answered Sep 20, 2018 at 12:51
1

There will be a struct called 'EventTriggerData' passed to the trigger function as its argument.

It can be read as,

event_trigger_data = (EventTriggerData *)fcinfo->context;

Include this condition check in your code,

if((nodeTag(event_trigger_data->parseTree) == T_DeleteStmt)
 // trigger called from delete statement
if((nodeTag(event_trigger_data->parseTree) == T_UpdateStmt)
 // trigger called from update statement

Might be helpful if you are created udf's written in C

answered Sep 20, 2018 at 12:34
1
  • Thank you for your answer, but I used solution from accepted answer, since it seems more simple and straight forward solution Commented Sep 20, 2018 at 12:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.