66 lines
2.1 KiB
Python
66 lines
2.1 KiB
Python
"""渠道码 CRUD。"""
|
|
from __future__ import annotations
|
|
|
|
from fastapi import status
|
|
from sqlalchemy import func, or_, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.exceptions import AppError
|
|
from app.models import ChannelCode
|
|
from app.schemas.channel_code import ChannelCreate, ChannelUpdate
|
|
|
|
|
|
async def paginate(
|
|
db: AsyncSession, page: int, size: int, keyword: str | None = None, type_: str | None = None
|
|
) -> tuple[list[ChannelCode], int]:
|
|
stmt = select(ChannelCode)
|
|
if keyword:
|
|
like = f"%{keyword}%"
|
|
stmt = stmt.where(or_(ChannelCode.code.ilike(like), ChannelCode.name.ilike(like)))
|
|
if type_:
|
|
stmt = stmt.where(ChannelCode.type == type_)
|
|
total = (await db.execute(
|
|
select(func.count()).select_from(stmt.order_by(None).subquery())
|
|
)).scalar() or 0
|
|
stmt = stmt.order_by(ChannelCode.id.desc()).offset((page - 1) * size).limit(size)
|
|
rows = list((await db.execute(stmt)).scalars().all())
|
|
return rows, total
|
|
|
|
|
|
async def list_all(db: AsyncSession) -> list[ChannelCode]:
|
|
res = await db.execute(select(ChannelCode).order_by(ChannelCode.id))
|
|
return list(res.scalars().all())
|
|
|
|
|
|
async def get(db: AsyncSession, cid: int) -> ChannelCode:
|
|
c = await db.get(ChannelCode, cid)
|
|
if c is None:
|
|
raise AppError("渠道码不存在", code=404, http_status=status.HTTP_404_NOT_FOUND)
|
|
return c
|
|
|
|
|
|
async def create(db: AsyncSession, data: ChannelCreate) -> ChannelCode:
|
|
res = await db.execute(select(ChannelCode).where(ChannelCode.code == data.code))
|
|
if res.scalar_one_or_none():
|
|
raise AppError("code 已存在", code=409, http_status=status.HTTP_409_CONFLICT)
|
|
c = ChannelCode(**data.model_dump())
|
|
db.add(c)
|
|
await db.commit()
|
|
await db.refresh(c)
|
|
return c
|
|
|
|
|
|
async def update(db: AsyncSession, cid: int, data: ChannelUpdate) -> ChannelCode:
|
|
c = await get(db, cid)
|
|
for k, v in data.model_dump(exclude_unset=True).items():
|
|
setattr(c, k, v)
|
|
await db.commit()
|
|
await db.refresh(c)
|
|
return c
|
|
|
|
|
|
async def delete(db: AsyncSession, cid: int) -> None:
|
|
c = await get(db, cid)
|
|
await db.delete(c)
|
|
await db.commit()
|