Files
ShiErFeng/shierfeng-fastapi-backend/module_business/dao/test_batch_dao.py
T

48 lines
1.8 KiB
Python

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from module_business.domain.enums import TestBatchStatus
from module_business.entity.do.test_batch_do import BizTestBatch, BizTestBatchUser
class TestBatchDao:
"""测试批次访问数据库操作层。"""
@classmethod
async def get_batch(cls, db: AsyncSession, batch_id: int) -> BizTestBatch | None:
result = await db.execute(select(BizTestBatch).where(BizTestBatch.batch_id == batch_id))
return result.scalar_one_or_none()
@classmethod
async def get_batch_for_update(cls, db: AsyncSession, batch_id: int) -> BizTestBatch | None:
result = await db.execute(
select(BizTestBatch)
.where(BizTestBatch.batch_id == batch_id)
.with_for_update()
.execution_options(populate_existing=True)
)
return result.scalar_one_or_none()
@classmethod
async def user_is_authorized(cls, db: AsyncSession, batch_id: int, user_id: int) -> bool:
result = await db.execute(
select(BizTestBatchUser.batch_id).where(
BizTestBatchUser.batch_id == batch_id,
BizTestBatchUser.user_id == user_id,
)
)
return result.scalar_one_or_none() is not None
@classmethod
async def list_available_batches(
cls,
db: AsyncSession,
user_id: int,
is_admin: bool,
) -> list[BizTestBatch]:
statement = select(BizTestBatch).where(BizTestBatch.status == TestBatchStatus.ACTIVE.value)
if not is_admin:
statement = statement.join(BizTestBatchUser).where(BizTestBatchUser.user_id == user_id)
result = await db.execute(statement.order_by(BizTestBatch.batch_id.desc()))
return list(result.scalars().all())