Home > Software engineering >  Does PERFORM inside of a trigger execute a function in the same transaction as the caller?
Does PERFORM inside of a trigger execute a function in the same transaction as the caller?

Time:12-15

I have come across a postgres trigger that is defined like so...

CREATE FUNCTION public.my_trigger_func() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
  BEGIN
    PERFORM my_other_func(NEW.my_val);
    RETURN NULL;
  END;
$$;

From what this other post's answer says (I cannot find it explicitly stated in the postgres documentation):

All PostgreSQL triggers execute in the same transaction as the transaction that has triggered them.

However, does the function my_other_func, called with PERFORM, get run in the same transaction as well? Or what is its behavior in this context?

Postgres version:

select version();
                                                     version                                                      
------------------------------------------------------------------------------------------------------------------
 PostgreSQL 12.7 (Debian 12.7-1.pgdg100 1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit

CodePudding user response:

The documentation states:

In all cases, a trigger is executed as part of the same transaction as the statement that triggered it, so if either the statement or the trigger causes an error, the effects of both will be rolled back.

Now a PostgreSQL function is always executed in a single transaction. You can deduce that from this statement in the documentation:

A procedure can commit or roll back transactions during its execution (then automatically beginning a new transaction), so long as the invoking CALL command is not part of an explicit transaction block. A function cannot do that.

The upshot is that the whole trigger function my_trigger_func(), including all functions called from it, will execute in the same transaction as the statement that triggered it.

  • Related