Skip to content

Commit

Permalink
use min and max in query
Browse files Browse the repository at this point in the history
Signed-off-by: F.N. Claessen <felix@seita.nl>
  • Loading branch information
Flix6x committed Jun 19, 2023
1 parent 4093be3 commit 6e5a099
Showing 1 changed file with 21 additions and 28 deletions.
49 changes: 21 additions & 28 deletions flexmeasures/data/services/timerange.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,30 @@

from datetime import datetime

from sqlalchemy import func

from flexmeasures.utils import time_utils


def get_timerange(sensor_ids: list[int]) -> tuple[datetime, datetime]:
"""Get the start and end of the least recent and most recent event, respectively."""
from flexmeasures.data.models.time_series import TimedBelief
"""Get the start and end of the least recent and most recent event, respectively.
least_recent_query = (
TimedBelief.query.filter(TimedBelief.sensor_id.in_(sensor_ids))
.order_by(TimedBelief.event_start.asc())
.limit(1)
)
most_recent_query = (
TimedBelief.query.filter(TimedBelief.sensor_id.in_(sensor_ids))
.order_by(TimedBelief.event_start.desc())
.limit(1)
)
results = least_recent_query.union_all(most_recent_query).all()
try:
# try the most common case first (sensor has more than 1 data point)
least_recent, most_recent = results
except ValueError as e:
if not results:
# return now in case there is no data for any of the sensors
now = time_utils.server_now()
return now, now
elif len(results) == 1:
# return the start and end of the only data point found
least_recent = most_recent = results[0]
else:
# reraise this unlikely error
raise e
In case of no data, defaults to (now, now).
"""
from flexmeasures.data.models.time_series import Sensor, TimedBelief

return least_recent.event_start, most_recent.event_end
least_recent_event_start_and_most_recent_event_end = (
TimedBelief.query.with_entities(
# least recent event start
func.min(TimedBelief.event_start),
# most recent event end
func.max(TimedBelief.event_start + Sensor.event_resolution),
)
.join(Sensor, TimedBelief.sensor_id == Sensor.id)
.filter(TimedBelief.sensor_id.in_(sensor_ids))
).one_or_none()
if least_recent_event_start_and_most_recent_event_end == (None, None):
# return now in case there is no data for any of the sensors
now = time_utils.server_now()
return now, now
return least_recent_event_start_and_most_recent_event_end

0 comments on commit 6e5a099

Please sign in to comment.