7.6.16. IN AUTONOMOUS TRANSACTION

Used for

Executing a statement or a block of statements in an autonomous transaction

Available in

PSQL

Syntax

  1. IN AUTONOMOUS TRANSACTION DO <compound_statement>
Table 93. IN AUTONOMOUS TRANSACTION Statement Parameter
ArgumentDescription

compound_statement

A statement or a block of statements

An IN AUTONOMOUS TRANSACTION statement enables execution of a statement or a block of statements in an autonomous transaction. Code running in an autonomous transaction will be committed right after its successful execution, regardless of the status of its parent transaction. It might be needed when certain operations must not be rolled back, even if an error occurs in the parent transaction.

An autonomous transaction has the same isolation level as its parent transaction. Any exception that is thrown in the block of the autonomous transaction code will result in the autonomous transaction being rolled back and all made changes being cancelled. If the code executes successfully, the autonomous transaction will be committed.

Example

Using an autonomous transaction in a trigger for the database ON CONNECT event, in order to log all connection attempts, including those that failed:

  1. CREATE TRIGGER TR_CONNECT ON CONNECT
  2. AS
  3. BEGIN
  4. -- Logging all attempts to connect to the database
  5. IN AUTONOMOUS TRANSACTION DO
  6. INSERT INTO LOG(MSG)
  7. VALUES ('USER ' || CURRENT_USER || ' CONNECTS.');
  8. IF (CURRENT_USER IN (SELECT
  9. USERNAME
  10. FROM
  11. BLOCKED_USERS)) THEN
  12. BEGIN
  13. -- Logging that the attempt to connect
  14. -- to the database failed and sending
  15. -- a message about the event
  16. IN AUTONOMOUS TRANSACTION DO
  17. BEGIN
  18. INSERT INTO LOG(MSG)
  19. VALUES ('USER ' || CURRENT_USER || ' REFUSED.');
  20. POST_EVENT 'CONNECTION ATTEMPT' || ' BY BLOCKED USER!';
  21. END
  22. -- now calling an exception
  23. EXCEPTION EX_BADUSER;
  24. END
  25. END

See also

Transsaction Control