# Transactions

`db.$transaction(fn)` runs several statements as one unit of work: either all of them take effect, or none does.

```ts
import { sql } from 'db2kit';

const orderId = await db.$transaction(
  async (tx) => {
    const created = await tx.call(createOrderWithOutcome, { customerId, amount });
    await tx.execute(
      sql`INSERT INTO MYSCHEMA.ORDER_LOG (ORDER_ID, STATE) VALUES (${created.output.orderId}, ${'C'})`,
    );
    return created.output.orderId;
  },
  { tag: 'OrderService.create' },
);
```

`tx` offers `query`, `queryOne`, `execute`, `call`, `run` and the object API (`findMany`... `create`, `update`...), with the same signatures as `db`. `tx.id` is the number of the transaction in the audit trail.

## How it works

| Step     | What happens                                                                                                                                                               |
| :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Start    | A connection is borrowed from the pool and autocommit is turned off on it                                                                                                  |
| Callback | Every `tx` statement runs on that connection, one at a time, in call order. A statement started without `await` still runs before the end                                  |
| End      | The callback resolved and nothing failed: `COMMIT`. Otherwise: `ROLLBACK`. The connection goes back to the pool with autocommit on, or is discarded after a driver failure |

| Option      | Default                  | Purpose                                                                                                                                                                                                                                                                                                     |
| :---------- | :----------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tag`       | the one from the context | Business label of every statement, `COMMIT` and `ROLLBACK`                                                                                                                                                                                                                                                  |
| `timeoutMs` | `transactions.timeoutMs` | Maximum duration, see [Timeout](#timeout)                                                                                                                                                                                                                                                                   |
| `rollback`  | `false`                  | Ends with `ROLLBACK` whatever the callback returns: to try writes on a test subsystem and undo them, as `npx db2kit add --rollback` does. A procedure that modifies data is then accepted without a validated outcome rule, since nothing is committed. A procedure that commits on return is still refused |

## Rollback-only after any error

After the first error inside a transaction, the transaction can only be rolled back, **even when the callback catches the error**:

- every later `tx` statement is refused before being sent, with a `Db2UsageError` that names the first error;
- at the end, db2kit sends `ROLLBACK`, and `$transaction` throws `Db2TransactionRolledBackError` (`reason: 'failed'`, the first error as `cause`).

Why: a failed step leaves the work incomplete. After -911 (deadlock or lock timeout), Db2 has already rolled back the whole unit of work: going on would commit only the statements that come after it.

Every error counts: Db2 errors, procedure rejections and unknown statuses, checks before sending (invalid input, read-only mode), misuse.

When the callback throws, `$transaction` rolls back and rethrows that same error.

```ts
import { Db2ProcedureRejectedError, Db2TransactionRolledBackError } from 'db2kit';

try {
  await db.$transaction(async (tx) => {
    /* ... */
  });
} catch (error) {
  const cause = error instanceof Db2TransactionRolledBackError ? error.cause : error;
  if (cause instanceof Db2ProcedureRejectedError) {
    throw new UnprocessableEntityException({ fields: cause.reasons });
  }
  throw error;
}
```

## Procedures in a transaction

`tx.call` refuses with `Db2UsageError`, before any network call:

| Procedure                                                                                  | Why                                                                                               |
| :----------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------ |
| Declared `COMMIT ON RETURN YES`                                                            | Db2 commits the whole unit of work when it returns, including the statements already run          |
| Declared `MODIFIES SQL DATA`, without an outcome rule or with a draft (`validated: false`) | A rejection reported with SQLCODE 0 would otherwise be committed with the rest of the transaction |

Procedures declared `READS SQL DATA`, `CONTAINS SQL` or `NO SQL` can be called without a rule, through `unchecked(descriptor, reason)` as outside a transaction (`tx.call` refuses the descriptor alone, as `db.call` does: [procedures.md](procedures.md#a-call-without-its-outcome-rule)). With `rollback: true`, a procedure that modifies data can be called through `unchecked()` too: the transaction never commits. Without `rollback: true`, `unchecked()` changes nothing to the refusal above: a rejection would be committed with the rest.

**Not detected**: a procedure program can run `COMMIT` or `ROLLBACK` itself, and the catalog does not say so. A `ROLLBACK` inside the program would undo the statements run before it in the transaction, a `COMMIT` would make them permanent. Check with the owners of each procedure called inside a transaction.

## Timeout

`transactions.timeoutMs` (default 10000 ms), or `{ timeoutMs }` per transaction. Beyond it:

- db2kit sends `ROLLBACK` at once, right after the statement in progress, to release the locks;
- every later `tx` statement is refused;
- `$transaction` throws `Db2TransactionRolledBackError` with `reason: 'timeout'`, or the error of the callback if it threw.

The connection goes back to the pool when the callback settles. The timer is cleared when the callback settles, and never keeps the process alive on its own. Keep HTTP calls, file access and any wait for a user outside the transaction: its locks are held until it ends, and other applications wait for them.

## Misuse

| Case                                                    | Behavior                                                                                                                                                           |
| :------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `db.query`, `db.execute`, `db.call` inside the callback | `Db2UsageError`, and the transaction fails. The statement would run on another connection, outside the transaction, and could wait for the transaction's own locks |
| `db.$transaction` inside the callback                   | `Db2UsageError`: nested transactions are not supported                                                                                                             |
| `tx` used after the callback returned                   | `Db2UsageError`, for the caller to handle: `$transaction` has already ended and reports nothing more                                                               |
| Invalid `timeoutMs`                                     | `Db2UsageError`, before borrowing a connection                                                                                                                     |

A client for another database can be used inside the callback: it is not part of the transaction.

## Failure of the driver

| Failure    | Result                                                                                                                                                                                                                             |
| :--------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Start      | The callback does not run. A connection that cannot open, or autocommit that cannot be turned off, gives a `Db2QueryError` as for a statement (`sql: 'BEGIN'`), or the `Db2UnavailableError` and `Db2PoolTimeoutError` of the pool |
| `COMMIT`   | `Db2TransactionCommitError`: whether Db2 committed is **unknown**, a connection lost during `COMMIT` can end either way. Check the effect before retrying. The connection is discarded                                             |
| `ROLLBACK` | `$transaction` still throws the error that caused the rollback. The failure is in the audit trail and the connection is discarded                                                                                                  |

ibm_db 4.0.1 ends a transaction in two steps: `SQLEndTran`, then autocommit back on, **even when the first step failed** (source). The ODBC specification commits the open work when autocommit is turned back on. db2kit discards the connection after any failed end, but cannot undo what the driver did meanwhile. Whether Db2 CLI commits after a failed `ROLLBACK` on a connection that still works is not verified.

## No automatic retry

A transaction is never replayed by db2kit. After a -911, call `$transaction` again only when the whole callback is safe to run twice.

## Isolation

Not configurable yet: the transaction runs at the isolation level of the connection (CLI keyword `TXNISOLATION`, cursor stability by default).

## Audit

Every statement of the transaction carries `transaction: { id }`. `COMMIT` and `ROLLBACK` produce their own events (`source: 'transaction'`, `sql: 'COMMIT'` or `'ROLLBACK'`) with `transaction.durationMs`, the time the transaction held its locks, and `transaction.statements`. `consoleSink` shows them as `tx=12 (35 ms, 3 statement(s))`. See [audit.md](audit.md).

## Read-only mode

Reads work inside a transaction. A write is refused before being sent, which fails the transaction: it is rolled back.
