|
| 1 | +"""Custom entity schema that holds entities of a specific type (e.g. files)""" |
| 2 | + |
| 3 | +from abc import abstractmethod |
| 4 | +from collections.abc import Iterator, Sequence |
| 5 | +from typing import Generic, TypeVar |
| 6 | + |
| 7 | +from cmem_plugin_base.dataintegration.entity import Entities, Entity, EntityPath, EntitySchema |
| 8 | + |
| 9 | +T = TypeVar("T") |
| 10 | + |
| 11 | + |
| 12 | +class TypedEntitySchema(EntitySchema, Generic[T]): |
| 13 | + """A custom entity schema that holds entities of a specific type (e.g. files).""" |
| 14 | + |
| 15 | + def __init__(self, type_uri: str, paths: Sequence[EntityPath]): |
| 16 | + super().__init__(type_uri, paths) |
| 17 | + |
| 18 | + @abstractmethod |
| 19 | + def to_entity(self, value: T) -> Entity: |
| 20 | + """Create a generic entity from a typed entity.""" |
| 21 | + |
| 22 | + @abstractmethod |
| 23 | + def from_entity(self, entity: Entity) -> T: |
| 24 | + """Create a typed entity from a generic entity. |
| 25 | +
|
| 26 | + Implementations may assume that the incoming schema matches the schema expected by |
| 27 | + this typed schema, i.e., schema validation is not required. |
| 28 | + """ |
| 29 | + |
| 30 | + def to_entities(self, values: Iterator[T]) -> "TypedEntities[T]": |
| 31 | + """Given a collection of values, create a new typed entities instance.""" |
| 32 | + return TypedEntities(values, self) |
| 33 | + |
| 34 | + def from_entities(self, entities: Entities) -> "TypedEntities[T]": |
| 35 | + """Create typed entities from generic entities. |
| 36 | +
|
| 37 | + Returns None if the entities do not match the target type. |
| 38 | + """ |
| 39 | + # TODO(robert): add validation |
| 40 | + # CMEM-6095 |
| 41 | + if entities.schema.type_uri == self.type_uri: |
| 42 | + if isinstance(entities, TypedEntities): |
| 43 | + return entities |
| 44 | + return TypedEntities(map(self.from_entity, entities.entities), self) |
| 45 | + raise ValueError( |
| 46 | + f"Expected entities of type '{self.type_uri}' but got '{entities.schema.type_uri}'." |
| 47 | + ) |
| 48 | + |
| 49 | + |
| 50 | +class TypedEntities(Entities, Generic[T]): |
| 51 | + """Collection of entities of a particular type.""" |
| 52 | + |
| 53 | + def __init__(self, values: Iterator[T], schema: TypedEntitySchema[T]): |
| 54 | + super().__init__(map(schema.to_entity, values), schema) |
| 55 | + self.values = values |
| 56 | + self.schema = schema |
0 commit comments