# Transactions

## Introduction

A transaction makes several writes one: they all count, or none does. Run the work in `connections.transaction()`, and everything
the callback awaits joins the transaction by itself: repositories, any query of the connection, the database queue and the
listeners of an event. You pass no transaction object around.

```ts title="modules/notes/NotePublishing.ts"
import { EventDispatcher } from '@marmeon/core';
import { Connections } from '@marmeon/database';
import { Queue } from '@marmeon/queue';
import { NotePublished } from './events/NotePublished.ts';
import { RebuildFeedJob } from './jobs/RebuildFeedJob.ts';
import { NoteRepository } from './NoteRepository.ts';
import { RevisionRepository } from './RevisionRepository.ts';

export class NotePublishing {
  readonly #connections: Connections;
  readonly #notes: NoteRepository;
  readonly #revisions: RevisionRepository;
  readonly #events: EventDispatcher;
  readonly #queue: Queue;

  constructor(connections: Connections, notes: NoteRepository, revisions: RevisionRepository, events: EventDispatcher, queue: Queue) {
    this.#connections = connections;
    this.#notes = notes;
    this.#revisions = revisions;
    this.#events = events;
    this.#queue = queue;
  }

  publish(id: number) {
    return this.#connections.transaction(async () => {
      const note = await this.#notes.update(id, { published_at: new Date() });
      if (!note) return undefined;
      await this.#revisions.insert({ note_id: note.id, title: note.title, body: note.body });
      await this.#events.dispatch(new NotePublished(note)); // its listeners write into the transaction too
      await this.#queue.dispatch(RebuildFeedJob, { userId: note.user_id }); // on the database queue: a row in the transaction
      return note;
    });
  }
}
```

The transaction commits when the callback resolves, and `transaction()` resolves with the callback's result. When the callback
throws, the transaction rolls back and the error reaches the caller. When it returns an [`err`](errors.md#results), the
transaction rolls back too, and the caller gets the `err`: see [returning an err](#returning-an-err). A rollback takes back the
note, the revision, whatever the listeners wrote, and the queued job.

## Running a transaction

| Call | What it does |
| --- | --- |
| `connections.transaction(callback)` | A transaction on the default connection. |
| `connections.transaction(callback, { connection: 'reporting' })` | A transaction on another connection. |
| `connections.transaction(callback, { isolationLevel: 'serializable' })` | Sets the isolation level of an outermost transaction: `'read committed'`, `'repeatable read'` or `'serializable'`. |
| `repository.transaction(callback)` | A transaction on the repository's connection. The callback receives the repository. |
| `inTransaction()` | Whether the current code runs inside a transaction. Import it from `@marmeon/database`. |
| `connections.inTransaction(name?)` | Whether it runs inside a transaction of that connection. |

Postgres and MySQL apply an isolation level. SQLite has one writer at a time and ignores it. Any other value, `'snapshot'` or `'read uncommitted'` for one, is a type error and throws a `TypeError` before the transaction begins. A transaction exists exactly as long as its
callback runs. "Check, then insert" is not safe on Postgres at the default isolation level: two transactions can both pass the
check. A rule such as "no two bookings overlap" belongs in a constraint, as the [bookings recipe](recipe-bookings.md) shows, with
a row lock or `isolationLevel: 'serializable'` as the other ways; the latter makes Postgres abort one transaction, and running it
again is up to you. A row lock is `forUpdate()` and its siblings (`forShare()`, `skipLocked()`, `noWait()`): Postgres locks the rows, while SQLite runs the query without the clause, because a write transaction there begins holding the database's only write lock (a read-only one begins deferred and needs none). Write it once for both drivers; a raw end modifier, `` modifyEnd(sql`for update`) ``, is passed on as written. There is no transaction per request, and none that you begin without a callback joins by itself: those are
[transactions you control yourself](#transactions-you-control-yourself).

## What joins a transaction

| Inside `transaction()` | What happens |
| --- | --- |
| Repositories, `Database`, `connections.get()` of the same connection | They join the transaction. |
| `queue.dispatch()` on the `database` queue of the same connection | The job is a row in the transaction: there with the commit, gone with a rollback. |
| `queue.dispatch()` on `redis`, `sync` or another connection | Held until the outermost commit, dropped on a rollback. A `sync` job then runs outside the transaction. |
| The listeners of `events.dispatch()` | They run inside the transaction. |
| Queued listeners, `mailer.queue()`, `notifications.send()` | Jobs, queued like `queue.dispatch()`. |
| `notifications.sendNow()` | When `NOTIFICATIONS_CONNECTION` is the transaction's connection, its row is written inside it. On another connection the row is committed by a transaction of its own and survives a rollback. Its mail is queued like `mailer.queue()` either way. |
| `broadcast.refresh()` | Sent once the outermost transaction committed. A rollback sends nothing. |
| The database cache with its rate limits and locks, the database sessions, uploads | **Never join.** On Postgres, and on SQLite with a file of their own, they write on [a connection of their own](database.md#infrastructure-connections), and their writes survive a rollback. With the app's own SQLite file, and in a test's refreshed database, they throw `InfrastructureTransactionError` inside a transaction. |
| `mailer.send()`, a file written to a disk, a call to another service | Happen at once and are not undone. Use [`afterCommit()`](#after-the-commit). |

The [queues](queues.md#inside-a-transaction) page explains the queue's side, and the [events](events.md#queued-listeners) page
queued listeners.

### Where the transaction ends

The transaction follows the call chain of its callback, and nothing else. It never reaches another request, job or test that runs
at the same time. The framework also cuts it at its own boundaries, so work that runs later never joins a transaction that
happened to be open when it was registered:

- work after the response: `afterResponse.defer()` and the `terminate` of a middleware;
- every job, whether a worker runs it, the `sync` connection or a test;
- scheduled tasks.

## Nested transactions

A `transaction()` inside another one becomes a **savepoint**. That holds for your own nested calls, a repository's `tryInsert()`,
and Kysely's own `db.transaction()`. A savepoint that rolls back takes back its own writes and keeps those before it. When the
outer transaction rolls back, everything is undone, the committed savepoints too:

```ts
await this.#connections.transaction(async () => {
  await this.#notes.insert(row);
  try {
    await this.#connections.transaction(async () => {
      await this.#tags.attach(noteId, tags);
      throw new TagLimitError();
    });
  } catch {
    // the tags are gone, the note stays
  }
});
```

On Postgres, a statement that fails aborts the transaction it runs in. Catch the error outside the nested `transaction()`, never
inside it; a transaction whose error was caught inside it rolls back and throws `TransactionError` (D24), and the transaction around
a savepoint can go on. Use `tryInsert()` where a taken value is expected. A savepoint you roll back yourself has to be a statement
of its own that starts with `rollback to`: a recovery behind a comment or after another statement in the same query is not
recognized, and the commit still throws D24.

A statement you started inside `transaction()` and did not await can also fail after the callback has returned. When the failure
reaches Postgres before the commit does, Postgres aborts the transaction, so nothing in it is committed, and `transaction()` throws `TransactionError` (D24) instead of reporting a commit.
Its `cause` is the database's answer to the commit, or to the release of the savepoint; the failed statement's own error reaches only
the promise of that statement. In a nested `transaction()`, and in every `transaction()` of a test with `database: 'refresh'` (these
run as savepoints), only that savepoint is undone: Marmeon rolls it back, and the transaction around it stays open and can go on.
[Await every statement](#await-everything) before the callback returns.

A `db.transaction()` or `db.startTransaction()` that you open inside `transaction()` and never close leaves a level open. The usual cause:
Kysely does not roll back a `db.transaction()` whose callback throws an `AbortedTransactionError`, even when you catch the error outside
the callback. Wrap that error before it leaves the callback, for example `new Error(message, { cause })`, or open nested transactions with
`connections.transaction()`, which does it for you. The `transaction()` around the open level is rolled back instead of committed, and
throws `TransactionError` (D24); its after-commit work does not run. In a nested `transaction()` that undoes the nested one, and the
transaction around it can go on.

Open nested transactions one after the other. Several at once, such as `transaction()` calls in a `Promise.all`, would share one
connection, so the second one throws:

```text
Two transactions were opened at the same time inside one transaction on "default" (Promise.all over transaction() calls?) — they would share one connection and interleave their savepoints. Run them one after the other.
```

A savepoint has no isolation level of its own, so `isolationLevel` on a nested `transaction()` throws as well.

## On MySQL

MySQL cannot be selected yet (see [MySQL](database.md#mysql)); this is how a transaction behaves on it. The server ends a transaction on its
own in several cases, and Marmeon turns every case it can see into an error, so that no statement runs outside a transaction by accident:

- **A deadlock rolls the whole transaction back**, not the statement. After the error, MySQL runs the next statement of your callback
  outside any transaction, so it would commit on its own. Marmeon notes the error, sends none of the following statements, and fails each
  of them, and the commit, with `TransactionError` (D24). Let the error leave the callback to roll back, and run the transaction again.
  A savepoint you roll back is passed over without being sent, since the rollback of the outermost transaction still goes out and ends it.
- **A lock wait timeout** (error 1205) and **a full lock table** (error 1206) are treated the same way. MySQL may keep the transaction
  (`innodb_rollback_on_timeout` decides), and Marmeon cannot tell which it did, so it ends the transaction (D24): the rollback undoes
  what is left.
- **A schema change commits the transaction**, silently. The builder's (`schema.createTable()`, `alterTable()`, `dropTable()`,
  `createIndex()`, `dropIndex()`, views and schemas) is refused inside `transaction()` and `isolate()` before it is sent, with `TransactionError`
  (D30); a temporary table is allowed, MySQL does not commit for it. If the error leaves the callback, an earlier insert is rolled back
  with the rest. Make the change outside the transaction. A schema change written as raw SQL inside a transaction runs, commits what came before it,
  and ends the transaction for what follows: the statements after it and the commit throw D24.
- **A statement that commits or rolls back by itself** does the same: `lock tables`, a `commit`, `begin`, `start transaction` or `rollback` of
  your own, also with `and chain`, `work` or `release`. Marmeon reads this from the server's answer and, for these three, from the statement
  (a version comment such as `/*!80000 begin */` is read as the server reads it: it runs on a server of that version or newer, and is skipped on an older one).
  What an answer does not say (the rows of `analyze table`, a failed `create table`) is asked about before the next statement, with a statement
  that does nothing (`do 0`); a plain `select`, `show` or `explain` leaves nothing to ask. `set autocommit = 1` does not end a transaction and is
  not refused.
- **A statement that fails keeps the transaction.** A duplicate key rolls back that statement only, and a savepoint around it, such as a nested
  `transaction()`, keeps the outer transaction, as on SQLite. Postgres is the one that aborts it.
- **Isolation level and access mode** are those of MySQL: `isolationLevel` sets the level of the next transaction (`'snapshot'` is a type error, as
  elsewhere), and `db.transaction().setAccessMode('read only')` refuses a write with the server's error.
- **A session that changes how a transaction ends is refused (D28).** Every connection is set to `completion_type = NO_CHAIN` and to report
  changes of `autocommit`, `completion_type` and the character sets. When a statement of yours turns `autocommit` off, or sets `completion_type`
  to anything but `NO_CHAIN`, the next statement is refused before it is sent, a commit included (nothing is committed), and the connection is
  discarded. Should a commit or rollback of Marmeon still answer with a transaction left open, the error says that the commit or rollback ran.

> [!WARNING]
> Two cases stay unseen: a stored procedure that commits and starts a new transaction itself, and a `prepare s from 'commit and chain'`
> followed by `execute s`. Marmeon sees a transaction as open there, and the statements after it run in the transaction the server began. What
> ran before the commit stays committed, and a rollback of yours does not undo it. Keep `commit` and `begin` out of procedures that you call
> inside `transaction()`.
>
> A lease that sets `session_track_system_variables = ''` itself blinds the watch over `autocommit` and `completion_type` for the rest of the
> lease; then only the check after the commit is left.

## Returning an err

An expected failure is a [`Result`](errors.md#results), and a callback that returns an `err` rolls its transaction back, as if
it had thrown. `transaction()` returns the `err` unchanged instead of throwing it. A savepoint that returns one takes back its own
writes only, and after-commit work is dropped while [after-rollback work](#after-a-rollback) runs, just as after an exception.

Some errors are a change of their own that must stay: a request that is dropped, or a failed attempt that is counted. Return
those as `commitAnyway(err(…))`, and the transaction commits:

```ts title="modules/teams/Invitations.ts"
import { commitAnyway, err, ok, type Result } from '@marmeon/core';
import { Connections } from '@marmeon/database';
import { InvitationRepository } from './InvitationRepository.ts';
import { MemberRepository } from './MemberRepository.ts';
import type { Member } from './members.ts';

export type AcceptError = { kind: 'expired' } | { kind: 'already-member'; teamId: number };

export class Invitations {
  readonly #connections: Connections;
  readonly #invitations: InvitationRepository;
  readonly #members: MemberRepository;

  constructor(connections: Connections, invitations: InvitationRepository, members: MemberRepository) {
    this.#connections = connections;
    this.#invitations = invitations;
    this.#members = members;
  }

  accept(invitationId: number, userId: number): Promise<Result<Member, AcceptError>> {
    return this.#connections.transaction(async () => {
      const invitation = await this.#invitations.claim(invitationId, new Date());
      if (!invitation) return err({ kind: 'expired' }); // rolls back: nothing to keep
      await this.#invitations.delete(invitation.id);
      if (await this.#members.isMember(invitation.team_id, userId)) {
        // The invitation is used up all the same: the delete commits, and the caller gets a plain err.
        return commitAnyway(err({ kind: 'already-member', teamId: invitation.team_id }));
      }
      return ok(await this.#members.insert({ team_id: invitation.team_id, user_id: userId }));
    });
  }
}
```

`commitAnyway()` takes an `err` only, and it marks that one return of that one callback. The caller gets a plain `err`; if it
returns that `err` from a transaction of its own, that transaction rolls back. Inside another transaction, `accept()` runs as a
savepoint, so that rollback takes back the deleted invitation as well. To keep it, mark the `err` again where you pass it on:

```ts
return this.#connections.transaction(async () => {
  const accepted = await this.#invitations.accept(invitationId, userId);
  if (!accepted.ok) return commitAnyway(accepted); // the invitation stays used up
  await this.#activity.insert({ team_id: accepted.value.team_id, user_id: userId, action: 'joined' });
  return accepted;
});
```

That commits the writes of the outer callback too. A write that must stay whatever its callers do, such as a failed-attempt
counter, belongs in [`outsideTransaction()`](#outside-the-transaction) instead.

A rollback looks for the results that `err()` made. An object that only looks like one, such as a JSON payload with `ok: false`
or a copy made with `{ ...result }`, commits like any other value.

`connections.transaction()` and a repository's `transaction()` both roll back on an `err`, whether they run as a savepoint or
over a transaction bound with `using(trx)`. Kysely's own `db.transaction().execute()` knows no results and commits whatever its
callback returns.

## Refusing a save made from an old state

Two people open the same record, and the second to save would overwrite what the first saved. A **version counter** refuses
that: the record has a number that every save raises, the form sends the number it was opened with, and a save that arrives with
an older one is refused.

```ts title="modules/documents/migrations/2026_10_08_090000_create_documents_table.ts"
import { defineMigration } from '@marmeon/database';

export default defineMigration({
  up: (schema) =>
    schema.create('documents', (table) => {
      table.id();
      table.string('title');
      table.integer('version').default(1);
      table.timestamps();
    }),
  down: (schema) => schema.drop('documents'),
});
```

The check and the write have to be one step. A save that reads the version, compares it in code and writes afterwards lets two
requests both pass. So the save starts with an `update … where version = ?` that raises the counter. The statement locks the row,
a second save waits for the first to commit, then finds the version changed and updates nothing. Everything else the save writes
comes after it in the same transaction, under that lock. A refused save is an expected failure, so it is an `err`, not a throw:

```ts title="modules/documents/DocumentRepository.ts"
import { err, ok, type Result } from '@marmeon/core';
import { Repository, type Row } from '@marmeon/database';

export type SaveError = { kind: 'missing' } | { kind: 'stale' };

export class DocumentRepository extends Repository<'documents'> {
  static table = 'documents' as const;

  /** Saves the title when the document still has the version the form was opened with. */
  save(id: Row<'documents'>['id'], version: number, values: { title: string }): Promise<Result<Row<'documents'>, SaveError>> {
    return this.transaction(async () => {
      const claimed = await this.db.updateTable('documents').set({ version: version + 1 }).where('id', '=', id).where('version', '=', version).executeTakeFirst();
      if (Number(claimed.numUpdatedRows) === 0) return (await this.find(id)) ? err({ kind: 'stale' }) : err({ kind: 'missing' });
      // Other rows of the same save are written here too, under the lock the update took.
      const saved = await this.update(id, values);
      return saved ? ok(saved) : err({ kind: 'missing' });
    });
  }
}
```

This works the same on Postgres and SQLite, and it needs no `select … for update` first. Postgres takes the row lock with the update,
and SQLite takes the write lock when a transaction begins.

Answer a refused save with **422, or with a redirect back that carries the error. Never with 409**: `409` is the code the page protocol uses for its own full loads
([a new version of the app](navigation.md#a-new-version-of-the-app)), and it reaches a form as no error at all. A
`ValidationError` keeps the form and shows the message: a page request goes back to the form with the errors and the input it was
given, and a JSON client gets the 422:

```ts title="modules/documents/controllers/UpdateDocumentController.ts"
import { can } from '@marmeon/auth';
import { abort, Controller, defineRequest, ValidationError, type ContextOf } from '@marmeon/http';
import { rules as r } from '@marmeon/validation';
import { DocumentRepository } from '../DocumentRepository.ts';
import { DocumentPolicy } from '../policies/DocumentPolicy.ts';

export const UpdateDocumentRequest = defineRequest({
  schema: r.object({
    title: r.string().trim().required().max(120),
    version: r.integer().min(1),
  }),
  authorize: can(DocumentPolicy, 'update', 'document'),
});

/** Saves the changes to a document, unless someone saved it after the form was opened. */
export class UpdateDocumentController extends Controller {
  static request = UpdateDocumentRequest;

  readonly #documents: DocumentRepository;

  constructor(documents: DocumentRepository) {
    super();
    this.#documents = documents;
  }

  async handle(ctx: ContextOf<typeof UpdateDocumentRequest>) {
    const saved = await this.#documents.save(ctx.params.document.id, ctx.body.version, { title: ctx.body.title });
    if (saved.ok) return this.redirect().route('documents.show', { document: saved.value.id }).flash('toast', { kind: 'success', message: 'Document saved.' });
    if (saved.error.kind === 'stale') throw new ValidationError({ version: ['Someone saved this document after you opened it. Reload it and make your change again.'] }, { title: ctx.body.title });
    abort(404);
  }
}
```

The route binds the record with `bind('document', DocumentRepository)`, and `DocumentPolicy` is written as in the
[resource recipe](recipe-resource.md#the-code); the version is no substitute for the policy. The page sends `version` from the record it
was rendered with, as a hidden field of the form. That field shows no message by itself, so the page renders `errors.version` near the
submit button (or the controller answers with a redirect and a flash message instead). A person who gets the error reloads the record, which has the new version, and makes the change again.

## Await everything

Work that started inside the callback but runs after the transaction finished, such as a promise you did not await or a timer,
throws instead of writing outside the transaction:

```text
This work was started inside transaction() on "default" but ran after that transaction was committed — await it inside the callback, or wrap it in outsideTransaction() if it should run on its own.
```

The error is a `TransactionFinishedError`.
It also covers a query that was already on its way when the transaction ended: it holds the transaction's connection but reaches it after the commit or rollback, so it is not sent.
The same holds for a nested `transaction()`: work that arrives after its savepoint ended throws a `TransactionFinishedError` and does not run in the transaction around it.
Such work never runs on the bare connection by accident.
This guarantee covers work started inside the callback, in its call chain. A `trx` that you use outside that call chain, and Kysely's own transactions, rely on Kysely's checks: an un-awaited statement on them can still run after the end, so await every one.

A statement that is still running when the callback returns is no exception: if it fails while the transaction is still open, the transaction is rolled back and throws D24, as described under [Nested transactions](#nested-transactions).

## After the commit

Some work must happen only for data that exists: a mail, a cache write, a call to another service. `afterCommit(fn)` runs `fn`
once the outermost transaction has committed, outside of any transaction, and never after a rollback:

```ts title="modules/notes/NoteSharing.ts"
import { afterCommit, Connections } from '@marmeon/database';
import { Mailer } from '@marmeon/mail';
import { NoteSharedMail } from './mail/NoteSharedMail.ts';
import { ShareRepository } from './ShareRepository.ts';

export class NoteSharing {
  readonly #connections: Connections;
  readonly #shares: ShareRepository;
  readonly #mailer: Mailer;

  constructor(connections: Connections, shares: ShareRepository, mailer: Mailer) {
    this.#connections = connections;
    this.#shares = shares;
    this.#mailer = mailer;
  }

  share(noteId: number, email: string, mail: NoteSharedMail) {
    return this.#connections.transaction(async () => {
      const share = await this.#shares.insert({ note_id: noteId, email });
      await afterCommit(() => this.#mailer.send(mail));
      return share;
    });
  }
}
```

Outside a transaction, `afterCommit()` runs `fn` at once and resolves when it is done. Inside one, it resolves at once. Inside a
savepoint, `fn` is handed on to the transaction around it when the savepoint commits, and dropped when the savepoint rolls back.
When `fn` fails, the `transaction()` call that committed throws its error, or an `AggregateError` when several failed: the data is
committed by then. `fn` runs after the transaction has given up its connection, so it may open a transaction of its own, in a test with
`database: 'refresh'` too. A mail that can wait for a worker is simpler still: `mailer.queue()` inside the transaction is held for the
commit by itself.

## Outside the transaction

`outsideTransaction(fn)` of `@marmeon/database` runs `fn` outside the current transaction. Its writes are kept even when the
transaction rolls back, which is what a failed-attempt counter or a security log needs:

```ts
await this.#connections.transaction(async () => {
  if (!(await this.#codes.consume(user, code))) {
    await outsideTransaction(() => this.#attempts.recordFailure(user.id)); // kept although the transaction rolls back
    throw new InvalidCodeError();
  }
  await this.#users.update(user.id, { two_factor_confirmed_at: new Date() });
});
```

This needs a second physical connection, which Postgres has in its pool. On SQLite, and in a test's isolated database, there is
only one, and the open transaction holds it. There the database work inside `outsideTransaction()` fails at once with a
`TransactionError` instead of waiting forever. Record such things after the transaction instead: catch the error, record, and
throw it again.

The framework's rate limits, locks and sessions need none of this. On Postgres, and on SQLite with a file of their own, they
always write on their own connection. With the app's own SQLite file, and in a test's refreshed database, they cannot work inside
a transaction and throw `InfrastructureTransactionError`. The [database](database.md#infrastructure-connections) page shows how to
give them a file of their own.

## After a rollback

`afterRollback(fn)` is the counterpart of `afterCommit()`: it undoes work that was done *outside* the transaction on its behalf.
A lock taken on the cache's own connection is the usual case. It is visible to every process at once, and the job it guards is a
row in the transaction. The example needs a cache that works inside a transaction: any driver but `database` on the app's own
SQLite file:

```ts title="modules/notes/FeedRebuilds.ts"
import { Cache } from '@marmeon/cache';
import { afterRollback, Connections } from '@marmeon/database';
import { Queue } from '@marmeon/queue';
import { RebuildFeedJob } from './jobs/RebuildFeedJob.ts';

export class FeedRebuilds {
  readonly #connections: Connections;
  readonly #cache: Cache;
  readonly #queue: Queue;

  constructor(connections: Connections, cache: Cache, queue: Queue) {
    this.#connections = connections;
    this.#cache = cache;
    this.#queue = queue;
  }

  request(userId: number) {
    return this.#connections.transaction(async () => {
      const lock = this.#cache.lock(`feed:rebuild:${userId}`, 600);
      if (!(await lock.get())) return;
      await afterRollback(() => lock.release()); // the job below never existed: free the lock again
      await this.#queue.dispatch(RebuildFeedJob, { userId });
    });
  }
}
```

`fn` runs right after the rollback, outside of any transaction, and never after a commit. It belongs to the innermost transaction:
a savepoint that rolls back runs it at once, since what it cleans up after is gone, even if the transaction around it commits. A
savepoint that commits hands it on to the transaction around it. Outside a transaction it never runs.

When `fn` fails, the error that rolled the transaction back is not lost: `transaction()` throws a `SuppressedError` whose `error`
is the failure of `fn` and whose `suppressed` is the original error. After an `err` there is no error to keep, so
`transaction()` throws the failure of `fn` itself, or an `AggregateError` when several failed.

A [unique job](queues.md#unique-jobs) does exactly this for you, so the lock of a unique dispatch needs no `afterRollback()` of
your own.

## Transactions you control yourself

The callback of `connections.transaction()` also receives the transaction as a `Transaction`, for code outside the call
chain. Three helpers bind to a transaction explicitly:

- `repository.using(trx)` builds the repository again, working in `trx`. This is why a repository's constructor takes only
  `Connections`: with more parameters, `using()` throws and says so.
- `queue.using(trx).dispatch(…)` writes the job's row through `trx`. Nothing reports the commit of a transaction you began yourself, so `JobQueued` is not fired for it, and a `sync` or unique job through it throws a `QueueError`; dispatch those inside `connections.transaction()`.
- `factory(…).using(trx)` inserts a factory's rows through it.

They are for transactions the ambient context does not know: one you start with Kysely's `db.startTransaction()`, a second
connection at the same time, or code that runs outside the callback's call chain:

```ts
const trx = await this.#db.startTransaction().execute();
try {
  await this.#notes.using(trx).insert(row);
  await this.#queue.using(trx).dispatch(RebuildFeedJob, { userId: row.user_id });
  await trx.commit().execute();
} catch (error) {
  await trx.rollback().execute();
  throw error;
}
```

Such a transaction reports neither its commit nor its rollback, so the job above is a row that exists once `trx` commits, but
`JobQueued` is not fired for it, and a `sync` job or a unique job dispatched through it throws a `QueueError`.

`commit()` can throw: on Postgres it throws `TransactionError` (D24) when a statement inside the transaction failed.
Call `rollback()` in the `catch` (as above): it ends the transaction if it is still open, and hands the connection back to the pool.

A connection that is released while its transaction is still open is rolled back by Marmeon, with a `MarmeonDatabaseWarning` (code
`MARMEON_TRANSACTION_LEFT_OPEN`) that names the connection only, and the release throws `TransactionError` (D24). The operation that
released the connection rejects with D24 instead of its own error. Through `startTransaction()` Kysely swallows that rejection, so only the
warning appears. Both are a sign that some code left a transaction open.

Kysely's own `db.transaction().execute(callback)` is not ambient either. Outside `connections.transaction()` it is a plain
transaction, and inside its callback only `trx`, or a repository bound with `using(trx)`, is in it. A query on the plain `db`
there waits for the connection the transaction holds: on SQLite, which has one connection, it waits forever.

A statement you send on a `trx` you began yourself while `commit()` or `rollback()` is running waits behind that call, and Kysely answers it with its own error ("Transaction is already committed" or "…rolled back"): it is not sent. Kysely's checks do not stop a statement that was already queued, so await every statement before `commit()` or `rollback()`.
After a failed `commit()` the transaction is in a state nobody decided on, so `trx` refuses every statement with a `TransactionError` until you call `rollback()`. Call it in the `catch`, as the example above does.
This applies to a transaction that starts on its own connection. Inside a `transaction()` or a test's isolated connection, `startTransaction()` opens a savepoint: a statement after a failed `commit()` is sent in that savepoint, which is still open, and `rollback()` undoes it.

## Testing

With `createTestApp(application, { database: 'refresh' })`, every test runs inside one transaction that is rolled back when the
test ends. Your transactions become savepoints in it and work as they do in the app. Transactions that run at the same time take
turns on the test's one connection. Like the app's own SQLite file, that one connection makes the database cache, sessions and
uploads throw `InfrastructureTransactionError` inside a transaction, and `outsideTransaction()` throw a `TransactionError`. The
[database testing](database-testing.md#how-the-database-is-reset) page explains it.
