| 112 | |
| 113 | |
| 114 | class BaseRepository(ABC, Generic[T]): |
| 115 | def __init__(self, db_config: MyDatabaseConfig, model: type[T], id_field: str = "id"): |
| 116 | self._db_config = db_config |
| 117 | self._model = model |
| 118 | self._id_field = id_field |
| 119 | |
| 120 | async def get_by_id( |
| 121 | self, |
| 122 | uid: Any, |
| 123 | ) -> T: |
| 124 | obj = await self.find_by_id(uid) |
| 125 | if obj is None: |
| 126 | raise DomainException( |
| 127 | error_no=ErrorNo.REPOSITORY_DATA_BY_ID_NOT_FOUND, |
| 128 | message=f"{self._model.__name__} with {self._id_field}={uid} not found", |
| 129 | ) |
| 130 | return obj |
| 131 | |
| 132 | async def find_by_id( |
| 133 | self, |
| 134 | uid: Any, |
| 135 | ) -> T | None: |
| 136 | query = select(self._model).where(getattr(self._model, self._id_field) == uid) |
| 137 | async with self.get_session() as session: |
| 138 | result = await session.execute(query) |
| 139 | return result.scalar_one_or_none() |
| 140 | |
| 141 | async def create(self, data: dict[str, Any] | T) -> T: |
| 142 | if isinstance(data, dict): |
| 143 | entity = self._model(**data) |
| 144 | else: |
| 145 | entity = data |
| 146 | async with self.get_session() as session: |
| 147 | session.add(entity) |
| 148 | await session.flush() |
| 149 | await session.refresh(entity) |
| 150 | return entity |
| 151 | |
| 152 | async def update( |
| 153 | self, |
| 154 | uid: Any, |
| 155 | data: dict[str, Any] | T, |
| 156 | ) -> T: |
| 157 | if isinstance(data, dict): |
| 158 | d = data |
| 159 | else: |
| 160 | d = data.__dict__ |
| 161 | |
| 162 | entity = await self.get_by_id(uid) |
| 163 | |
| 164 | for field, value in d.items(): |
| 165 | if hasattr(entity, field): |
| 166 | setattr(entity, field, value) |
| 167 | async with self.get_session() as session: |
| 168 | session.add(entity) |
| 169 | await session.flush() |
| 170 | await session.refresh(entity) |
| 171 | return entity |
nothing calls this directly
no outgoing calls
no test coverage detected