## 16.6. PL/pgSQL Grammar Extension for Autonomous Transactions

Block construction in PL/pgSQL is extended by optional `autonomous` keyword. It is possible to treat the whole function body as an autonomous transaction:

    create function foo(x integer) returns integer as $$
    begin autonomous
      return x;
    end;
    $$ language plpgsql;

or create separate begin-end block:

    create or replace function myaudit() returns boolean as $$
    begin autonomous
            begin autonomous
            insert into audit_schedule values ('new audit',now());
            end;
            ... -- do audit itself
            return true;
    end;
    $$ language plpgsql;

When exception is raised inside `BEGIN AUTONOMOUS` block, this autonomous transaction is aborted and standard exception handling procedure is started, unwinding stack and executing exception handlers until exception is caught. So exception handling is done in the same way as with normal Postgres Pro subtransactions.

When an error is caught by an `EXCEPTION` clause, the local variables of the PL/pgSQL function remain as they were when the error occurred, but all changes to persistent database state within the block are rolled back.