Skip to content
Merged
Changes from 1 commit
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
32 changes: 18 additions & 14 deletions homeassistant/components/statistics/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,19 +470,9 @@ 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)

with session_scope(hass=self.hass) as session:
query = session.query(States).filter(
States.entity_id == self._source_entity_id.lower()
Expand All @@ -502,9 +492,23 @@ async def _initialize_from_database(self) -> None:
query = query.order_by(States.last_updated.desc()).limit(
self._samples_max_buffer_size
)
states = execute(query, to_native=True, validate_entity_ids=False)
if results := execute(query, to_native=False, validate_entity_ids=False):
return [state.to_native() for state in results]
return []

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 self.hass.async_add_executor_job(
self._fetch_states_from_database
):
for state in reversed(states):
self._add_state_to_queue(state)

Expand Down