base.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from __future__ import annotations
  2. from typing import Any, TypeVar
  3. from sqlalchemy import Select, func, select
  4. from sqlalchemy.orm import Session
  5. from app.db.base import Base
  6. ModelT = TypeVar("ModelT", bound=Base)
  7. def create_model(db: Session, model: type[ModelT], data: dict[str, Any]) -> ModelT:
  8. instance = model(**data)
  9. db.add(instance)
  10. db.commit()
  11. db.refresh(instance)
  12. return instance
  13. def update_model(
  14. db: Session,
  15. instance: ModelT,
  16. data: dict[str, Any],
  17. ) -> ModelT:
  18. for key, value in data.items():
  19. setattr(instance, key, value)
  20. db.add(instance)
  21. db.commit()
  22. db.refresh(instance)
  23. return instance
  24. def delete_model(db: Session, instance: ModelT) -> None:
  25. db.delete(instance)
  26. db.commit()
  27. def paginate(
  28. db: Session,
  29. statement: Select,
  30. page: int,
  31. page_size: int,
  32. ) -> tuple[list[Any], int]:
  33. count_statement = select(func.count()).select_from(statement.order_by(None).subquery())
  34. total = int(db.scalar(count_statement) or 0)
  35. rows = db.scalars(
  36. statement.offset((page - 1) * page_size).limit(page_size)
  37. ).all()
  38. return list(rows), total