From 09b3498f410106881fc5e095c49a8d527fa89644 Mon Sep 17 00:00:00 2001 From: Greg Laabs Date: Sat, 29 Jul 2017 18:43:09 -0700 Subject: [PATCH] Remove the ORDER BY entity_id when fetching states, and add logging Having this ORDER BY in the query prevents it from using an index due to the range filter, so it has been removed. We already do a `groupby` in the `states_to_json` method which accomplishes exactly what the ORDER BY in the query was trying to do anyway, so this change causes no functional difference. Also added DEBUG-level logging to allow diagnosing a user's slow history page. --- homeassistant/components/history.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/history.py b/homeassistant/components/history.py index 0eb177fb5c7..51e7fb0ce5a 100644 --- a/homeassistant/components/history.py +++ b/homeassistant/components/history.py @@ -57,6 +57,7 @@ def get_significant_states(hass, start_time, end_time=None, entity_id=None, as well as all states from certain domains (for instance thermostat so that we get current temperature in our graphs). """ + timer_start = time.perf_counter() from homeassistant.components.recorder.models import States entity_ids = (entity_id.lower(), ) if entity_id is not None else None @@ -73,12 +74,18 @@ def get_significant_states(hass, start_time, end_time=None, entity_id=None, if end_time is not None: query = query.filter(States.last_updated < end_time) + query = query.order_by(States.last_updated) + states = ( - state for state in execute( - query.order_by(States.entity_id, States.last_updated)) + state for state in execute(query) if (_is_significant(state) and not state.attributes.get(ATTR_HIDDEN, False))) + if _LOGGER.isEnabledFor(logging.DEBUG): + elapsed = time.perf_counter() - timer_start + _LOGGER.debug( + 'get_significant_states took %fs', elapsed) + return states_to_json(hass, states, start_time, entity_id, filters)