utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from uuid import UUID
  2. from fastapi import HTTPException
  3. from sqlalchemy import exists, select
  4. from sqlalchemy.orm import Session
  5. from sqlalchemy.sql import func
  6. from app.models import Project
  7. def assert_project_exists_or_404(session: Session, project_id: UUID) -> None:
  8. if not session.execute(select(exists().where(Project.id == project_id))).scalar():
  9. raise HTTPException(status_code=404, detail="Project not found")
  10. def get_project_or_404(session: Session, project_id: UUID) -> Project:
  11. p = session.get(Project, project_id)
  12. if p is None:
  13. raise HTTPException(status_code=404, detail="Project not found")
  14. return p
  15. def get_project_organization_id(session: Session, project_id: UUID) -> str:
  16. """Fetches only Project.organization_id -- avoids loading the full
  17. Project row (and its relationships) just to check existence/ownership."""
  18. org_id = session.execute(
  19. select(Project.organization_id).where(Project.id == project_id)
  20. ).scalar_one_or_none()
  21. if org_id is None:
  22. raise HTTPException(status_code=404, detail="Project not found")
  23. return org_id
  24. async def verify_id_list(
  25. session: Session,
  26. id_list: list[UUID],
  27. project_id: UUID,
  28. ObjectClass,
  29. error_message: str = "Invalid id list",
  30. ) -> None:
  31. """Verfiy the list of uuids exists and are from the right project
  32. ---
  33. Parameters
  34. - session : sqlachlemy Async session to use to verify slot validity
  35. - id_list : list of id to check
  36. - project_id :
  37. - ObjectClass : the ORM class of the object to check the ids from. Need to have id and project_id property
  38. ---
  39. Raise
  40. HTTPException(400, error_message) - if all the ids doesn't exists or are not associated with the right project
  41. """
  42. statement = select(func.count(ObjectClass.id)).where(
  43. ObjectClass.id.in_(id_list) & (ObjectClass.project_id == project_id)
  44. )
  45. results = session.execute(statement)
  46. if results.scalar() != len(id_list):
  47. raise HTTPException(status_code=400, detail=error_message)
  48. def update_object_from_payload(obj, payload: dict):
  49. """Update the ORM model object from a pydantic payload dictionary"""
  50. for attr_name, value in payload.items():
  51. setattr(obj, attr_name, value)