This commit is contained in:
J. Nick Koston
2023-04-10 15:11:03 -10:00
parent c3be08d630
commit 541e51c867

View File

@@ -335,33 +335,37 @@ def _state_changed_during_period_stmt(
stmt = stmt.outerjoin( stmt = stmt.outerjoin(
StateAttributes, States.attributes_id == StateAttributes.attributes_id StateAttributes, States.attributes_id == StateAttributes.attributes_id
) )
if descending:
stmt = stmt.order_by(States.metadata_id, States.last_updated_ts.desc())
else:
stmt = stmt.order_by(States.metadata_id, States.last_updated_ts)
if limit: if limit:
stmt = stmt.limit(limit) stmt = stmt.limit(limit)
if not include_start_time_state or not run_start_ts: if not include_start_time_state or not run_start_ts:
return stmt return stmt.order_by(
start_time_subquery = _select_from_subquery( States.metadata_id,
_get_single_entity_start_time_stmt( States.last_updated_ts.desc() if descending else States.last_updated_ts,
start_time_ts, )
single_metadata_id,
union_subquery = union_all(
_select_from_subquery(
_get_single_entity_start_time_stmt(
start_time_ts,
single_metadata_id,
no_attributes,
False,
).subquery(),
no_attributes, no_attributes,
False, False,
).subquery(), ),
no_attributes, _select_from_subquery(
False, stmt.order_by(States.metadata_id, States.last_updated_ts).subquery(),
) no_attributes,
main_subquery = _select_from_subquery(stmt.subquery(), no_attributes, False) False,
if descending: ),
inner_queries = [main_subquery, start_time_subquery] ).subquery()
else: stmt = _select_from_subquery(union_subquery, no_attributes, False)
inner_queries = [start_time_subquery, main_subquery] if not descending:
return _select_from_subquery( return stmt
union_all(*inner_queries).subquery(), # If descending, we need to reverse the results
no_attributes, return stmt.order_by(
False, union_subquery.c.metadata_id, union_subquery.c.last_updated_ts.desc()
) )