# execute, fetch\_all and fetch\_one

Escape hatches for SQL the query builder does not cover. All three functions take an SQL string and positional bind parameters (placeholders are `?` on SQLite and `$1`, `$2`, ... on Postgres) and honor an active `transaction()` block. See the [Raw SQL guide](<https://ferro-orm.x54.sh/guide/raw-sql/index.md>).

## execute

```python
execute(sql: str, *args: Any, using: str | None = None, session: Any | None = None, autocommit: bool = False) -> int
```

Run one SQL statement and return the number of rows it changed.

It runs inside the enclosing `transaction()` block, if any. Outside one, two calls may run on different pooled connections; wrap statements that need one connection (`SET LOCAL`, an advisory lock) in `transaction()`. See [Raw SQL](<https://ferro-orm.x54.sh/guide/raw-sql/index.md>).

> [!WARNING]
>
> **`autocommit=True` drops the session's settings**
>
> Under the default settings delivery, an `autocommit` statement carries none of the session's settings, so a row-security policy sees no tenant while it runs. Use it for maintenance statements, never for statements that read or write rows a policy protects.

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: `str`, `int`, `float`, `bool`, `bytes`, `None`, `UUID`, `datetime`, `date`, `time`, `Decimal`, an `Enum` member, or a `dict` or `list` sent as JSON text. | `()` |
| `using` | `str \| None` | The connection to run on, outside a session. Defaults to `None`, the current session's connection. | `None` |
| `session` | `Any \| None` | The session to run in. Defaults to `None`, the one opened by the enclosing `async with engines.session():`. | `None` |
| `autocommit` | `bool` | Run the statement outside the transaction Ferro opens for each operation in a session with settings, for the Postgres statements that refuse one (`CREATE INDEX CONCURRENTLY`, `VACUUM`). Defaults to `False`. Inside an explicit `transaction()` block it changes nothing. See [Statements that refuse a transaction](<https://ferro-orm.x54.sh/guide/raw-sql/#statements-that-refuse-a-transaction>). | `False` |

Returns:

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

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | `sql` is empty, or `using` names another connection than the session's or the transaction's. |
| `TypeError` | A value in `args` has a type that cannot be bound. |
| `RuntimeError` | No session is open and neither `using` nor `session` was given. |

Examples:

```python
from ferro import execute

changed = await execute('UPDATE "post" SET "views" = "views" + 1 WHERE "published" = ?', True)
assert changed == 2
```

## fetch\_all

```python
fetch_all(sql: str, *args: Any, using: str | None = None, session: Any | None = None) -> list[dict[str, Any]]
```

Run one SQL query and return every row as a dict.

It runs inside the enclosing `transaction()` block, if any. Values come back as plain primitives: UUID, datetime and JSON columns as strings.

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: `str`, `int`, `float`, `bool`, `bytes`, `None`, `UUID`, `datetime`, `date`, `time`, `Decimal`, an `Enum` member, or a `dict` or `list` sent as JSON text. | `()` |
| `using` | `str \| None` | The connection to run on, outside a session. Defaults to `None`, the current session's connection. | `None` |
| `session` | `Any \| None` | The session to run in. Defaults to `None`, the one opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `list[dict[str, Any]]` | One dict per row, keyed by column name, in the query's order. |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | `sql` is empty, or `using` names another connection than the session's or the transaction's. |
| `TypeError` | A value in `args` has a type that cannot be bound. |
| `RuntimeError` | No session is open and neither `using` nor `session` was given. |

Examples:

```python
from ferro import fetch_all

rows = await fetch_all('SELECT "title", "views" FROM "post" WHERE "views" > ? ORDER BY "views"', 900)
assert rows == [
    {"title": "The Education of a Computer", "views": 952},
    {"title": "Notes on the Analytical Engine", "views": 1843},
]
```

## fetch\_one

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

Run one SQL query and return its first row as a dict, or `None`.

It runs inside the enclosing `transaction()` block, if any. Ferro does not add `LIMIT 1`; write it when more than one row can match, so the database stops at the first.

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: `str`, `int`, `float`, `bool`, `bytes`, `None`, `UUID`, `datetime`, `date`, `time`, `Decimal`, an `Enum` member, or a `dict` or `list` sent as JSON text. | `()` |
| `using` | `str \| None` | The connection to run on, outside a session. Defaults to `None`, the current session's connection. | `None` |
| `session` | `Any \| None` | The session to run in. Defaults to `None`, the one opened by the enclosing `async with engines.session():`. | `None` |

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, or `using` names another connection than the session's or the transaction's. |
| `TypeError` | A value in `args` has a type that cannot be bound. |
| `RuntimeError` | No session is open and neither `using` nor `session` was given. |

Examples:

```python
from ferro import fetch_one

row = await fetch_one('SELECT "name" FROM "author" WHERE "email" = ?', "ada@example.com")
assert row == {"name": "Ada Lovelace"}
assert await fetch_one('SELECT "name" FROM "author" WHERE "id" = ?', 99) is None
```
