"""Async database engine and session factory.""" from sqlalchemy.ext.asyncio import ( AsyncSession, async_sessionmaker, create_async_engine, ) from sqlalchemy.orm import DeclarativeBase from app.config import settings engine = create_async_engine( settings.DATABASE_URL, echo=settings.DEBUG, pool_size=10, max_overflow=20, ) async_session_factory = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, ) class Base(DeclarativeBase): pass async def get_db() -> AsyncSession: """Dependency that yields an async database session. Handlers are responsible for committing or rolling back their own transactions. This avoids the double-commit problem where the session is committed both here and in the handler. """ async with async_session_factory() as session: try: yield session except Exception: await session.rollback() raise