repository.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # (c) Nelen & Schuurmans
  2. from typing import Any
  3. from typing import Generic
  4. from typing import List
  5. from typing import Optional
  6. from typing import Type
  7. from typing import TypeVar
  8. from typing import Union
  9. from .exceptions import DoesNotExist
  10. from .filter import Filter
  11. from .gateway import Gateway
  12. from .gateway import SyncGateway
  13. from .pagination import Page
  14. from .pagination import PageOptions
  15. from .types import Id
  16. from .types import Json
  17. from .value_object import ValueObject
  18. __all__ = ["Repository", "SyncRepository"]
  19. T = TypeVar("T", bound=ValueObject)
  20. class Repository(Generic[T]):
  21. entity: Type[T]
  22. def __init__(self, gateway: Gateway):
  23. self.gateway = gateway
  24. def __init_subclass__(cls) -> None:
  25. (base,) = cls.__orig_bases__ # type: ignore
  26. (entity,) = base.__args__
  27. super().__init_subclass__()
  28. cls.entity = entity
  29. async def all(self, params: Optional[PageOptions] = None) -> Page[T]:
  30. return await self.filter([], params=params)
  31. async def by(
  32. self, key: str, value: Any, params: Optional[PageOptions] = None
  33. ) -> Page[T]:
  34. return await self.filter([Filter(field=key, values=[value])], params=params)
  35. async def filter(
  36. self, filters: List[Filter], params: Optional[PageOptions] = None
  37. ) -> Page[T]:
  38. records = await self.gateway.filter(filters, params=params)
  39. total = len(records)
  40. # when using pagination, we may need to do a count in the db
  41. # except in a typical 'first page' situation with few records
  42. if params is not None and not (params.offset == 0 and total < params.limit):
  43. total = await self.count(filters)
  44. return Page(
  45. total=total,
  46. limit=params.limit if params else None,
  47. offset=params.offset if params else None,
  48. items=[self.entity(**x) for x in records],
  49. )
  50. async def get(self, id: Id) -> T:
  51. res = await self.gateway.get(id)
  52. if res is None:
  53. raise DoesNotExist("object", id)
  54. else:
  55. return self.entity(**res)
  56. async def add(self, item: Union[T, Json]) -> T:
  57. if isinstance(item, dict):
  58. item = self.entity.create(**item)
  59. created = await self.gateway.add(item.model_dump())
  60. return self.entity(**created)
  61. async def update(self, id: Id, values: Json) -> T:
  62. if not values:
  63. return await self.get(id)
  64. updated = await self.gateway.update_transactional(
  65. id, lambda x: self.entity(**x).update(**values).model_dump()
  66. )
  67. return self.entity(**updated)
  68. async def upsert(self, item: T) -> T:
  69. values = item.model_dump()
  70. upserted = await self.gateway.upsert(values)
  71. return self.entity(**upserted)
  72. async def remove(self, id: Id) -> bool:
  73. return await self.gateway.remove(id)
  74. async def count(self, filters: List[Filter]) -> int:
  75. return await self.gateway.count(filters)
  76. async def exists(self, filters: List[Filter]) -> bool:
  77. return await self.gateway.exists(filters)
  78. # This is a copy-paste from Repository, but with all the async / await removed
  79. class SyncRepository(Generic[T]):
  80. entity: Type[T]
  81. def __init__(self, gateway: SyncGateway):
  82. self.gateway = gateway
  83. def __init_subclass__(cls) -> None:
  84. (base,) = cls.__orig_bases__ # type: ignore
  85. (entity,) = base.__args__
  86. super().__init_subclass__()
  87. cls.entity = entity
  88. def all(self, params: Optional[PageOptions] = None) -> Page[T]:
  89. return self.filter([], params=params)
  90. def by(self, key: str, value: Any, params: Optional[PageOptions] = None) -> Page[T]:
  91. return self.filter([Filter(field=key, values=[value])], params=params)
  92. def filter(
  93. self, filters: List[Filter], params: Optional[PageOptions] = None
  94. ) -> Page[T]:
  95. records = self.gateway.filter(filters, params=params)
  96. total = len(records)
  97. # when using pagination, we may need to do a count in the db
  98. # except in a typical 'first page' situation with few records
  99. if params is not None and not (params.offset == 0 and total < params.limit):
  100. total = self.count(filters)
  101. return Page(
  102. total=total,
  103. limit=params.limit if params else None,
  104. offset=params.offset if params else None,
  105. items=[self.entity(**x) for x in records],
  106. )
  107. def get(self, id: Id) -> T:
  108. res = self.gateway.get(id)
  109. if res is None:
  110. raise DoesNotExist("object", id)
  111. else:
  112. return self.entity(**res)
  113. def add(self, item: Union[T, Json]) -> T:
  114. if isinstance(item, dict):
  115. item = self.entity.create(**item)
  116. created = self.gateway.add(item.model_dump())
  117. return self.entity(**created)
  118. def update(self, id: Id, values: Json) -> T:
  119. if not values:
  120. return self.get(id)
  121. updated = self.gateway.update_transactional(
  122. id, lambda x: self.entity(**x).update(**values).model_dump()
  123. )
  124. return self.entity(**updated)
  125. def upsert(self, item: T) -> T:
  126. values = item.model_dump()
  127. upserted = self.gateway.upsert(values)
  128. return self.entity(**upserted)
  129. def remove(self, id: Id) -> bool:
  130. return self.gateway.remove(id)
  131. def count(self, filters: List[Filter]) -> int:
  132. return self.gateway.count(filters)
  133. def exists(self, filters: List[Filter]) -> bool:
  134. return self.gateway.exists(filters)