From 43b4b55778207d87e3f24543a876ae73e4a7107a Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 19 Feb 2023 17:40:33 -0600 Subject: [PATCH] reduce --- .../components/recorder/statistics.py | 33 ++++++++----------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/homeassistant/components/recorder/statistics.py b/homeassistant/components/recorder/statistics.py index e0d02e8a0e3..539c9add70e 100644 --- a/homeassistant/components/recorder/statistics.py +++ b/homeassistant/components/recorder/statistics.py @@ -1976,24 +1976,6 @@ def get_latest_short_term_statistics( ) -def _get_most_recent_statistics_subquery( - metadata_ids: set[int], table: type[StatisticsBase], start_time_ts: float -) -> Subquery: - """Generate the subquery to find the most recent statistic row.""" - return ( - select( - # https://github.com/sqlalchemy/sqlalchemy/issues/9189 - # pylint: disable-next=not-callable - func.max(table.start_ts).label("max_start_ts"), - table.metadata_id.label("max_metadata_id"), - ) - .filter(table.start_ts < start_time_ts) - .filter(table.metadata_id.in_(metadata_ids)) - .group_by(table.metadata_id) - .subquery() - ) - - def _statistics_at_time( session: Session, metadata_ids: set[int], @@ -2017,8 +1999,19 @@ def _statistics_at_time( columns = columns.add_columns(table.sum) start_time_ts = start_time.timestamp() - most_recent_statistic_ids = _get_most_recent_statistics_subquery( - metadata_ids, table, start_time_ts + most_recent_statistic_ids = ( + # https://github.com/sqlalchemy/sqlalchemy/issues/9189 + # pylint: disable-next=not-callable + lambda_stmt( + lambda: select( + func.max(table.start_ts).label("max_start_ts"), + table.metadata_id.label("max_metadata_id"), + ) + ) + .filter(table.start_ts < start_time_ts) + .filter(table.metadata_id.in_(metadata_ids)) + .group_by(table.metadata_id) + .subquery() ) stmt = lambda_stmt(lambda: columns).join( most_recent_statistic_ids,