Source: https://gres.monicz.dev/migrating/

# Migrating from asyncpg or Psycopg

Gres uses PostgreSQL's native `$1` placeholders and libpq's connection settings, so most calls map directly from [asyncpg](https://magicstack.github.io/asyncpg/current/) or [Psycopg 3](https://www.psycopg.org/psycopg3/docs/).

## Behavior that differs

- **Opening is explicit.** `Connection(...)` and `Pool(...)` perform no I/O. Enter them with `async with`, or call `await db.open()` and later `await db.aclose()`.
- **Cardinality is checked.** `fetch_one` raises `CardinalityError` unless the statement returns exactly one row. `fetch_optional` returns `None` for no rows and raises for more than one. Neither silently drops extra rows.
- **Rows are dictionaries by default.** Pass `row=tuple`, `row=scalar()`, or a callable such as a dataclass to choose another shape.
- **An omitted `timeout` inherits `operation_timeout`; `None` disables the deadline.** A wrapper that forwards a timeout should default it to [`gres.INHERIT`](https://gres.monicz.dev/api/queries/#gres.INHERIT).
- **Statements are prepared automatically** and reused per session. Pass `prepare=False` to a call, or `auto_prepare=False` to the connection or pool, for fresh type inference.
- **Nothing is retried.** A failed statement is never replayed; see [Errors and retries](https://gres.monicz.dev/guide/errors/).

## Values that differ

Where Gres's default Python types differ from asyncpg or Psycopg 3:

| PostgreSQL type | Gres | Note |
| --- | --- | --- |
| `interval` | `gres.Interval` | Months, days, and microseconds stay separate. `to_timedelta()` converts when there are no months. A `timedelta` parameter is accepted. |
| `inet` | `ipaddress.IPv4Interface` or `IPv6Interface` | The prefix length is preserved, including `/32` and `/128`. |
| `uuid` | `uuid.UUID` | A UUID `str` or the 16 `bytes` of `UUID.bytes` also binds. |
| `numeric` | `decimal.Decimal` | `Decimal`, `int`, `float`, and `str` parameters bind; a `float` takes its shortest decimal form, matching PostgreSQL's own cast. |
| `json`, `jsonb` | Decoded Python value | Dictionaries, lists, and numbers bind directly without codec registration. A `str` is JSON text, so existing `json.dumps(...)` arguments keep working. `Json(None)` binds JSON `null` rather than SQL `NULL`. |
| range types | `gres.Range` | `lower`, `upper`, `bounds`, and `is_empty`. |

[Types and adapters](https://gres.monicz.dev/guide/types/) covers every type and the `Decoding` options that select other representations.

## From asyncpg

| asyncpg | Gres |
| --- | --- |
| `await asyncpg.connect(dsn)` | `async with Connection(dsn) as db` |
| `await asyncpg.create_pool(dsn, max_size=10)` | `async with Pool(dsn, max_size=10) as pool` |
| `async with pool.acquire() as conn` | `async with pool.connection() as db`, or call query methods on the pool |
| `conn.fetch(sql, a, b)` | `db.fetch_all(sql, (a, b))` |
| `conn.fetchrow(sql, a)` | `db.fetch_optional(sql, (a,))` |
| `conn.fetchval(sql, a)` | `db.fetch_one(sql, (a,), row=scalar())` |
| `conn.execute(sql, a)` returning a status string | `db.execute(sql, (a,))` returning `Command` with `tag` and `row_count` |
| `conn.executemany(sql, rows)` | `db.execute_many(sql, rows)` |
| `async with conn.transaction()` | `async with db.transaction() as tx` |
| `conn.cursor(sql)` | `async with db.stream(sql, fetch_size=...) as rows` |
| `await conn.prepare(sql)` | `async with db.prepare(sql) as query` |
| `conn.copy_records_to_table(table, records=rows)` | `db.copy_from_rows(table, rows, columns=[...])` |
| `conn.add_listener(channel, callback)` | `async with db.listen(channel) as events`, then `async for event in events` |
| `conn.set_type_codec(...)` | `adapters=[Codec(...)]` on the connection, pool or call |

## From Psycopg 3

| Psycopg 3 | Gres |
| --- | --- |
| `await AsyncConnection.connect(conninfo)` | `async with Connection(conninfo) as db` |
| `AsyncConnectionPool(conninfo, max_size=10)` | `Pool(conninfo, max_size=10)` |
| `%s` and `%(name)s` placeholders | `$1` and `$name` |
| `cur.execute(sql, params)` then `cur.fetchall()` | `db.fetch_all(sql, params)` |
| `cur.fetchone()` | `db.fetch_optional(sql, params)` |
| `row_factory=dict_row`, `class_row(T)` | The default, and `row=T` |
| `cur.executemany(sql, rows)` | `db.execute_many(sql, rows)`, which commits on its own outside a transaction |
| `conn.transaction()` | `db.transaction()`; a nested block is a savepoint, as in Psycopg |
| `cur.copy('COPY t FROM STDIN')` | `db.copy_in(...)`, or `copy_from_rows` and `copy_from_arrow` for typed input |
| `cur.stream(sql)` | `db.stream(sql)` |
| `conn.notifies()` | `db.listen(channel)` |
| `psycopg.sql.SQL`, `Identifier` | `gres.Query`, `gres.Identifier`; see [SQL composition](https://gres.monicz.dev/guide/composition/) |
| Autocommit off by default | Each statement outside `transaction()` commits on its own |

The [SQLAlchemy dialect](https://gres.monicz.dev/guide/sqlalchemy/) is the shorter route for an application that already goes through SQLAlchemy: change the URL scheme to `postgresql+gres`.
