Files
Profeto/src/db/base.py
T
shangfangjian 7d2eabf750 chore: 死代码与重复逻辑清理
删除未引用/未调用符号:
- PredictionRepository(无引用)
- is_correct_1x2(无调用者)
- LeagueOut(路由用 list[dict])
- IngestResponse(IngestBzzoiroResponse 已替代)
- SecurityCheckError(从未 raise,assert_security_on_startup 用 sys.exit)
- short_write(仅自引用,全仓库无外部调用)
- fetchIngestJobs(列表函数无页面使用,单数 fetchIngestJob 仍保留)
- clear_prompt_cache(无入口)

去重:
- eval._actual_1x2 改为委托 utils.actual_1x2(单一权威源)

全量测试 270 通过,业务行为不变。
2026-09-22 01:55:52 +08:00

86 lines
2.2 KiB
Python

"""SQLAlchemy async engine + session。"""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from src.core.config import settings
class Base(DeclarativeBase):
pass
engine = create_async_engine(
settings.DATABASE_URL,
echo=False,
pool_pre_ping=True,
pool_size=settings.DB_POOL_SIZE,
max_overflow=settings.DB_MAX_OVERFLOW,
pool_timeout=settings.DB_POOL_TIMEOUT,
pool_recycle=settings.DB_POOL_RECYCLE,
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def get_db() -> AsyncIterator[AsyncSession]:
"""写路由用: 退出时自动 commit。"""
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def get_db_read() -> AsyncIterator[AsyncSession]:
"""读路由用: 不 commit(只读)。"""
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
@asynccontextmanager
async def short_read():
"""短生命周期 read session: 用于非路由上下文(如后台任务、手动调用)。
用法:
async with short_read() as session:
m = await session.get(Match, match_id)
# session 已关闭,连接已释放
"""
async with AsyncSessionLocal() as session:
yield session
async def init_db() -> None:
"""验证数据库连接(不建表)。
生产环境 schema 由 Alembic 管理。
本地开发/测试需要建表时调用 `create_all()`。
"""
async with engine.begin() as conn:
# 只验证连接,不自动建表
await conn.run_sync(lambda conn: None)
async def create_all() -> None:
"""创建所有表(仅用于本地开发/测试)。"""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)