from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy import create_engine from sqlalchemy.orm import DeclarativeBase, sessionmaker from app.core.config import settings # Async engine for FastAPI engine = create_async_engine( settings.database_url, echo=settings.environment == "development", pool_size=10, max_overflow=20, ) AsyncSessionLocal = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, ) # Sync engine for Celery workers (Celery + asyncio don't mix well) # Convert async URL to sync: postgresql+asyncpg:// → postgresql+psycopg2:// sync_url = settings.database_url.replace("postgresql+asyncpg://", "postgresql+psycopg2://") sync_engine = create_engine( sync_url, echo=False, pool_size=5, max_overflow=10, pool_pre_ping=True, ) SyncSessionLocal = sessionmaker(sync_engine, expire_on_commit=False) class Base(DeclarativeBase): pass async def get_db(): async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close()