"""大周天运行记录数据访问。""" from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.models.big_cycle import BigCycle async def add_cycle(session: AsyncSession, cycle: BigCycle) -> BigCycle: session.add(cycle) await session.flush() return cycle async def get_cycle(session: AsyncSession, cycle_id: str) -> BigCycle | None: return await session.get(BigCycle, cycle_id) async def get_last_completed(session: AsyncSession, character_id: str) -> BigCycle | None: result = await session.execute( select(BigCycle) .where( BigCycle.character_id == character_id, BigCycle.completed_at.is_not(None), ) .order_by(BigCycle.completed_at.desc()) .limit(1) ) return result.scalar_one_or_none() async def list_cycles( session: AsyncSession, character_id: str, *, page: int = 1, page_size: int = 20, ) -> tuple[list[BigCycle], int]: conditions = [BigCycle.character_id == character_id] total = ( await session.execute(select(func.count()).select_from(BigCycle).where(*conditions)) ).scalar_one() items_result = await session.execute( select(BigCycle) .where(*conditions) .order_by(BigCycle.created_at.desc()) .offset(max(page - 1, 0) * page_size) .limit(page_size) ) return list(items_result.scalars().all()), int(total or 0)