schema_service.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # app/services/schema_service.py
  2. from typing import List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from sqlalchemy import select
  5. from app.core.biz_exception import NotFoundError
  6. from app.models.schema import VasSchema
  7. from app.schemas.schema import VasSchemaCreate, VasSchemaUpdate
  8. class SchemaService:
  9. @staticmethod
  10. async def create(
  11. db: AsyncSession,
  12. data: VasSchemaCreate,
  13. ) -> VasSchema:
  14. rec = VasSchema(**data.dict())
  15. db.add(rec)
  16. await db.commit()
  17. await db.refresh(rec)
  18. return rec
  19. @staticmethod
  20. async def get(
  21. db: AsyncSession,
  22. id: int,
  23. ) -> VasSchema:
  24. stmt = select(VasSchema).where(VasSchema.id == id)
  25. obj = (await db.execute(stmt)).scalar_one_or_none()
  26. if not obj:
  27. raise NotFoundError("Schema not exist")
  28. return obj
  29. @staticmethod
  30. async def update(
  31. db: AsyncSession,
  32. id: int,
  33. data: VasSchemaUpdate,
  34. ) -> VasSchema:
  35. stmt = select(VasSchema).where(VasSchema.id == id)
  36. obj = (await db.execute(stmt)).scalar_one_or_none()
  37. if not obj:
  38. raise NotFoundError("Schema not exist")
  39. for k, v in data.dict(exclude_unset=True).items():
  40. setattr(obj, k, v)
  41. await db.commit()
  42. await db.refresh(obj)
  43. return obj
  44. @staticmethod
  45. async def delete(
  46. db: AsyncSession,
  47. id: int,
  48. ) -> None:
  49. stmt = select(VasSchema).where(VasSchema.id == id)
  50. obj = (await db.execute(stmt)).scalar_one_or_none()
  51. if not obj:
  52. raise NotFoundError("Schema not exist")
  53. await db.delete(obj)
  54. await db.commit()
  55. @staticmethod
  56. async def list_all(
  57. db: AsyncSession,
  58. ) -> List[VasSchema]:
  59. stmt = select(VasSchema)
  60. result = await db.execute(stmt)
  61. return result.scalars().all()