Improve db performance of state change events and reduce overall db size (#36883)
* Add old_state_id to states, remove old/new state data from events since it can now be found by a join * remove state lookup on restart * Ensure old_state is set for exisitng states
This commit is contained in:
1 parent
94132e5572
commit
e7d982ee11
6 files changed
+83
-26
No files matched your search
@@ -1215,10 +1215,10 @@ class TestComponentLogbook(unittest.TestCase):
|
||||
self, entity_id, event_time_fired, old_state, new_state
|
||||
):
|
||||
"""Create a state changed event from a old and new state."""
|
||||
event_data_json = json.dumps(
|
||||
{"entity_id": entity_id, "old_state": old_state, "new_state": new_state},
|
||||
cls=JSONEncoder,
|
||||
)
|
||||
attributes = {}
|
||||
if new_state is not None:
|
||||
attributes = new_state.get("attributes")
|
||||
attributes_json = json.dumps(attributes, cls=JSONEncoder)
|
||||
row = collections.namedtuple(
|
||||
"Row",
|
||||
[
|
||||
@@ -1230,18 +1230,23 @@ class TestComponentLogbook(unittest.TestCase):
|
||||
"state"
|
||||
"entity_id"
|
||||
"domain"
|
||||
"attributes"
|
||||
"state_id",
|
||||
"old_state_id",
|
||||
],
|
||||
)
|
||||
|
||||
row.event_type = EVENT_STATE_CHANGED
|
||||
row.event_data = event_data_json
|
||||
row.event_data = "{}"
|
||||
row.attributes = attributes_json
|
||||
row.time_fired = event_time_fired
|
||||
row.state = new_state and new_state.get("state")
|
||||
row.entity_id = entity_id
|
||||
row.domain = entity_id and ha.split_entity_id(entity_id)[0]
|
||||
row.context_id = None
|
||||
row.context_user_id = None
|
||||
|
||||
row.old_state_id = old_state and 1
|
||||
row.state_id = new_state and 1
|
||||
return logbook.LazyEventPartialState(row)
|
||||
|
||||
|
||||
|
||||
@@ -258,3 +258,29 @@ def test_auto_purge(hass_recorder):
|
||||
assert len(purge_old_data.mock_calls) == 1
|
||||
|
||||
dt_util.set_default_time_zone(original_tz)
|
||||
|
||||
|
||||
def test_saving_sets_old_state(hass_recorder):
|
||||
"""Test saving sets old state."""
|
||||
hass = hass_recorder()
|
||||
|
||||
hass.states.set("test.one", "on", {})
|
||||
hass.states.set("test.two", "on", {})
|
||||
wait_recording_done(hass)
|
||||
hass.states.set("test.one", "off", {})
|
||||
hass.states.set("test.two", "off", {})
|
||||
wait_recording_done(hass)
|
||||
|
||||
with session_scope(hass=hass) as session:
|
||||
states = list(session.query(States))
|
||||
assert len(states) == 4
|
||||
|
||||
assert states[0].entity_id == "test.one"
|
||||
assert states[1].entity_id == "test.two"
|
||||
assert states[2].entity_id == "test.one"
|
||||
assert states[3].entity_id == "test.two"
|
||||
|
||||
assert states[0].old_state_id is None
|
||||
assert states[1].old_state_id is None
|
||||
assert states[2].old_state_id == states[0].state_id
|
||||
assert states[3].old_state_id == states[1].state_id
|
||||
Reference in new issue
Block a user