Home Assistant Unofficial Reference 2024.12.1
sensor.py
Go to the documentation of this file.
1 """Sensor from an SQL Query."""
2 
3 from __future__ import annotations
4 
5 from datetime import date
6 import decimal
7 import logging
8 from typing import Any
9 
10 import sqlalchemy
11 from sqlalchemy import lambda_stmt
12 from sqlalchemy.engine import Result
13 from sqlalchemy.exc import SQLAlchemyError
14 from sqlalchemy.orm import Session, scoped_session, sessionmaker
15 from sqlalchemy.sql.lambdas import StatementLambdaElement
16 from sqlalchemy.util import LRUCache
17 
19  CONF_DB_URL,
20  SupportedDialect,
21  get_instance,
22 )
23 from homeassistant.components.sensor import CONF_STATE_CLASS
24 from homeassistant.config_entries import ConfigEntry
25 from homeassistant.const import (
26  CONF_DEVICE_CLASS,
27  CONF_ICON,
28  CONF_NAME,
29  CONF_UNIQUE_ID,
30  CONF_UNIT_OF_MEASUREMENT,
31  CONF_VALUE_TEMPLATE,
32  EVENT_HOMEASSISTANT_STOP,
33  MATCH_ALL,
34 )
35 from homeassistant.core import Event, HomeAssistant, callback
36 from homeassistant.exceptions import TemplateError
37 from homeassistant.helpers import issue_registry as ir
38 from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
39 from homeassistant.helpers.entity_platform import AddEntitiesCallback
40 from homeassistant.helpers.template import Template
42  CONF_AVAILABILITY,
43  CONF_PICTURE,
44  ManualTriggerSensorEntity,
45 )
46 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
47 
48 from .const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN
49 from .models import SQLData
50 from .util import redact_credentials, resolve_db_url
51 
52 _LOGGER = logging.getLogger(__name__)
53 
54 _SQL_LAMBDA_CACHE: LRUCache = LRUCache(1000)
55 
56 TRIGGER_ENTITY_OPTIONS = (
57  CONF_AVAILABILITY,
58  CONF_DEVICE_CLASS,
59  CONF_ICON,
60  CONF_PICTURE,
61  CONF_UNIQUE_ID,
62  CONF_STATE_CLASS,
63  CONF_UNIT_OF_MEASUREMENT,
64 )
65 
66 
68  hass: HomeAssistant,
69  config: ConfigType,
70  async_add_entities: AddEntitiesCallback,
71  discovery_info: DiscoveryInfoType | None = None,
72 ) -> None:
73  """Set up the SQL sensor from yaml."""
74  if (conf := discovery_info) is None:
75  return
76 
77  name: Template = conf[CONF_NAME]
78  query_str: str = conf[CONF_QUERY]
79  value_template: Template | None = conf.get(CONF_VALUE_TEMPLATE)
80  column_name: str = conf[CONF_COLUMN_NAME]
81  unique_id: str | None = conf.get(CONF_UNIQUE_ID)
82  db_url: str = resolve_db_url(hass, conf.get(CONF_DB_URL))
83 
84  trigger_entity_config = {CONF_NAME: name}
85  for key in TRIGGER_ENTITY_OPTIONS:
86  if key not in conf:
87  continue
88  trigger_entity_config[key] = conf[key]
89 
90  await async_setup_sensor(
91  hass,
92  trigger_entity_config,
93  query_str,
94  column_name,
95  value_template,
96  unique_id,
97  db_url,
98  True,
99  async_add_entities,
100  )
101 
102 
104  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
105 ) -> None:
106  """Set up the SQL sensor from config entry."""
107 
108  db_url: str = resolve_db_url(hass, entry.options.get(CONF_DB_URL))
109  name: str = entry.options[CONF_NAME]
110  query_str: str = entry.options[CONF_QUERY]
111  template: str | None = entry.options.get(CONF_VALUE_TEMPLATE)
112  column_name: str = entry.options[CONF_COLUMN_NAME]
113 
114  value_template: Template | None = None
115  if template is not None:
116  try:
117  value_template = Template(template, hass)
118  value_template.ensure_valid()
119  except TemplateError:
120  value_template = None
121 
122  name_template = Template(name, hass)
123  trigger_entity_config = {CONF_NAME: name_template, CONF_UNIQUE_ID: entry.entry_id}
124  for key in TRIGGER_ENTITY_OPTIONS:
125  if key not in entry.options:
126  continue
127  trigger_entity_config[key] = entry.options[key]
128 
129  await async_setup_sensor(
130  hass,
131  trigger_entity_config,
132  query_str,
133  column_name,
134  value_template,
135  entry.entry_id,
136  db_url,
137  False,
138  async_add_entities,
139  )
140 
141 
142 @callback
143 def _async_get_or_init_domain_data(hass: HomeAssistant) -> SQLData:
144  """Get or initialize domain data."""
145  if DOMAIN in hass.data:
146  sql_data: SQLData = hass.data[DOMAIN]
147  return sql_data
148 
149  session_makers_by_db_url: dict[str, scoped_session] = {}
150 
151  #
152  # Ensure we dispose of all engines at shutdown
153  # to avoid unclean disconnects
154  #
155  # Shutdown all sessions in the executor since they will
156  # do blocking I/O
157  #
158  def _shutdown_db_engines(event: Event) -> None:
159  """Shutdown all database engines."""
160  for sessmaker in session_makers_by_db_url.values():
161  sessmaker.connection().engine.dispose()
162 
163  cancel_shutdown = hass.bus.async_listen_once(
164  EVENT_HOMEASSISTANT_STOP, _shutdown_db_engines
165  )
166 
167  sql_data = SQLData(cancel_shutdown, session_makers_by_db_url)
168  hass.data[DOMAIN] = sql_data
169  return sql_data
170 
171 
173  hass: HomeAssistant,
174  trigger_entity_config: ConfigType,
175  query_str: str,
176  column_name: str,
177  value_template: Template | None,
178  unique_id: str | None,
179  db_url: str,
180  yaml: bool,
181  async_add_entities: AddEntitiesCallback,
182 ) -> None:
183  """Set up the SQL sensor."""
184  try:
185  instance = get_instance(hass)
186  except KeyError: # No recorder loaded
187  uses_recorder_db = False
188  else:
189  uses_recorder_db = db_url == instance.db_url
190  sessmaker: scoped_session | None
191  sql_data = _async_get_or_init_domain_data(hass)
192  use_database_executor = False
193  if uses_recorder_db and instance.dialect_name == SupportedDialect.SQLITE:
194  use_database_executor = True
195  assert instance.engine is not None
196  sessmaker = scoped_session(sessionmaker(bind=instance.engine, future=True))
197  # For other databases we need to create a new engine since
198  # we want the connection to use the default timezone and these
199  # database engines will use QueuePool as its only sqlite that
200  # needs our custom pool. If there is already a session maker
201  # for this db_url we can use that so we do not create a new engine
202  # for every sensor.
203  elif db_url in sql_data.session_makers_by_db_url:
204  sessmaker = sql_data.session_makers_by_db_url[db_url]
205  elif sessmaker := await hass.async_add_executor_job(
206  _validate_and_get_session_maker_for_db_url, db_url
207  ):
208  sql_data.session_makers_by_db_url[db_url] = sessmaker
209  else:
210  return
211 
212  upper_query = query_str.upper()
213  if uses_recorder_db:
214  redacted_query = redact_credentials(query_str)
215 
216  issue_key = unique_id if unique_id else redacted_query
217  # If the query has a unique id and they fix it we can dismiss the issue
218  # but if it doesn't have a unique id they have to ignore it instead
219 
220  if (
221  "ENTITY_ID," in upper_query or "ENTITY_ID " in upper_query
222  ) and "STATES_META" not in upper_query:
223  _LOGGER.error(
224  "The query `%s` contains the keyword `entity_id` but does not "
225  "reference the `states_meta` table. This will cause a full table "
226  "scan and database instability. Please check the documentation and use "
227  "`states_meta.entity_id` instead",
228  redacted_query,
229  )
230 
231  ir.async_create_issue(
232  hass,
233  DOMAIN,
234  f"entity_id_query_does_full_table_scan_{issue_key}",
235  translation_key="entity_id_query_does_full_table_scan",
236  translation_placeholders={"query": redacted_query},
237  is_fixable=False,
238  severity=ir.IssueSeverity.ERROR,
239  )
240  raise ValueError(
241  "Query contains entity_id but does not reference states_meta"
242  )
243 
244  ir.async_delete_issue(
245  hass, DOMAIN, f"entity_id_query_does_full_table_scan_{issue_key}"
246  )
247 
248  # MSSQL uses TOP and not LIMIT
249  if not ("LIMIT" in upper_query or "SELECT TOP" in upper_query):
250  if "mssql" in db_url:
251  query_str = upper_query.replace("SELECT", "SELECT TOP 1")
252  else:
253  query_str = query_str.replace(";", "") + " LIMIT 1;"
254 
256  [
257  SQLSensor(
258  trigger_entity_config,
259  sessmaker,
260  query_str,
261  column_name,
262  value_template,
263  yaml,
264  use_database_executor,
265  )
266  ],
267  )
268 
269 
270 def _validate_and_get_session_maker_for_db_url(db_url: str) -> scoped_session | None:
271  """Validate the db_url and return a session maker.
272 
273  This does I/O and should be run in the executor.
274  """
275  sess: Session | None = None
276  try:
277  engine = sqlalchemy.create_engine(db_url, future=True)
278  sessmaker = scoped_session(sessionmaker(bind=engine, future=True))
279  # Run a dummy query just to test the db_url
280  sess = sessmaker()
281  sess.execute(sqlalchemy.text("SELECT 1;"))
282 
283  except SQLAlchemyError as err:
284  _LOGGER.error(
285  "Couldn't connect using %s DB_URL: %s",
286  redact_credentials(db_url),
287  redact_credentials(str(err)),
288  )
289  return None
290  else:
291  return sessmaker
292  finally:
293  if sess:
294  sess.close()
295 
296 
297 def _generate_lambda_stmt(query: str) -> StatementLambdaElement:
298  """Generate the lambda statement."""
299  text = sqlalchemy.text(query)
300  return lambda_stmt(lambda: text, lambda_cache=_SQL_LAMBDA_CACHE)
301 
302 
304  """Representation of an SQL sensor."""
305 
306  _unrecorded_attributes = frozenset({MATCH_ALL})
307 
308  def __init__(
309  self,
310  trigger_entity_config: ConfigType,
311  sessmaker: scoped_session,
312  query: str,
313  column: str,
314  value_template: Template | None,
315  yaml: bool,
316  use_database_executor: bool,
317  ) -> None:
318  """Initialize the SQL sensor."""
319  super().__init__(self.hasshasshass, trigger_entity_config)
320  self._query_query = query
321  self._template_template = value_template
322  self._column_name_column_name = column
323  self.sessionmakersessionmaker = sessmaker
324  self._attr_extra_state_attributes_attr_extra_state_attributes = {}
325  self._use_database_executor_use_database_executor = use_database_executor
326  self._lambda_stmt_lambda_stmt = _generate_lambda_stmt(query)
327  if not yaml and (unique_id := trigger_entity_config.get(CONF_UNIQUE_ID)):
328  self._attr_name_attr_name = None
329  self._attr_has_entity_name_attr_has_entity_name = True
330  self._attr_device_info_attr_device_info = DeviceInfo(
331  entry_type=DeviceEntryType.SERVICE,
332  identifiers={(DOMAIN, unique_id)},
333  manufacturer="SQL",
334  name=self.namenamename,
335  )
336 
337  async def async_added_to_hass(self) -> None:
338  """Call when entity about to be added to hass."""
339  await super().async_added_to_hass()
340  await self.async_updateasync_update()
341 
342  @property
343  def extra_state_attributes(self) -> dict[str, Any] | None:
344  """Return extra attributes."""
345  return dict(self._attr_extra_state_attributes_attr_extra_state_attributes)
346 
347  async def async_update(self) -> None:
348  """Retrieve sensor data from the query using the right executor."""
349  if self._use_database_executor_use_database_executor:
350  data = await get_instance(self.hasshasshass).async_add_executor_job(self._update_update)
351  else:
352  data = await self.hasshasshass.async_add_executor_job(self._update_update)
353  self._process_manual_data_process_manual_data(data)
354 
355  def _update(self) -> Any:
356  """Retrieve sensor data from the query."""
357  data = None
358  self._attr_extra_state_attributes_attr_extra_state_attributes = {}
359  sess: scoped_session = self.sessionmakersessionmaker()
360  try:
361  result: Result = sess.execute(self._lambda_stmt_lambda_stmt)
362  except SQLAlchemyError as err:
363  _LOGGER.error(
364  "Error executing query %s: %s",
365  self._query_query,
366  redact_credentials(str(err)),
367  )
368  sess.rollback()
369  sess.close()
370  return None
371 
372  for res in result.mappings():
373  _LOGGER.debug("Query %s result in %s", self._query_query, res.items())
374  data = res[self._column_name_column_name]
375  for key, value in res.items():
376  if isinstance(value, decimal.Decimal):
377  value = float(value)
378  elif isinstance(value, date):
379  value = value.isoformat()
380  elif isinstance(value, (bytes, bytearray)):
381  value = f"0x{value.hex()}"
382  self._attr_extra_state_attributes_attr_extra_state_attributes[key] = value
383 
384  if data is not None and isinstance(data, (bytes, bytearray)):
385  data = f"0x{data.hex()}"
386 
387  if data is not None and self._template_template is not None:
388  self._attr_native_value_attr_native_value = (
389  self._template_template.async_render_with_possible_json_value(data, None)
390  )
391  else:
392  self._attr_native_value_attr_native_value = data
393 
394  if data is None:
395  _LOGGER.warning("%s returned no results", self._query_query)
396 
397  sess.close()
398  return data
dict[str, Any]|None extra_state_attributes(self)
Definition: sensor.py:343
None __init__(self, ConfigType trigger_entity_config, scoped_session sessmaker, str query, str column, Template|None value_template, bool yaml, bool use_database_executor)
Definition: sensor.py:317
str|UndefinedType|None name(self)
Definition: entity.py:738
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: sensor.py:72
SQLData _async_get_or_init_domain_data(HomeAssistant hass)
Definition: sensor.py:143
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: sensor.py:105
StatementLambdaElement _generate_lambda_stmt(str query)
Definition: sensor.py:297
scoped_session|None _validate_and_get_session_maker_for_db_url(str db_url)
Definition: sensor.py:270
None async_setup_sensor(HomeAssistant hass, ConfigType trigger_entity_config, str query_str, str column_name, Template|None value_template, str|None unique_id, str db_url, bool yaml, AddEntitiesCallback async_add_entities)
Definition: sensor.py:182
str redact_credentials(str|None data)
Definition: util.py:15
str resolve_db_url(HomeAssistant hass, str|None db_url)
Definition: util.py:22
Recorder get_instance(HomeAssistant hass)
Definition: recorder.py:74