"""Database setup: async engine, session factory, declarative base.""" from collections.abc import AsyncGenerator from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase from app.core.config import get_settings settings = get_settings() engine = create_async_engine( settings.database_url, echo=settings.log_level.upper() == "DEBUG", pool_pre_ping=True, ) async_session_factory = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, autoflush=False, ) class Base(DeclarativeBase): """Declarative base for all ORM models.""" async def get_db() -> AsyncGenerator[AsyncSession, None]: """FastAPI dependency yielding an async DB session.""" async with async_session_factory() as session: try: yield session await session.commit() except Exception: await session.rollback() raise async def init_db() -> None: """Create all tables (scaffold mode; Alembic migrations come later).""" # Import models so they register on the metadata from app import models # noqa: F401 async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)