from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy import event import asyncio from contextlib import asynccontextmanager from app.models import Base class Database: def __init__(self, settings): self.mode = settings.mode self.engine = create_async_engine(settings.sqlalchemy_url, pool_pre_ping=True) if settings.sqlalchemy_url.drivername.startswith("sqlite"): @event.listens_for(self.engine.sync_engine, "connect") def sqlite_options(connection, _): cursor = connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.execute("PRAGMA busy_timeout=10000") cursor.close() self._sessions = async_sessionmaker(self.engine, expire_on_commit=False) # 单 API 进程内串行提交短事务,确保 SSE 游标顺序与提交顺序一致;GPU 并行不等于增加 API workers。 self._unit_lock = asyncio.Lock() @asynccontextmanager async def session(self): async with self._unit_lock: async with self._sessions() as session: yield session async def initialize(self): async with self.engine.begin() as connection: if self.mode in {"test", "preview"}: await connection.run_sync(Base.metadata.create_all) else: from app.core.schema import check_schema_revision, SUPPORTED_SCHEMA_REVISIONS await connection.run_sync(check_schema_revision, SUPPORTED_SCHEMA_REVISIONS) async def close(self): await self.engine.dispose()