"""SQLAlchemy async database session and base.""" from __future__ import annotations from typing import AsyncGenerator from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase from app.config import settings from app.utils.logger import logger class Base(DeclarativeBase): pass engine = create_async_engine(settings.database_url, echo=False, future=True) AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) async def get_db() -> AsyncGenerator[AsyncSession, None]: async with AsyncSessionLocal() as session: try: yield session except Exception: await session.rollback() raise else: try: await session.commit() except Exception as e: logger.warning(f"DB commit failed (non-fatal): {e}") async def init_db() -> None: """Create all tables. In production use Alembic migrations instead.""" from app.models import db_models # noqa: F401 - register models async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)