Separate attrs into another table (reduces database size) (#68224)

This commit is contained in:
J. Nick Koston 2022-03-18 00:23:13 -10:00 committed by GitHub
parent d7145095ef
commit 9215702388
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 788 additions and 98 deletions

View file

@ -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):