I have some questions about how postgres functions and transactions work.
Currently my function looks like this:
CREATE OR REPLACE FUNCTION test_function(some_id character varying)
RETURNS character varying AS
$BODY$
BEGIN
S1;
S2;
S3;
.
.
Sn;
RETURN some_id;
END; $BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
The statements can be INSERT
, UPDATE
or plain SELECT
queries based on some_id
. As I understand from postgre documentation, all statements in this function are executed as a single transaction and committed at the END.
My questions are:
S1
is successful but S2
fails, will S1
get committed?BEGIN
are executed as a single trasaction, correct?COMMIT
before END
and all statements are successful, will the transaction be committed regardless of autocommit = on/off ?S1, S2, S3
are all INSERT
statements. S1
and S2
succeed but S3
fails, will the inserts in S1, S2
be reversed in the absence of an explicit ROLLBACK
statement?Thank you!
Answers by number:
No; if S2
fails, the whole transaction is aborted and can only be rolled back.
There is probably a misunderstanding. The SQL statement BEGIN
that starts a transaction is something quite different from the BEGIN
that starts a PL/pgSQL block. The latter does not start a transaction.
If there was no explicit SQL command BEGIN
, every statement runs in its own transaction (“autocommit”).
All statements in a function are executed in a single transaction.
You cannot have COMMIT
(or ROLLBACK
) in a function.
Yes. This is the same question as 1., only in the negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With