Skip to content

Quickstart

These examples read the libpq environment (PGHOST, PGDATABASE, PGUSER, plus PGPASSWORD or a password file when required) and need a role allowed to create temporary tables. Unix socket directories in PGHOST connect locally without TLS; TCP hosts default to sslmode='verify-full' (see TLS and authentication).

Pool sessions, transactions, and typed rows

Pool opens sessions on demand and lends one per operation; pool.connection() pins one session across several statements (needed here because temporary tables are session-local). transaction() commits on normal exit and rolls back on exception.

import asyncio
from dataclasses import dataclass
from gres import Pool, errors


@dataclass
class Account:
    id: int
    balance: int


async def main() -> None:
    async with Pool(max_size=4) as pool:
        async with pool.connection() as db:
            async with db.transaction() as tx:
                await tx.execute(
                    'CREATE TEMP TABLE account('
                    'id int PRIMARY KEY, balance int CHECK (balance >= 0))'
                )
                await tx.execute_many(
                    'INSERT INTO account VALUES ($1, $2)', [(1, 100), (2, 0)]
                )
            try:
                async with db.transaction() as tx:
                    await tx.execute(
                        'UPDATE account SET balance = balance - $1'
                        ' WHERE id = $2',
                        (150, 1),
                    )
            except errors.CheckViolation as error:
                print(error.constraint_name)  # account_balance_check
            accounts = await db.fetch_all(
                'SELECT id, balance FROM account ORDER BY id', row=Account
            )
    print(accounts)  # [Account(id=1, balance=100), Account(id=2, balance=0)]


asyncio.run(main())

Rows default to dict; pass row=tuple, row=scalar(T), or a dataclass / NamedTuple / TypedDict / callable to control the row shape. Ordinary queries run on the pool directly without checking out a connection, and execute_many runs atomically.

Import rows with COPY

copy_from_rows encodes Python records into PostgreSQL binary COPY:

import asyncio
from gres import Connection, scalar


async def main() -> None:
    async with Connection() as db:
        await db.execute('CREATE TEMP TABLE reading(sensor int, value float8)')
        await db.copy_from_rows(
            'reading',
            ((n % 8, n / 10) for n in range(10_000)),
            columns=['sensor', 'value'],
        )
        count = await db.fetch_one(
            'SELECT count(*) FROM reading', row=scalar(int)
        )
        print(count)  # 10000


asyncio.run(main())

Next steps