|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any, Optional, List, Dict |
| 4 | + |
| 5 | +# Generic OData DAO for code-generated models. |
| 6 | +# It uses the code-generated module's ENTITY_SETS mapping to build URLs and (de)serialize entities. |
| 7 | + |
| 8 | +class GenericODataDao: |
| 9 | + def __init__(self, service, entity_set: str, model_module: Any): |
| 10 | + self.service = service |
| 11 | + self.entity_set = entity_set |
| 12 | + self.model_module = model_module |
| 13 | + |
| 14 | + def _base_collection_url(self) -> str: |
| 15 | + base = self.service.url.url |
| 16 | + if not str(self.service.url.path).endswith('/'): |
| 17 | + base += '/' |
| 18 | + return base + self.entity_set |
| 19 | + |
| 20 | + def _entity_url(self, entity_id: Any) -> str: |
| 21 | + if isinstance(entity_id, str): |
| 22 | + _id = f"'{entity_id}'" |
| 23 | + else: |
| 24 | + _id = entity_id |
| 25 | + return f"{self._base_collection_url()}({_id})" |
| 26 | + |
| 27 | + def create(self, entity: Any) -> None: |
| 28 | + # POST to collection; deep inserts are supported if server allows them. |
| 29 | + payload = entity.__getstate__() |
| 30 | + resp = self.service.execute('POST', self._base_collection_url(), json=payload) |
| 31 | + try: |
| 32 | + data = resp.json() |
| 33 | + except Exception: |
| 34 | + data = None |
| 35 | + if isinstance(data, dict): |
| 36 | + try: |
| 37 | + entity.__setstate__(data) |
| 38 | + except Exception: |
| 39 | + # Keep entity as-is if server returns minimal response |
| 40 | + pass |
| 41 | + # ensure service propagation for nested entities |
| 42 | + try: |
| 43 | + entity.set_service(self.service) |
| 44 | + entity.ensure_service_on_children(self.service) |
| 45 | + except Exception: |
| 46 | + pass |
| 47 | + |
| 48 | + def update(self, entity: Any) -> None: |
| 49 | + if getattr(entity, 'id', None) is None: |
| 50 | + raise ValueError('Cannot update an entity without id') |
| 51 | + payload = entity.__getstate__() |
| 52 | + self.service.execute('PATCH', self._entity_url(entity.id), json=payload) |
| 53 | + |
| 54 | + def patch(self, entity: Any, patches: List[Dict[str, Any]]) -> None: |
| 55 | + if getattr(entity, 'id', None) is None: |
| 56 | + raise ValueError('Cannot patch an entity without id') |
| 57 | + headers = {'Content-Type': 'application/json-patch+json'} |
| 58 | + self.service.execute('PATCH', self._entity_url(entity.id), headers=headers, json=patches) |
| 59 | + |
| 60 | + def delete(self, entity: Any) -> None: |
| 61 | + if getattr(entity, 'id', None) is None: |
| 62 | + raise ValueError('Cannot delete an entity without id') |
| 63 | + self.service.execute('DELETE', self._entity_url(entity.id)) |
0 commit comments