1
mirror of https://github.com/home-assistant/core synced 2024-07-15 09:42:11 +02:00

Avoid db hit and executor job for impossible history queries (#104724)

This commit is contained in:
J. Nick Koston 2023-11-29 11:20:22 -07:00 committed by GitHub
parent 1fefa93648
commit 50f2c41145
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 15 additions and 4 deletions

View File

@ -21,7 +21,7 @@ import homeassistant.util.dt as dt_util
from . import websocket_api
from .const import DOMAIN
from .helpers import entities_may_have_state_changes_after
from .helpers import entities_may_have_state_changes_after, has_recorder_run_after
CONF_ORDER = "use_include_order"
@ -106,7 +106,8 @@ class HistoryPeriodView(HomeAssistantView):
no_attributes = "no_attributes" in request.query
if (
not include_start_time_state
(end_time and not has_recorder_run_after(hass, end_time))
or not include_start_time_state
and entity_ids
and not entities_may_have_state_changes_after(
hass, entity_ids, start_time, no_attributes

View File

@ -4,6 +4,8 @@ from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime as dt
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.models import process_timestamp
from homeassistant.core import HomeAssistant
@ -21,3 +23,10 @@ def entities_may_have_state_changes_after(
return True
return False
def has_recorder_run_after(hass: HomeAssistant, run_time: dt) -> bool:
"""Check if the recorder has any runs after a specific time."""
return run_time >= process_timestamp(
get_instance(hass).recorder_runs_manager.first.start
)

View File

@ -39,7 +39,7 @@ from homeassistant.helpers.typing import EventType
import homeassistant.util.dt as dt_util
from .const import EVENT_COALESCE_TIME, MAX_PENDING_HISTORY_STATES
from .helpers import entities_may_have_state_changes_after
from .helpers import entities_may_have_state_changes_after, has_recorder_run_after
_LOGGER = logging.getLogger(__name__)
@ -142,7 +142,8 @@ async def ws_get_history_during_period(
no_attributes = msg["no_attributes"]
if (
not include_start_time_state
(end_time and not has_recorder_run_after(hass, end_time))
or not include_start_time_state
and entity_ids
and not entities_may_have_state_changes_after(
hass, entity_ids, start_time, no_attributes