Source: https://gres.monicz.dev/guide/sqlalchemy/

# SQLAlchemy and Alembic

Gres ships an asyncio dialect for [SQLAlchemy 2.1+](https://docs.sqlalchemy.org/en/21/orm/extensions/asyncio.html) under the `postgresql+gres` URL scheme (`pip install 'gres[sqlalchemy]'`):

```python
import asyncio
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine


async def main() -> None:
    engine = create_async_engine('postgresql+gres://')
    try:
        async with engine.begin() as db:
            result = await db.execute(
                text(
                    "SELECT name FROM (VALUES (1, 'Harbour'), (2, 'Airport'))"
                    ' AS s(id, name) WHERE id = :id'
                ),
                {'id': 1},
            )
            print(result.scalar_one())  # Harbour
    finally:
        await engine.dispose()


asyncio.run(main())
```

SQLAlchemy owns connection pooling and transactions (`AsyncConnection.stream()` for streaming, `begin_nested()` for savepoints). Pass Gres options via `connect_args` (e.g. `pool_mode='transaction'` behind PgBouncer); transaction isolation, read-only, and deferrable options apply at `BEGIN` even across reassigned pooler backends.

## Migrations with Alembic

[Alembic](https://alembic.sqlalchemy.org/en/latest/cookbook.html#using-asyncio-with-alembic)'s async template (`alembic init -t async migrations`) works directly:

```ini
# Configuration: alembic.ini. Host, user, and password come from PG*
# environment variables.
sqlalchemy.url = postgresql+gres:///inventory?auto_prepare=false
```

`auto_prepare=false` forces fresh type inference on every statement after `ALTER TABLE`. Once migrations commit, call [`invalidate_types()`](https://gres.monicz.dev/guide/types/#refresh-type-metadata-after-a-migration) on running application pools or restart workers.

## Column types

SQLAlchemy types retain their standard Python values; the dialect adapts at the boundary where Gres's native type differs:

| SQLAlchemy type | Python value | Note |
| --- | --- | --- |
| `Interval`, `postgresql.INTERVAL` | `datetime.timedelta` | Months count as 30 days (matching other PostgreSQL dialects). Use a Gres connection directly for exact `gres.Interval`. |
| `Uuid`, `postgresql.UUID(as_uuid=False)` | `uuid.UUID` or `str` |  |
| `postgresql.HSTORE` | `dict[str, str \| None]` | Requires the `hstore` extension. |
| `postgresql.INT4RANGE` and other range types | `postgresql.Range` |  |
| `postgresql.INT4MULTIRANGE` and other multirange types | `postgresql.MultiRange` |  |
| `JSON`, `JSONB` | Decoded JSON | Honors `json_serializer` and `json_deserializer` on the engine. |
| [GeoAlchemy2](https://geoalchemy-2.readthedocs.io/) `Geometry`, `Geography` | `geoalchemy2.WKBElement` | Spatial functions and table reflection work as with other PostgreSQL dialects. |

URL query parameters accept libpq settings plus `auto_prepare`, `open_timeout`, `operation_timeout`, `cleanup_timeout`, and `max_value_bytes` (e.g. `postgresql+gres://db.example/app?operation_timeout=5`).

## Errors

Catch SQLAlchemy exceptions as usual; `error.orig` holds the underlying `gres.errors.Error` (e.g. `UniqueViolation` with `sqlstate` and `constraint_name` inside `sqlalchemy.exc.IntegrityError`). On a connection failure during commit, inspect `error.orig.transaction_outcome` before reconciling; see [Retry safety](https://gres.monicz.dev/guide/errors/#retry-safety).
