# transaction and Transaction

`transaction()` is an async context manager that runs everything inside the block on one connection, committing on exit and rolling back on exception. It yields a `Transaction` handle for raw SQL that must run on the transaction's connection. Route it with `using=`, an explicit `session=`, or the ambient session (`ferro.engines.session(...)`). See the [Transactions guide](<https://ferro-orm.x54.sh/guide/transactions/index.md>) for semantics and patterns.

## transaction

```python
transaction(using: str | None = None, *, session: Session | None = None, immediate: bool = False)
```

Run the operations in the block in one database transaction.

The transaction commits when the block exits and rolls back when it raises. A `transaction()` inside another one opens a savepoint. The yielded `Transaction` handle runs raw SQL on the transaction's connection, for statements no model covers, such as setting a Postgres setting or taking an advisory lock. See [Transactions](<https://ferro-orm.x54.sh/guide/transactions/index.md>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `using` | `str \| None` | The named connection to open the transaction on. Defaults to `None`, the session's connection. | `None` |
| `session` | `Session \| None` | The session to open the transaction in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |
| `immediate` | `bool` | On SQLite, open with `BEGIN IMMEDIATE`, which takes the write lock at once, so a transaction that reads and then writes never fails with `SQLITE_BUSY` while upgrading its lock. Postgres and nested transactions ignore it. Defaults to `False`. | `False` |

Yields:

| Name | Type | Description |
| --- | --- | --- |
| `tx` | `Transaction` | A handle with `execute`, `fetch_all` and `fetch_one` for raw SQL on the transaction's connection. |

Raises:

| Type | Description |
| --- | --- |
| `RuntimeError` | No session, `using=` or transaction gives the call a database route. |

Examples:

A failure inside the block rolls back every write in it:

```python
from ferro import transaction

try:
    async with transaction():
        await Author.create(name="Mary Somerville", email="mary@example.com")
        raise RuntimeError("abandon the import")
except RuntimeError:
    pass

assert await Author.where(lambda author: author.name == "Mary Somerville").count() == 0
```

The handle runs raw SQL in the same transaction:

```python
from ferro import transaction

async with transaction() as tx:
    await Author.create(name="Mary Somerville", email="mary@example.com")
    row = await tx.fetch_one("SELECT count(*) AS total FROM author")

assert row == {"total": 3}
```

## Transaction

```python
Transaction(route: RouteHandle)
```

The handle `async with transaction() as tx` yields, for raw SQL on its connection.

Its methods take the same `sql` and `*args` as the top-level `execute`, `fetch_all` and `fetch_one`, and always run on the transaction's connection. After the block exits, every call raises `RuntimeError`.

Examples:

```python
from ferro import transaction

async with transaction() as tx:
    await tx.execute('UPDATE "post" SET "views" = 0 WHERE "id" = ?', 1)
    row = await tx.fetch_one('SELECT "views" FROM "post" WHERE "id" = ?', 1)
assert row == {"views": 0}
```

Methods:

| Name | Description |
| --- | --- |
| `execute` | Run one SQL statement on this transaction's connection. |
| `fetch_all` | Run one SQL query on this transaction's connection and return every row. |
| `fetch_one` | Run one SQL query on this transaction's connection and return its first row. |

### execute

```python
execute(sql: str, *args: Any) -> int
```

Run one SQL statement on this transaction's connection.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `sql` | `str` | One SQL statement, with `?` placeholders on SQLite and `$1`, `$2`, ... on Postgres. | *required* |
| `*args` | `Any` | The values bound to the placeholders, in order. | `()` |

Returns:

| Type | Description |
| --- | --- |
| `int` | The number of rows the statement changed. |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | `sql` is empty. |
| `TypeError` | A value in `args` has a type that cannot be bound. |
| `RuntimeError` | The transaction's block has exited. |

### fetch\_all

```python
fetch_all(sql: str, *args: Any) -> list[dict[str, Any]]
```

Run one SQL query on this transaction's connection and return every row.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `sql` | `str` | One SQL query, with `?` placeholders on SQLite and `$1`, `$2`, ... on Postgres. | *required* |
| `*args` | `Any` | The values bound to the placeholders, in order. | `()` |

Returns:

| Type | Description |
| --- | --- |
| `list[dict[str, Any]]` | One dict per row, keyed by column name. |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | `sql` is empty. |
| `TypeError` | A value in `args` has a type that cannot be bound. |
| `RuntimeError` | The transaction's block has exited. |

### fetch\_one

```python
fetch_one(sql: str, *args: Any) -> dict[str, Any] | None
```

Run one SQL query on this transaction's connection and return its first row.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `sql` | `str` | One SQL query, with `?` placeholders on SQLite and `$1`, `$2`, ... on Postgres. | *required* |
| `*args` | `Any` | The values bound to the placeholders, in order. | `()` |

Returns:

| Type | Description |
| --- | --- |
| `dict[str, Any] \| None` | The first row, keyed by column name, or `None` when no row matched. |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | `sql` is empty. |
| `TypeError` | A value in `args` has a type that cannot be bound. |
| `RuntimeError` | The transaction's block has exited. |
