Sub topic 14
Autonomous Transactions for Logging and Auditing
This chapter assumes you can write stored procedures and functions, use EXCEPTION blocks, and know that COMMIT and ROLLBACK end a transaction. You also need a schema with CREATE TABLE and CREATE PROCEDURE privileges.
The problem: logs that disappear on rollback
Suppose a procedure fails and you want to record the failure in a log table. The usual handler writes the log row, then re-raises the error. The caller then rolls back, and the log row is rolled back with it. You lose the evidence of what went wrong.
The cause is that a log insert normally belongs to the same transaction as the work around it. Its fate follows the main transaction. An autonomous transaction breaks that link.
What an autonomous transaction is
An autonomous transaction is an independent transaction started from inside another one. The calling transaction is called the main transaction. While the autonomous transaction runs, the main transaction is suspended. When the autonomous block ends, control returns to the main transaction, which resumes where it stopped.
You declare it with PRAGMA AUTONOMOUS_TRANSACTION in the declaration section of a subprogram. A pragma is a compiler directive. It changes how the compiler treats the unit and is not a statement that runs.
A logging procedure
First create a log table.
CREATE TABLE app_log (
log_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
logged_by VARCHAR2(128) DEFAULT SYS_CONTEXT('USERENV', 'SESSION_USER'),
severity VARCHAR2(10) NOT NULL,
message VARCHAR2(4000)
);Now the logging procedure.
CREATE OR REPLACE PROCEDURE log_message (
p_severity IN app_log.severity%TYPE,
p_message IN app_log.message%TYPE
) AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO app_log (severity, message)
VALUES (p_severity, SUBSTR(p_message, 1, 4000));
COMMIT;
END log_message;
/The COMMIT here commits only the work done inside log_message. It does not commit anything in the caller's transaction.
Using it from another subprogram
This version of raise_salary logs a failure before it re-raises the error.
CREATE OR REPLACE PROCEDURE raise_salary_logged (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
EXCEPTION
WHEN OTHERS THEN
log_message('ERROR', 'raise_salary_logged failed: ' || SQLERRM);
RAISE;
END raise_salary_logged;
/Call it with an employee that does not exist, roll back, and read the log.
BEGIN
raise_salary_logged(p_employee_id => -1);
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Caught: ' || SQLERRM);
END;
/
SELECT severity, message
FROM app_log
ORDER BY log_id;The query returns the error row even though the caller rolled back. The RAISE with no argument re-raises the original exception, so the caller still sees the failure. Handling an error by logging it and then swallowing it would hide the problem. Always re-raise unless you have actually recovered.
Rules you must follow
Every autonomous transaction must end cleanly.
- Before the autonomous block returns, it must commit or roll back any DML it performed. If it ends with uncommitted changes, Oracle raises
ORA-06519: active autonomous transaction detected and rolled back. - A
COMMITorROLLBACKwith noSAVEPOINTclause affects only the autonomous transaction. - A procedure that only reads data, with no DML, needs no
COMMIT.
The pragma applies to the subprogram it appears in, not to its callers. You can place it in:
- Top-level standalone procedures and functions.
- Procedures and functions declared in a package body or specification.
- Methods of object types.
- Database triggers.
- Anonymous blocks, but not nested ones.
You cannot put it on a whole package. Mark each subprogram that needs it.
Isolation: what the autonomous block can see
The autonomous transaction does not see uncommitted changes from the main transaction. It is a separate transaction, so Oracle's read consistency applies as between two sessions. It sees only data committed before it began.
This leads to a common deadlock. If the main transaction has updated a row and the autonomous block tries to update the same row, the autonomous block waits for a lock that the suspended main transaction holds. The main transaction cannot resume until the autonomous one finishes, so Oracle detects the deadlock and raises ORA-00060.
CREATE OR REPLACE PROCEDURE touch_employee (
p_employee_id IN employees.employee_id%TYPE
) AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
UPDATE employees
SET salary = salary
WHERE employee_id = p_employee_id;
COMMIT;
END touch_employee;
/
BEGIN
UPDATE employees SET salary = salary + 1 WHERE employee_id = 100;
touch_employee(100); -- ORA-00060: deadlock detected
END;
/Use autonomous transactions for work that is independent of the main transaction's data, such as a log table the main work never touches.
Auditing with a trigger
A common use is recording attempted changes, including ones that get rolled back. A trigger can call an autonomous procedure. Do not put the pragma on the trigger itself unless the trigger's own work must commit separately. Put the commit in a helper.
CREATE OR REPLACE PROCEDURE audit_salary_attempt (
p_employee_id IN NUMBER,
p_old_salary IN NUMBER,
p_new_salary IN NUMBER
) AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO app_log (severity, message)
VALUES ('AUDIT',
'Employee ' || p_employee_id ||
' salary ' || p_old_salary || ' -> ' || p_new_salary);
COMMIT;
END audit_salary_attempt;
/
CREATE OR REPLACE TRIGGER trg_employees_salary_audit
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
audit_salary_attempt(:OLD.employee_id, :OLD.salary, :NEW.salary);
END;
/The trigger is BEFORE UPDATE, so the audit row is recorded even if a later constraint failure or a rollback cancels the update. Be aware that a row-level trigger can fire more than once for the same row if Oracle restarts a statement because of a write conflict, so audit rows may repeat. Treat the audit trail as a record of attempts, not a precise change history. For a precise history of committed changes, use a trigger inside the main transaction or a feature such as Flashback Data Archive.
Gotchas
| Issue | What happens | What to do |
|---|---|---|
| Autonomous block ends with uncommitted DML | `ORA-06519` | Commit or roll back before returning |
| Both transactions touch the same row | `ORA-00060` deadlock | Keep autonomous work on separate data |
| Logging inside a function called from SQL | The function does DML, which SQL queries forbid, though an autonomous function may commit its own | Test it carefully and prefer a procedure |
| Heavy use in a loop | Each call commits, which costs redo and log writes | Batch, or log only significant events |
| Logging fails inside the handler | A second error masks the original | Wrap the log call in its own handler |
| Hidden commits | Callers do not expect a subprogram to commit anything | Document the behavior in the name and comments |
Each autonomous transaction also counts against the TRANSACTIONS limit and uses its own transaction slot, so deep nesting of autonomous calls is wasteful.
A safer logging helper protects the caller from a logging failure.
CREATE OR REPLACE PROCEDURE safe_log (
p_severity IN app_log.severity%TYPE,
p_message IN app_log.message%TYPE
) AS
BEGIN
log_message(p_severity, p_message);
EXCEPTION
WHEN OTHERS THEN
NULL; -- logging must never break the business operation
END safe_log;
/Swallowing every error is a deliberate trade-off here. If losing a log row is unacceptable, remove the handler and let the failure propagate.
When to use and when to avoid
Use autonomous transactions for:
- Error logs that must survive a rollback.
- Audit records of attempted actions.
- Generating sequence-like numbers that must not be rolled back.
Avoid them to:
- Work around locking or constraint problems. This usually hides a design flaw.
- Split business work into pieces that appear atomic but are not. If the main transaction rolls back, the autonomous work stays committed, and data can become inconsistent.
Exercise
A procedure updates an orders row, then calls an autonomous logging procedure, and then fails and rolls back. What happens to the log row and to the orders update? Then name the error you get if the logging procedure inserts a row but has no COMMIT or ROLLBACK before it ends.
Show answer
The log row stays, because the autonomous transaction committed independently. The orders update is rolled back, because it belonged to the main transaction. If the logging procedure ends with the insert uncommitted, Oracle raises ORA-06519 and rolls back the autonomous work.
Exercise
In a main transaction you update the row for employee 100. You then call an autonomous procedure that updates the same row and commits. What error occurs, and why?
Show answer
ORA-00060, deadlock detected. The autonomous transaction waits for the row lock held by the suspended main transaction, and the main transaction cannot resume until the autonomous one finishes.