85 lines
2.8 KiB
Python
85 lines
2.8 KiB
Python
"""人格数据访问。"""
|
|
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.personality import PersonalityProposal, PersonalityVersion
|
|
|
|
|
|
async def get_personality(session: AsyncSession, personality_id: str) -> PersonalityVersion | None:
|
|
return await session.get(PersonalityVersion, personality_id)
|
|
|
|
|
|
async def get_latest_personality(
|
|
session: AsyncSession, character_id: str
|
|
) -> PersonalityVersion | None:
|
|
result = await session.execute(
|
|
select(PersonalityVersion)
|
|
.where(PersonalityVersion.character_id == character_id)
|
|
.order_by(PersonalityVersion.version.desc())
|
|
.limit(1)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
|
|
async def list_personality_versions(
|
|
session: AsyncSession,
|
|
character_id: str,
|
|
*,
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
) -> tuple[list[PersonalityVersion], int]:
|
|
"""按版本号倒序分页返回某人物的人格版本历史,返回 (条目, 总数)。"""
|
|
cond = PersonalityVersion.character_id == character_id
|
|
total = int(
|
|
(
|
|
await session.execute(select(func.count()).select_from(PersonalityVersion).where(cond))
|
|
).scalar_one()
|
|
)
|
|
result = await session.execute(
|
|
select(PersonalityVersion)
|
|
.where(cond)
|
|
.order_by(PersonalityVersion.version.desc())
|
|
.offset((page - 1) * page_size)
|
|
.limit(page_size)
|
|
)
|
|
return list(result.scalars().all()), total
|
|
|
|
|
|
async def add_proposal(session: AsyncSession, proposal: PersonalityProposal) -> PersonalityProposal:
|
|
session.add(proposal)
|
|
await session.flush()
|
|
return proposal
|
|
|
|
|
|
async def get_proposal(session: AsyncSession, proposal_id: str) -> PersonalityProposal | None:
|
|
return await session.get(PersonalityProposal, proposal_id)
|
|
|
|
|
|
async def list_proposals(
|
|
session: AsyncSession,
|
|
*,
|
|
character_id: str | None = None,
|
|
status: str | None = None,
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
) -> tuple[list[PersonalityProposal], int]:
|
|
"""按创建时间倒序分页返回人格修改建议;可选按人物/状态过滤,返回 (条目, 总数)。"""
|
|
conds = []
|
|
if character_id is not None:
|
|
conds.append(PersonalityProposal.character_id == character_id)
|
|
if status is not None:
|
|
conds.append(PersonalityProposal.status == status)
|
|
count_stmt = select(func.count()).select_from(PersonalityProposal)
|
|
list_stmt = select(PersonalityProposal)
|
|
if conds:
|
|
count_stmt = count_stmt.where(*conds)
|
|
list_stmt = list_stmt.where(*conds)
|
|
total = int((await session.execute(count_stmt)).scalar_one())
|
|
result = await session.execute(
|
|
list_stmt.order_by(PersonalityProposal.created_at.desc())
|
|
.offset((page - 1) * page_size)
|
|
.limit(page_size)
|
|
)
|
|
return list(result.scalars().all()), total
|