""" Database Configuration and Session Management """ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy.orm import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from app.core.config import settings # Async engine for FastAPI async_engine = create_async_engine( settings.DATABASE_URL, echo=settings.DEBUG, pool_pre_ping=True, pool_size=10, max_overflow=20, ) # Async session factory AsyncSessionLocal = async_sessionmaker( async_engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False, ) # Sync engine for Celery workers sync_engine = create_engine( settings.DATABASE_URL_SYNC, echo=settings.DEBUG, pool_pre_ping=True, pool_size=5, max_overflow=10, ) # Sync session factory SyncSessionLocal = sessionmaker( sync_engine, autocommit=False, autoflush=False, ) # Base class for models Base = declarative_base() async def init_db(): """Initialize database (create tables if needed).""" # Tables are created by init.sql, but we can add migrations here pass async def get_db() -> AsyncSession: """Dependency for getting async database session.""" async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close() def get_sync_db(): """Get sync database session for Celery workers.""" db = SyncSessionLocal() try: yield db db.commit() except Exception: db.rollback() raise finally: db.close()