PostgreSQL 12 Update : Limited top-level PROCEDURE support that can manage transactions . You still cannot manage transactions in regular SQL functions that are called, so the following remains true, unless you use new top-level procedures.
Functions are part of the transaction from which they are called. Their effects roll back if the transaction rolls back. Their work is committed if the transaction is committed. Any BEGIN... EXCEPT blocks within a function work similarly (and covertly used) to savepoints, such as the SQL SAVEPOINT and ROLLBACK TO SAVEPOINT statements.
The function either succeeds or completes with an error entirely, with the exception of BEGIN... EXCEPT error handling. If an error occurs in the function that is not being processed, the transaction that calls the function is aborted. Aborted transactions cannot commit, and if they try to commit, COMMIT treated as a ROLLBACK , just like for any other transaction with an error. Note:
regress=
See how a transaction that is in a state of error due to zero division rolls back to COMMIT ?
If you call a function without an explicit surrounding transaction, the rules are exactly the same as for any other Pg statement:
BEGIN; SELECT refresh_materialized_view(name); COMMIT;
(where COMMIT will fail if SELECT raises an error).
PostgreSQL (for now) does not support stand-alone transactions in functions where a procedure / function can commit / roll back regardless of the calling transaction. This can be modeled using a new session via dblink .
BUT , things that are not transactional or imperfectly transactional exist in PostgreSQL. If it has non-transactional behavior in normal BEGIN; do stuff; COMMIT; mode BEGIN; do stuff; COMMIT; BEGIN; do stuff; COMMIT; BEGIN; do stuff; COMMIT; block, it also has non-transactional behavior in the function. For example, nextval and setval , TRUNCATE , etc.
Craig Ringer Oct 08 2018-12-12T00: 00Z
source share