# Transactions

> BEGIN, COMMIT and ROLLBACK in StackQL: group provider INSERT statements so that a rollback discards or deletes the resources they would create, with durable journals, recovery and per-session configuration.

Source: https://stackql.io/language-spec/transactions

Groups provider statements so that they are committed together, or rolled back by deleting the resources they created.  Available in StackQL releases from `v1.1.959`.

See also:  
[[` INSERT `]](/language-spec/insert) [[` SET `]](/language-spec/set) [[ Native IaC (Preview) ]](/getting-started/native-iac) [[ Global Flags ]](/command-line-usage/global-flags)

* * *

## Syntax

*beginStatement::=*

*commitStatement::=*

*rollbackStatement::=*

&nbsp;  
&nbsp;  

```sql
{ BEGIN | START TRANSACTION };
COMMIT;
ROLLBACK;
```

Cloud APIs have no transactions of their own, so StackQL implements a transaction as compensation: every provider mutation in the transaction is recorded in a durable journal, and `ROLLBACK` undoes executed mutations by calling the inverse operation the provider declares (for a create, the delete).  It is not database isolation: other clients see each change as soon as the provider applies it, and no isolation is emulated for the SQL backend.

From `v1.1.959` every transaction is run by the engine's `omnisdk` transaction support with no configuration needed.  The earlier transaction coordinators and the `--acid` flag were removed in that release.

## Behaviour

In the default `lazy` mode, a mutation inside a transaction is queued rather than sent, and `ROLLBACK` discards the queue, so the following statements send nothing to the provider:

```sql
BEGIN;
INSERT INTO google.compute.networks (project, data__name, data__autoCreateSubnetworks)
SELECT 'my-project', 'txn-network-01', false;
ROLLBACK;
```

```
transaction begun: Y2JI4I55B3LQLDIFFS2VUCYNT5
mutating statement queued
Rollback OK
```

- `BEGIN` prints `transaction begun: <id>`, a queued mutation prints `mutating statement queued`, `COMMIT` prints `transaction committed` and `ROLLBACK` prints `Rollback OK`.
- Only creates can be committed: an `INSERT` through a provider method whose `inverse` declaration names the delete method and the response field that identifies the created resource.  `UPDATE`, `DELETE`, `REPLACE` and other mutations, and an `INSERT` through a method without a declared inverse, fail before anything is sent to the provider, at `COMMIT` in `lazy` mode or when executed in `eager` mode.  Inverse declarations are new, and most published provider methods do not have one yet, so check a provider before relying on a transaction for it.  Provider authors declare them as described in [Developing StackQL Providers](/developers/developing-stackql-providers#transaction-inverses).
- In `lazy` mode, queued mutations are sent at `COMMIT`.  A read, or a statement with `RETURNING`, first sends the queued mutations so that it sees their effect.  In `eager` mode each mutation is sent when it is executed, and `ROLLBACK` deletes the resources already created.  The mode is set by [`$.transaction`](#transaction-configuration), or by `rollback_type` in the [`--session`](/command-line-usage/global-flags) flag (`nop`, the default, selects `lazy`; `eager` selects `eager`).
- Inside a transaction the first failing statement ends the batch.  A syntax error or a local DDL statement (`CREATE TABLE`, `CREATE VIEW`, `CREATE MATERIALIZED VIEW`) is rejected and aborts the transaction; `COMMIT` is then refused until `ROLLBACK`.  Outside a transaction, local DDL behaves as before.
- `SET`, `UNSET` and other statements that are not provider reads or creates are refused inside a transaction with `statement cannot execute inside a provider transaction`.  Configure the session before `BEGIN`.
- Nested transactions are rejected, and `COMMIT` or `ROLLBACK` without an open transaction fails with `no active provider transaction`.
- `stackql exec` exits with status `1` when a statement in a transaction fails.
- Read cursors must be consumed before `COMMIT` or `ROLLBACK`.  PostgreSQL clients that open transactions implicitly (SQLAlchemy, psycopg) need an `AUTOCOMMIT` connection to run local DDL.

The journal and transaction records are kept with the [native IaC](/getting-started/native-iac#ledger-and-state-location) state under `<approot>/iac`: transaction records in `ledger/<collection>/.transactions/` and journals in `journal/txn-<id>.jsonl`.

## Transaction status

`stackql_preview.txn.status` returns the open transaction's `id`, `status`, `version` and `pending` mutations (a JSON array), and takes no predicates:

```sql
BEGIN;
SELECT * FROM stackql_preview.txn.status;
ROLLBACK;
```

```
transaction begun: SHFQN2KCDNFPWNN6XXWPC22KX4
|----------------------------|--------|---------|---------|
|             id             | status | version | pending |
|----------------------------|--------|---------|---------|
| SHFQN2KCDNFPWNN6XXWPC22KX4 | active |       4 | null    |
|----------------------------|--------|---------|---------|
Rollback OK
```

## Transaction configuration

By default a transaction uses the collection `sql` in the IaC state root.  `SET "$.transaction"` replaces the configuration for the session's next transaction; it must be a complete JSON object, needs a `collection`, and cannot change while a transaction is open:

```sql
SET "$.transaction" = '{"collection": "demo", "mode": "lazy"}';
BEGIN;
SELECT * FROM stackql_preview.txn.status;
COMMIT;
```

| Key | Description |
|--|--|
| `collection` | Required.  Ledger collection the transaction records its resources in. |
| `state` | Optional directory under the IaC state root, as for native IaC. |
| `mode` | `lazy` or `eager`, overriding `rollback_type`. |
| `keys`, `targets` | Explicit resource addressing.  `targets` maps a relation to its resource key, identity field and addressing parameter, for example `{"aws.ec2.vpcs": {"key": "vpc", "identity": "VpcId", "addressed_by": "VpcId"}}`.  Needed only when the identity of a create cannot be derived from the provider's declared inverse. |
| `lease_seconds` | Lease held on the collection.  Default `300`. |
| `timeout_seconds` | Maximum execution lifetime.  Default `900`. |
| `resume_id` | ID of an earlier transaction to resume; see [Recovery](#recovery). |

`UNSET "$.transaction"` restores the defaults.  Provider aliases (`$.providers`) cannot be used inside a transaction.

## Recovery

A process that exits with a transaction open leaves it in the journal, and its lease expires after `lease_seconds`.  To finish it, reconnect, set the same collection and state with `resume_id`, then `BEGIN`; read the status before anything else, then `COMMIT` or `ROLLBACK`:

```sql
SET "$.transaction" = '{"collection": "demo", "resume_id": "SHFQN2KCDNFPWNN6XXWPC22KX4"}';
BEGIN;
SELECT * FROM stackql_preview.txn.status;
ROLLBACK;
```

Stop or isolate the previous process first: a lease cannot fence provider requests that are already in flight.  A closed transaction ID cannot be resumed.

When a mutation's outcome is uncertain, verify the provider's state, then record it with `stackql_preview.txn.recover`, passing the transaction `version` from the status, a `resources` JSON array of `key`, `outcome` (`applied` or `absent`), the observed resource `version` and, for an applied create, the verified `identity`, and `continue`: `'true'` attests that the statement completed, `'false'` aborts it for a subsequent rollback.  Recovery sends no provider request:

```sql
SELECT * FROM stackql_preview.txn.recover
WHERE version = '7'
  AND resources = '[{"key": "item", "outcome": "applied", "version": "2", "identity": "id-0123"}]'
  AND continue = 'false';
ROLLBACK;
```

## Permissions

With [access management](/command-line-usage/access-management) enabled, `BEGIN`, `COMMIT` and `ROLLBACK` require `execute` on `host/sql/begin`, `host/sql/commit` and `host/sql/rollback`, and ownership and permission checks apply to every operation in the transaction.  Without it, an open transaction is bound to its session, but a durable transaction ID does not establish ownership by a user.
