add select relations to list_by_type tool

This commit is contained in:
phernandez
2024-12-30 15:05:35 -06:00
parent 8dd2de3e9a
commit 12a21d81b6
2 changed files with 100 additions and 6 deletions
@@ -24,17 +24,34 @@ class EntityRepository(Repository[Entity]):
return await self.find_one(query)
async def list_entities(
self,
entity_type: Optional[str] = None,
doc_id: Optional[int] = None,
sort_by: Optional[str] = "updated_at",
self,
entity_type: Optional[str] = None,
doc_id: Optional[int] = None,
sort_by: Optional[str] = "updated_at",
include_related: bool = False,
) -> Sequence[Entity]:
"""List all entities, optionally filtered by type and sorted."""
query = self.select().options(*self.get_load_options())
query = self.select()
# Always load base relations
query = query.options(*self.get_load_options())
# Apply filters
if entity_type:
query = query.where(Entity.entity_type == entity_type)
# When include_related is True, get both:
# 1. Entities of the requested type
# 2. Entities that have relations with entities of the requested type
if include_related:
query = query.where(
or_(
Entity.entity_type == entity_type,
Entity.from_relations.any(Relation.to_entity.has(entity_type=entity_type)),
Entity.to_relations.any(Relation.from_entity.has(entity_type=entity_type))
)
)
else:
query = query.where(Entity.entity_type == entity_type)
if doc_id:
query = query.where(Entity.doc_id == doc_id)