""" Gestion de la session SQLAlchemy async. """ from typing import AsyncGenerator from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.config import settings from infrastructure.database.models import Base # Engine async pour FastAPI async_engine = create_async_engine( settings.get_database_url(), echo=settings.debug, future=True, ) # Session factory async AsyncSessionLocal = async_sessionmaker( bind=async_engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False, ) # Engine sync pour certaines opérations (comme les tests de health) sync_engine = create_engine( settings.sync_database_url, echo=settings.debug, ) SyncSessionLocal = sessionmaker( bind=sync_engine, autocommit=False, autoflush=False, ) async def get_async_session() -> AsyncGenerator[AsyncSession, None]: """ Dependency pour obtenir une session async. Usage: @router.get("/items") async def get_items(session: AsyncSession = Depends(get_async_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_session(): """ Récupère une session synchrone (pour les opérations qui ne supportent pas async). """ session = SyncSessionLocal() try: yield session finally: session.close() async def init_db(): """ Initialise la base de données (crée les tables si elles n'existent pas). Note: En production, on utilise la DB existante de v1, donc cette fonction ne devrait pas être appelée. """ async with async_engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)