From 59e90508dbf09781b6be9861cafbdb7473c262fc Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 18 Mar 2022 15:31:20 -1000 Subject: [PATCH] Cache newly written state attribute ids - Once commit the new state attributes to the database the attributes_id field will be filled out. Since we have them we can add them to the cache before we clear the pending state attributes to avoid selecting them the next time we have a matching attribute set --- homeassistant/components/recorder/__init__.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/recorder/__init__.py b/homeassistant/components/recorder/__init__.py index 2ee6896d03200..31231a11f126c 100644 --- a/homeassistant/components/recorder/__init__.py +++ b/homeassistant/components/recorder/__init__.py @@ -1080,9 +1080,18 @@ def _commit_event_session(self): if dbstate in self.event_session: self.event_session.expunge(dbstate) self._pending_expunge = [] - self._pending_state_attributes = {} self.event_session.commit() + # We just committed the state attributes to the database + # and we now know the attributes_ids. We can save + # a many selects for matching attributes by loading them + # into the LRU cache now. + for state_attr in self._pending_state_attributes.values(): + self._state_attributes_ids[ + state_attr.shared_attrs + ] = state_attr.attributes_id + self._pending_state_attributes = {} + # Expire is an expensive operation (frequently more expensive # than the flush and commit itself) so we only # do it after EXPIRE_AFTER_COMMITS commits