Skip to content
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: 17 additions & 12 deletions homeassistant/components/statistics/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import voluptuous as vol

from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.models import StateAttributes, States
from homeassistant.components.recorder.util import execute, session_scope
from homeassistant.components.sensor import (
Expand Down Expand Up @@ -470,17 +471,8 @@ def _scheduled_update(now: datetime) -> None:
self.hass, _scheduled_update, next_to_purge_timestamp
)

async def _initialize_from_database(self) -> None:
"""Initialize the list of states from the database.

The query will get the list of states in DESCENDING order so that we
can limit the result to self._sample_size. Afterwards reverse the
list so that we get it in the right order again.

If MaxAge is provided then query will restrict to entries younger then
current datetime - MaxAge.
"""

def _fetch_states_from_database(self) -> list[State]:
"""Fetch the states from the database."""
_LOGGER.debug("%s: initializing values from the database", self.entity_id)
states = []

Expand Down Expand Up @@ -512,8 +504,21 @@ async def _initialize_from_database(self) -> None:
if not native.attributes:
native.attributes = attributes.to_native()
states.append(native)
return states

if states:
async def _initialize_from_database(self) -> None:
"""Initialize the list of states from the database.

The query will get the list of states in DESCENDING order so that we
can limit the result to self._sample_size. Afterwards reverse the
list so that we get it in the right order again.

If MaxAge is provided then query will restrict to entries younger then
current datetime - MaxAge.
"""
if states := await get_instance(self.hass).async_add_executor_job(
self._fetch_states_from_database
):
for state in reversed(states):
self._add_state_to_queue(state)

Expand Down