"""Database engine + session factory.""" from __future__ import annotations from contextlib import asynccontextmanager from typing import AsyncIterator from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase from app.config import settings class Base(DeclarativeBase): pass _engine_kwargs: dict = dict( echo=False, pool_pre_ping=True, ) # Pool size params only for Postgres/MySQL (not SQLite) if "sqlite" not in settings.database_url: _engine_kwargs.update(pool_size=10, max_overflow=20) engine = create_async_engine(settings.database_url, **_engine_kwargs) AsyncSessionLocal = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, autoflush=False ) @asynccontextmanager async def get_db() -> AsyncIterator[AsyncSession]: async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise async def get_db_dep() -> AsyncIterator[AsyncSession]: """FastAPI dependency.""" async with AsyncSessionLocal() as session: try: yield session finally: await session.close()