2026-11-10 21:36:09 +08:00
|
|
|
|
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
|
|
|
|
|
from sqlalchemy import event
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
from contextlib import asynccontextmanager
|
2026-11-14 14:07:26 +08:00
|
|
|
|
from app.models import Base
|
2026-11-10 21:36:09 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Database:
|
|
|
|
|
|
def __init__(self, settings):
|
2026-11-10 23:56:50 +08:00
|
|
|
|
self.mode = settings.mode
|
2026-11-10 21:36:09 +08:00
|
|
|
|
self.engine = create_async_engine(settings.sqlalchemy_url, pool_pre_ping=True)
|
|
|
|
|
|
if settings.sqlalchemy_url.drivername.startswith("sqlite"):
|
2026-11-14 14:07:26 +08:00
|
|
|
|
|
2026-11-10 21:36:09 +08:00
|
|
|
|
@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()
|
2026-11-14 14:07:26 +08:00
|
|
|
|
|
2026-11-10 21:36:09 +08:00
|
|
|
|
self._sessions = async_sessionmaker(self.engine, expire_on_commit=False)
|
2026-11-14 14:07:26 +08:00
|
|
|
|
# 单 API 进程内串行提交短事务,确保 SSE 游标顺序与提交顺序一致;GPU 并行不等于增加 API workers。
|
2026-11-10 21:36:09 +08:00
|
|
|
|
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:
|
2026-11-10 23:56:50 +08:00
|
|
|
|
if self.mode in {"test", "preview"}:
|
|
|
|
|
|
await connection.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
else:
|
2026-11-14 14:07:26 +08:00
|
|
|
|
from app.core.schema import check_schema_revision
|
|
|
|
|
|
|
|
|
|
|
|
await connection.run_sync(check_schema_revision, {"007"})
|
2026-11-10 21:36:09 +08:00
|
|
|
|
|
|
|
|
|
|
async def close(self):
|
|
|
|
|
|
await self.engine.dispose()
|