Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Managers for each table."""
2 
3 from __future__ import annotations
4 
5 from typing import TYPE_CHECKING, Any
6 
7 from lru import LRU
8 
9 from homeassistant.util.event_type import EventType
10 
11 if TYPE_CHECKING:
12  from ..core import Recorder
13 
14 
15 class BaseTableManager[_DataT]:
16  """Base class for table managers."""
17 
18  _id_map: LRU[EventType[Any] | str, int]
19 
20  def __init__(self, recorder: Recorder) -> None:
21  """Initialize the table manager.
22 
23  The table manager is responsible for managing the id mappings
24  for a table. When data is committed to the database, the
25  manager will move the data from the pending to the id map.
26  """
27  self.recorderrecorder = recorder
28  self._pending: dict[EventType[Any] | str, _DataT] = {}
29 
30  def get_from_cache(self, data: str) -> int | None:
31  """Resolve data to the id without accessing the underlying database.
32 
33  This call is not thread-safe and must be called from the
34  recorder thread.
35  """
36  return self._id_map.get(data)
37 
38  def get_pending(self, shared_data: EventType[Any] | str) -> _DataT | None:
39  """Get pending data that have not be assigned ids yet.
40 
41  This call is not thread-safe and must be called from the
42  recorder thread.
43  """
44  return self._pending.get(shared_data)
45 
46  def reset(self) -> None:
47  """Reset after the database has been reset or changed.
48 
49  This call is not thread-safe and must be called from the
50  recorder thread.
51  """
52  self._id_map.clear()
53  self._pending.clear()
54 
55 
56 class BaseLRUTableManager[_DataT](BaseTableManager[_DataT]):
57  """Base class for LRU table managers."""
58 
59  def __init__(self, recorder: Recorder, lru_size: int) -> None:
60  """Initialize the LRU table manager.
61 
62  We keep track of the most recently used items
63  and evict the least recently used items when the cache is full.
64  """
65  super().__init__(recorder)
66  self._id_map_id_map = LRU(lru_size)
67 
68  def adjust_lru_size(self, new_size: int) -> None:
69  """Adjust the LRU cache size.
70 
71  This call is not thread-safe and must be called from the
72  recorder thread.
73  """
74  lru = self._id_map_id_map
75  if new_size > lru.get_size():
76  lru.set_size(new_size)
None __init__(self, Recorder recorder, int lru_size)
Definition: __init__.py:59
_DataT|None get_pending(self, EventType[Any]|str shared_data)
Definition: __init__.py:38
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88