annotations.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from sqlalchemy import select
  4. from sqlalchemy.orm import Query
  5. from flexmeasures.data.models.annotations import (
  6. Annotation,
  7. GenericAssetAnnotationRelationship,
  8. )
  9. from flexmeasures.data.models.data_sources import DataSource
  10. def query_asset_annotations(
  11. asset_id: int,
  12. annotations_after: datetime | None = None,
  13. annotations_before: datetime | None = None,
  14. sources: list[DataSource] | None = None,
  15. annotation_type: str | None = None,
  16. ) -> Query:
  17. """Match annotations assigned to the given asset."""
  18. query = (
  19. select(Annotation)
  20. .join(GenericAssetAnnotationRelationship)
  21. .filter(
  22. GenericAssetAnnotationRelationship.generic_asset_id == asset_id,
  23. GenericAssetAnnotationRelationship.annotation_id == Annotation.id,
  24. )
  25. )
  26. if annotations_after is not None:
  27. query = query.filter(
  28. Annotation.end > annotations_after,
  29. )
  30. if annotations_before is not None:
  31. query = query.filter(
  32. Annotation.start < annotations_before,
  33. )
  34. if sources:
  35. query = query.filter(
  36. Annotation.source.in_(sources),
  37. )
  38. if annotation_type is not None:
  39. query = query.filter(
  40. Annotation.type == annotation_type,
  41. )
  42. return query