2 41.8. Transaction Management #
4 In procedures invoked by the CALL command as well as in anonymous code
5 blocks (DO command), it is possible to end transactions using the
6 commands COMMIT and ROLLBACK. A new transaction is started
7 automatically after a transaction is ended using these commands, so
8 there is no separate START TRANSACTION command. (Note that BEGIN and
9 END have different meanings in PL/pgSQL.)
11 Here is a simple example:
12 CREATE PROCEDURE transaction_test1()
17 INSERT INTO test1 (a) VALUES (i);
27 CALL transaction_test1();
29 A new transaction starts out with default transaction characteristics
30 such as transaction isolation level. In cases where transactions are
31 committed in a loop, it might be desirable to start new transactions
32 automatically with the same characteristics as the previous one. The
33 commands COMMIT AND CHAIN and ROLLBACK AND CHAIN accomplish this.
35 Transaction control is only possible in CALL or DO invocations from the
36 top level or nested CALL or DO invocations without any other
37 intervening command. For example, if the call stack is CALL proc1() →
38 CALL proc2() → CALL proc3(), then the second and third procedures can
39 perform transaction control actions. But if the call stack is CALL
40 proc1() → SELECT func2() → CALL proc3(), then the last procedure cannot
41 do transaction control, because of the SELECT in between.
43 PL/pgSQL does not support savepoints (SAVEPOINT/ROLLBACK TO
44 SAVEPOINT/RELEASE SAVEPOINT commands). Typical usage patterns for
45 savepoints can be replaced by blocks with exception handlers (see
46 Section 41.6.8). Under the hood, a block with exception handlers forms
47 a subtransaction, which means that transactions cannot be ended inside
50 Special considerations apply to cursor loops. Consider this example:
51 CREATE PROCEDURE transaction_test2()
57 FOR r IN SELECT * FROM test2 ORDER BY x LOOP
58 INSERT INTO test1 (a) VALUES (r.x);
64 CALL transaction_test2();
66 Normally, cursors are automatically closed at transaction commit.
67 However, a cursor created as part of a loop like this is automatically
68 converted to a holdable cursor by the first COMMIT or ROLLBACK. That
69 means that the cursor is fully evaluated at the first COMMIT or
70 ROLLBACK rather than row by row. The cursor is still removed
71 automatically after the loop, so this is mostly invisible to the user.
72 But one must keep in mind that any table or row locks taken by the
73 cursor's query will no longer be held after the first COMMIT or
76 Transaction commands are not allowed in cursor loops driven by commands
77 that are not read-only (for example UPDATE ... RETURNING).