from sqlalchemy.ext.asyncio import ( create_async_engine, async_sessionmaker, AsyncSession, ) from sqlalchemy.orm import declarative_base from app.core.config import settings # ========================= # Async Engine # ========================= engine = create_async_engine( settings.database_url, # ⚠️ 必须是 async URL echo=settings.debug, pool_pre_ping=True, pool_recycle=1800, ) # ========================= # Async Session 工厂 # ========================= AsyncSessionLocal = async_sessionmaker( bind=engine, class_=AsyncSession, autoflush=False, expire_on_commit=False, ) # ORM 基类 Base = declarative_base() # ========================= # FastAPI 依赖 # ========================= async def get_db() -> AsyncSession: async with AsyncSessionLocal() as session: try: yield session except Exception: # --- 核心改进:全局兜底回滚 --- await session.rollback() raise finally: await session.close()