From e3174fab3160d9850a17888bf2d9ac8b2c18bad1 Mon Sep 17 00:00:00 2001 From: Peter Dudfield <34686298+peterdudfield@users.noreply.github.com> Date: Thu, 7 Mar 2024 17:01:13 +0000 Subject: [PATCH] add created_by filter to latest_forecast_value (#103) --- pvsite_datamodel/read/latest_forecast_values.py | 16 +++++++++++----- tests/test_read.py | 9 +++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/pvsite_datamodel/read/latest_forecast_values.py b/pvsite_datamodel/read/latest_forecast_values.py index 1908e74..bac5a65 100644 --- a/pvsite_datamodel/read/latest_forecast_values.py +++ b/pvsite_datamodel/read/latest_forecast_values.py @@ -16,6 +16,7 @@ def get_latest_forecast_values_by_site( site_uuids: list[uuid.UUID], start_utc: dt.datetime, sum_by: Optional[str] = None, + created_by: Optional[dt.datetime] = None, ) -> Union[dict[uuid.UUID, list[ForecastValueSQL]], List[ForecastValueSum]]: """Get the forecast values by input sites, get the latest value. @@ -40,6 +41,7 @@ def get_latest_forecast_values_by_site( :param session: The sqlalchemy database session :param site_uuids: list of site_uuids for which to fetch latest forecast values :param start_utc: filters on forecast values target_time >= start_utc + :param created_by: filter on forecast values created time <= created_by :param sum_by: optional, sum the forecast values by this column """ @@ -57,11 +59,15 @@ def get_latest_forecast_values_by_site( ForecastValueSQL.start_utc >= start_utc, ForecastSQL.site_uuid.in_(site_uuids), ) - .order_by( - ForecastSQL.site_uuid, - ForecastValueSQL.start_utc, - ForecastSQL.timestamp_utc.desc(), - ) + ) + + if created_by is not None: + query = query.filter(ForecastValueSQL.created_utc <= created_by) + + query = query.order_by( + ForecastSQL.site_uuid, + ForecastValueSQL.start_utc, + ForecastSQL.timestamp_utc.desc(), ) if sum_by is None: diff --git a/tests/test_read.py b/tests/test_read.py index 0237aa4..9f20d31 100644 --- a/tests/test_read.py +++ b/tests/test_read.py @@ -333,6 +333,15 @@ def test_get_latest_forecast_values(db_session, sites): assert values_as_tuple == expected[site_uuid] + latest_forecast = get_latest_forecast_values_by_site( + session=db_session, + site_uuids=site_uuids, + start_utc=d1, + sum_by="total", + created_by=dt.datetime.now() - dt.timedelta(hours=3), + ) + assert len(latest_forecast) == 0 + latest_forecast = get_latest_forecast_values_by_site( session=db_session, site_uuids=site_uuids, start_utc=d1, sum_by="total" )