"""SQLAlchemy 2.0 async database engine and session factory.""" from collections.abc import AsyncGenerator from sqlalchemy.ext.asyncio import ( AsyncSession, async_sessionmaker, create_async_engine, ) from app.config import settings def _build_url(url: str) -> str: """Ensure the connection string uses the asyncpg driver.""" if url.startswith("postgresql://"): return url.replace("postgresql://", "postgresql+asyncpg://", 1) return url db_url = _build_url(settings.database_url) if db_url.startswith("postgresql"): engine = create_async_engine( db_url, echo=(settings.app_env == "development"), # NOTE: pool_size + max_overflow = up to 5 connections. Limiting this # prevents Supabase's transaction pooler (limit 15) from throwing errors. pool_size=5, max_overflow=5, pool_timeout=15, # fail fast on pool starvation instead of hanging pool_pre_ping=True, # validate connections before use (drops stale ones) pool_recycle=180, # recycle every 3 min to avoid stale pooler connections connect_args={ # Required for the Supabase/pgbouncer transaction pooler + asyncpg: # disables server-side prepared-statement caching. "prepared_statement_cache_size": 0, "statement_cache_size": 0, "command_timeout": 30, } ) else: engine = create_async_engine( db_url, echo=(settings.app_env == "development"), ) async_session_factory = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, ) async def get_db() -> AsyncGenerator[AsyncSession, None]: """FastAPI dependency that yields a database session.""" async with async_session_factory() as session: try: yield session finally: await session.close()