AsyncPG Connection Pool

Configure SQLSpec with the AsyncPG adapter and verify the server version. The DSN defaults to postgresql://postgres:postgres@localhost:5432/postgres and can be overridden via the SQLSPEC_ASYNCPG_DSN environment variable.

SQLSPEC_ASYNCPG_DSN=postgresql://user:pass@host/db \
  uv run python docs/examples/adapters/asyncpg/connect_pool.py

Source

 1"""AsyncPG connection pool configured through SQLSpec."""
 2
 3import asyncio
 4import os
 5
 6from sqlspec.adapters.asyncpg import AsyncpgConfig, AsyncpgPoolConfig
 7
 8__all__ = ("main",)
 9
10
11DSN = os.getenv("SQLSPEC_ASYNCPG_DSN", "postgresql://postgres:postgres@localhost:5432/postgres")
12config = AsyncpgConfig(bind_key="docs_asyncpg", pool_config=AsyncpgPoolConfig(dsn=DSN, min_size=1, max_size=5))
13
14
15async def main() -> None:
16    """Connect to Postgres and return the server version."""
17    async with config.provide_session() as session:
18        result = await session.execute("SELECT version() AS version")
19        row = result.one_or_none()
20        if row:
21            print({"adapter": "asyncpg", "version": row["version"]})
22        else:
23            print({"adapter": "asyncpg", "version": "unknown"})
24
25
26if __name__ == "__main__":
27    asyncio.run(main())