0

I've got plpgsql function that does multiple inserts to multiple tables. I've also trigger that do some stuff f.g notifies some service.

The process looks like this:

  1. Insert into table A
  2. Trigger executed on table A
  3. Function fails on insert into table B

And then transaction is rollbacked and I've got no data in table A but trigger has executed. Furthemore there is no any DELETE on table A.

My trigger and function:

CREATE OR REPLACE FUNCTION some_function() RETURNS trigger AS
$$
BEGIN
    PERFORM pg_notify('pgchannel1', row_to_json(new)::text);
    RETURN NULL;
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER some_trigger
    AFTER INSERT
    ON some_table
    FOR EACH ROW
EXECUTE PROCEDURE some_function();

I would like to have this process like that:

  1. Insert into table A
  2. Insert into table B
  3. Trigger executed on table A / Trigger executed when function is done

How could I catch that transaction was rollbacked and not executing trigger? Is there any way to trigger function status?

1 Answer 1

1

Yes, you can do that with constraint triggers:

CREATE CONSTRAINT TRIGGER some_trigger
   AFTER INSERT ON some_table
   DEFERRABLE INITIALLY DEFERRED FOR EACH ROW
EXECUTE PROCEDURE some_function();

Such a trigger will fire at the end of the transaction rather than immediately.

Sign up to request clarification or add additional context in comments.

4 Comments

Thats it. There is another question. Is it possible to spy function state or trigger after its execution (done).
I am not sure what you mean.
I've got function that is executing multiple inserts on multiple tables. Is there any way to trigger function when it finish?
No, a trigger is always defined on one table.

Your Answer

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.