Separate attrs into another table (reduces database size) (#68224)
This commit is contained in:
parent
d7145095ef
commit
9215702388
17 changed files with 788 additions and 98 deletions
|
@ -12,7 +12,7 @@ from typing import Any, Literal, cast
|
|||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
|
||||
from homeassistant.components.recorder.models import States
|
||||
from homeassistant.components.recorder.models import StateAttributes, States
|
||||
from homeassistant.components.recorder.util import execute, session_scope
|
||||
from homeassistant.components.sensor import (
|
||||
PLATFORM_SCHEMA,
|
||||
|
@ -482,9 +482,10 @@ class StatisticsSensor(SensorEntity):
|
|||
"""
|
||||
|
||||
_LOGGER.debug("%s: initializing values from the database", self.entity_id)
|
||||
states = []
|
||||
|
||||
with session_scope(hass=self.hass) as session:
|
||||
query = session.query(States).filter(
|
||||
query = session.query(States, StateAttributes).filter(
|
||||
States.entity_id == self._source_entity_id.lower()
|
||||
)
|
||||
|
||||
|
@ -499,10 +500,18 @@ class StatisticsSensor(SensorEntity):
|
|||
else:
|
||||
_LOGGER.debug("%s: retrieving all records", self.entity_id)
|
||||
|
||||
query = query.outerjoin(
|
||||
StateAttributes, States.attributes_id == StateAttributes.attributes_id
|
||||
)
|
||||
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):
|
||||
for state, attributes in results:
|
||||
native = state.to_native()
|
||||
if not native.attributes:
|
||||
native.attributes = attributes.to_native()
|
||||
states.append(native)
|
||||
|
||||
if states:
|
||||
for state in reversed(states):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue