Files
Profeto/src/db/unit_of_work.py
T
shangfangjian ff0045ad93 fix: 数据库与数据管线 6 个 P1 + 5 个 P2 审查问题修复
P1-1 [context_builder] build_context 共享 session,切片函数传 db 参数,
        回测 20 场并发连接需求从 100+ 降至每场 1 个
P1-2 [bzzoiro] 预加载改为按 raw_events 日期范围 ±30 天按需加载
P1-3 [understat] 批量查询球队 + 比赛,从 1140 次往返降到 3 次
P1-4 [injuries] 批量幂等检查 + 分批 flush,IntegrityError 逐条回退
P1-5 [predict] 删除 threading.Lock,dict 操作原子无需同步锁
P1-6 [models] 添加 (match_id, provider, model) 唯一约束 + 迁移

P2-1 [unit_of_work] get_uow 返回类型改为 AsyncIterator[AsyncSession]
P2-2 [normalize] _parse_date 失败时记录 warning 避免静默丢数据
P2-3 [repositories] find_by_teams_and_date 改用 match_date_date 等值匹配
P2-4 [migration] 幽灵列 cutoff_at 已在 0006 迁移删除(已有)
P2-5 [migration] injuries 约束命名对齐 ORM,UniqueConstraint → 唯一索引
2026-09-16 03:09:39 +08:00

38 lines
952 B
Python

"""工作单元(Unit of Work):统一事务边界。
使用方式:
async with get_uow() as uow:
await uow.session.get(Match, 1)
await uow.commit()
"""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING
from src.db.base import AsyncSessionLocal
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
@asynccontextmanager
async def get_uow() -> AsyncIterator[AsyncSession]:
"""创建新的工作单元(用于非路由上下文)。
用法:
async with get_uow() as session:
await session.get(...)
# 退出时自动 commit(无异常) 或 rollback(有异常)
"""
session = AsyncSessionLocal()
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()