8000 Speed up history `get_states` by bramkragten · Pull Request #23881 · home-assistant/core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Speed up history get_states #23881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 25, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 13 additions & 16 deletions homeassistant/components/history/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,20 +151,21 @@ def get_states(hass, utc_point_in_time, entity_ids=None, run=None, filters=None)
from sqlalchemy import and_, func

with session_scope(hass=hass) as session:
query = session.query(States)

if entity_ids and len(entity_ids) == 1:
# Use an entirely different (and extremely fast) query if we only
# have a single entity id
most_recent_state_ids = (
session.query(States.state_id.label("max_state_id"))
.filter(
(States.last_updated < utc_point_in_time)
& (States.entity_id.in_(entity_ids))
query = (
query.filter(
States.last_updated >= run.start,
States.last_updated < utc_point_in_time,
States.entity_id.in_(entity_ids),
)
.order_by(States.last_updated.desc())
.limit(1)
)

most_recent_state_ids = most_recent_state_ids.limit(1)

else:
# We have more than one entity to look at (most commonly we want
# all entities,) so we need to do a search on all states since the
Expand Down Expand Up @@ -200,19 +201,15 @@ def get_states(hass, utc_point_in_time, entity_ids=None, run=None, filters=None)

most_recent_state_ids = most_recent_state_ids.group_by(States.entity_id)

most_recent_state_ids = most_recent_state_ids.subquery()
most_recent_state_ids = most_recent_state_ids.subquery()

query = (
session.query(States)
.join(
query = query.join(
most_recent_state_ids,
States.state_id == most_recent_state_ids.c.max_state_id,
)
.filter((~States.domain.in_(IGNORE_DOMAINS)))
)
).filter(~States.domain.in_(IGNORE_DOMAINS))

if filters:
query = filters.apply(query, entity_ids)
if filters:
query = filters.apply(query, entity_ids)

return [
state
Expand Down
0