init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,126 @@
"""The sql component."""
from __future__ import annotations
import logging
import sqlparse
import voluptuous as vol
from homeassistant.components.recorder import CONF_DB_URL, get_instance
from homeassistant.components.sensor import (
CONF_STATE_CLASS,
DEVICE_CLASSES_SCHEMA,
STATE_CLASSES_SCHEMA,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_ICON,
CONF_NAME,
CONF_UNIQUE_ID,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.trigger_template_entity import (
CONF_AVAILABILITY,
CONF_PICTURE,
)
from homeassistant.helpers.typing import ConfigType
from .const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN, PLATFORMS
from .util import redact_credentials
_LOGGER = logging.getLogger(__name__)
def validate_sql_select(value: str) -> str:
"""Validate that value is a SQL SELECT query."""
if len(query := sqlparse.parse(value.lstrip().lstrip(";"))) > 1:
raise vol.Invalid("Multiple SQL queries are not supported")
if len(query) == 0 or (query_type := query[0].get_type()) == "UNKNOWN":
raise vol.Invalid("Invalid SQL query")
if query_type != "SELECT":
_LOGGER.debug("The SQL query %s is of type %s", query, query_type)
raise vol.Invalid("Only SELECT queries allowed")
return str(query[0])
QUERY_SCHEMA = vol.Schema(
{
vol.Required(CONF_COLUMN_NAME): cv.string,
vol.Required(CONF_NAME): cv.template,
vol.Required(CONF_QUERY): vol.All(cv.string, validate_sql_select),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_DB_URL): cv.string,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_STATE_CLASS): STATE_CLASSES_SCHEMA,
vol.Optional(CONF_AVAILABILITY): cv.template,
vol.Optional(CONF_ICON): cv.template,
vol.Optional(CONF_PICTURE): cv.template,
}
)
CONFIG_SCHEMA = vol.Schema(
{vol.Optional(DOMAIN): vol.All(cv.ensure_list, [QUERY_SCHEMA])},
extra=vol.ALLOW_EXTRA,
)
def remove_configured_db_url_if_not_needed(
hass: HomeAssistant, entry: ConfigEntry
) -> None:
"""Remove db url from config if it matches recorder database."""
hass.config_entries.async_update_entry(
entry,
options={
key: value for key, value in entry.options.items() if key != CONF_DB_URL
},
)
async def async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Update listener for options."""
await hass.config_entries.async_reload(entry.entry_id)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up SQL from yaml config."""
if (conf := config.get(DOMAIN)) is None:
return True
for sensor_conf in conf:
await discovery.async_load_platform(
hass, Platform.SENSOR, DOMAIN, sensor_conf, config
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up SQL from a config entry."""
_LOGGER.debug(
"Comparing %s and %s",
redact_credentials(entry.options.get(CONF_DB_URL)),
redact_credentials(get_instance(hass).db_url),
)
if entry.options.get(CONF_DB_URL) == get_instance(hass).db_url:
remove_configured_db_url_if_not_needed(hass, entry)
entry.async_on_unload(entry.add_update_listener(async_update_listener))
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload SQL config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -0,0 +1,282 @@
"""Adds config flow for SQL integration."""
from __future__ import annotations
import logging
from typing import Any
import sqlalchemy
from sqlalchemy.engine import Result
from sqlalchemy.exc import MultipleResultsFound, NoSuchColumnError, SQLAlchemyError
from sqlalchemy.orm import Session, scoped_session, sessionmaker
import sqlparse
from sqlparse.exceptions import SQLParseError
import voluptuous as vol
from homeassistant.components.recorder import CONF_DB_URL, get_instance
from homeassistant.components.sensor import (
CONF_STATE_CLASS,
SensorDeviceClass,
SensorStateClass,
)
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlow,
ConfigFlowResult,
OptionsFlow,
)
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_NAME,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import callback
from homeassistant.helpers import selector
from .const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN
from .util import resolve_db_url
_LOGGER = logging.getLogger(__name__)
OPTIONS_SCHEMA: vol.Schema = vol.Schema(
{
vol.Optional(
CONF_DB_URL,
): selector.TextSelector(),
vol.Required(
CONF_COLUMN_NAME,
): selector.TextSelector(),
vol.Required(
CONF_QUERY,
): selector.TextSelector(selector.TextSelectorConfig(multiline=True)),
vol.Optional(
CONF_UNIT_OF_MEASUREMENT,
): selector.TextSelector(),
vol.Optional(
CONF_VALUE_TEMPLATE,
): selector.TemplateSelector(),
vol.Optional(CONF_DEVICE_CLASS): selector.SelectSelector(
selector.SelectSelectorConfig(
options=[
cls.value
for cls in SensorDeviceClass
if cls != SensorDeviceClass.ENUM
],
mode=selector.SelectSelectorMode.DROPDOWN,
translation_key="device_class",
sort=True,
)
),
vol.Optional(CONF_STATE_CLASS): selector.SelectSelector(
selector.SelectSelectorConfig(
options=[cls.value for cls in SensorStateClass],
mode=selector.SelectSelectorMode.DROPDOWN,
translation_key="state_class",
sort=True,
)
),
}
)
CONFIG_SCHEMA: vol.Schema = vol.Schema(
{
vol.Required(CONF_NAME, default="Select SQL Query"): selector.TextSelector(),
}
).extend(OPTIONS_SCHEMA.schema)
def validate_sql_select(value: str) -> str:
"""Validate that value is a SQL SELECT query."""
if len(query := sqlparse.parse(value.lstrip().lstrip(";"))) > 1:
raise MultipleResultsFound
if len(query) == 0 or (query_type := query[0].get_type()) == "UNKNOWN":
raise ValueError
if query_type != "SELECT":
_LOGGER.debug("The SQL query %s is of type %s", query, query_type)
raise SQLParseError
return str(query[0])
def validate_query(db_url: str, query: str, column: str) -> bool:
"""Validate SQL query."""
engine = sqlalchemy.create_engine(db_url, future=True)
sessmaker = scoped_session(sessionmaker(bind=engine, future=True))
sess: Session = sessmaker()
try:
result: Result = sess.execute(sqlalchemy.text(query))
except SQLAlchemyError as error:
_LOGGER.debug("Execution error %s", error)
if sess:
sess.close()
engine.dispose()
raise ValueError(error) from error
for res in result.mappings():
if column not in res:
_LOGGER.debug("Column `%s` is not returned by the query", column)
if sess:
sess.close()
engine.dispose()
raise NoSuchColumnError(f"Column {column} is not returned by the query.")
data = res[column]
_LOGGER.debug("Return value from query: %s", data)
if sess:
sess.close()
engine.dispose()
return True
class SQLConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for SQL integration."""
VERSION = 1
@staticmethod
@callback
def async_get_options_flow(
config_entry: ConfigEntry,
) -> SQLOptionsFlowHandler:
"""Get the options flow for this handler."""
return SQLOptionsFlowHandler()
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the user step."""
errors = {}
description_placeholders = {}
if user_input is not None:
db_url = user_input.get(CONF_DB_URL)
query = user_input[CONF_QUERY]
column = user_input[CONF_COLUMN_NAME]
db_url_for_validation = None
try:
query = validate_sql_select(query)
db_url_for_validation = resolve_db_url(self.hass, db_url)
await self.hass.async_add_executor_job(
validate_query, db_url_for_validation, query, column
)
except NoSuchColumnError:
errors["column"] = "column_invalid"
description_placeholders = {"column": column}
except MultipleResultsFound:
errors["query"] = "multiple_queries"
except SQLAlchemyError:
errors["db_url"] = "db_url_invalid"
except SQLParseError:
errors["query"] = "query_no_read_only"
except ValueError as err:
_LOGGER.debug("Invalid query: %s", err)
errors["query"] = "query_invalid"
options = {
CONF_QUERY: query,
CONF_COLUMN_NAME: column,
CONF_NAME: user_input[CONF_NAME],
}
if uom := user_input.get(CONF_UNIT_OF_MEASUREMENT):
options[CONF_UNIT_OF_MEASUREMENT] = uom
if value_template := user_input.get(CONF_VALUE_TEMPLATE):
options[CONF_VALUE_TEMPLATE] = value_template
if device_class := user_input.get(CONF_DEVICE_CLASS):
options[CONF_DEVICE_CLASS] = device_class
if state_class := user_input.get(CONF_STATE_CLASS):
options[CONF_STATE_CLASS] = state_class
if db_url_for_validation != get_instance(self.hass).db_url:
options[CONF_DB_URL] = db_url_for_validation
if not errors:
return self.async_create_entry(
title=user_input[CONF_NAME],
data={},
options=options,
)
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(CONFIG_SCHEMA, user_input),
errors=errors,
description_placeholders=description_placeholders,
)
class SQLOptionsFlowHandler(OptionsFlow):
"""Handle SQL options."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Manage SQL options."""
errors = {}
description_placeholders = {}
if user_input is not None:
db_url = user_input.get(CONF_DB_URL)
query = user_input[CONF_QUERY]
column = user_input[CONF_COLUMN_NAME]
name = self.config_entry.options.get(CONF_NAME, self.config_entry.title)
try:
query = validate_sql_select(query)
db_url_for_validation = resolve_db_url(self.hass, db_url)
await self.hass.async_add_executor_job(
validate_query, db_url_for_validation, query, column
)
except NoSuchColumnError:
errors["column"] = "column_invalid"
description_placeholders = {"column": column}
except MultipleResultsFound:
errors["query"] = "multiple_queries"
except SQLAlchemyError:
errors["db_url"] = "db_url_invalid"
except SQLParseError:
errors["query"] = "query_no_read_only"
except ValueError as err:
_LOGGER.debug("Invalid query: %s", err)
errors["query"] = "query_invalid"
else:
recorder_db = get_instance(self.hass).db_url
_LOGGER.debug(
"db_url: %s, resolved db_url: %s, recorder: %s",
db_url,
db_url_for_validation,
recorder_db,
)
options = {
CONF_QUERY: query,
CONF_COLUMN_NAME: column,
CONF_NAME: name,
}
if uom := user_input.get(CONF_UNIT_OF_MEASUREMENT):
options[CONF_UNIT_OF_MEASUREMENT] = uom
if value_template := user_input.get(CONF_VALUE_TEMPLATE):
options[CONF_VALUE_TEMPLATE] = value_template
if device_class := user_input.get(CONF_DEVICE_CLASS):
options[CONF_DEVICE_CLASS] = device_class
if state_class := user_input.get(CONF_STATE_CLASS):
options[CONF_STATE_CLASS] = state_class
if db_url_for_validation != get_instance(self.hass).db_url:
options[CONF_DB_URL] = db_url_for_validation
return self.async_create_entry(
data=options,
)
return self.async_show_form(
step_id="init",
data_schema=self.add_suggested_values_to_schema(
OPTIONS_SCHEMA, user_input or self.config_entry.options
),
errors=errors,
description_placeholders=description_placeholders,
)

View File

@@ -0,0 +1,12 @@
"""Adds constants for SQL integration."""
import re
from homeassistant.const import Platform
DOMAIN = "sql"
PLATFORMS = [Platform.SENSOR]
CONF_COLUMN_NAME = "column"
CONF_QUERY = "query"
DB_URL_RE = re.compile("//.*:.*@")

View File

@@ -0,0 +1,9 @@
{
"domain": "sql",
"name": "SQL",
"codeowners": ["@gjohansson-ST", "@dougiteixeira"],
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/sql",
"iot_class": "local_polling",
"requirements": ["SQLAlchemy==2.0.36", "sqlparse==0.5.0"]
}

View File

@@ -0,0 +1,17 @@
"""The sql integration models."""
from __future__ import annotations
from dataclasses import dataclass
from sqlalchemy.orm import scoped_session
from homeassistant.core import CALLBACK_TYPE
@dataclass(slots=True)
class SQLData:
"""Data for the sql integration."""
shutdown_event_cancel: CALLBACK_TYPE
session_makers_by_db_url: dict[str, scoped_session]

View File

@@ -0,0 +1,405 @@
"""Sensor from an SQL Query."""
from __future__ import annotations
from datetime import date
import decimal
import logging
from typing import Any
import sqlalchemy
from sqlalchemy import lambda_stmt
from sqlalchemy.engine import Result
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session, scoped_session, sessionmaker
from sqlalchemy.sql.lambdas import StatementLambdaElement
from sqlalchemy.util import LRUCache
from homeassistant.components.recorder import (
CONF_DB_URL,
SupportedDialect,
get_instance,
)
from homeassistant.components.sensor import CONF_STATE_CLASS
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_DEVICE_CLASS,
CONF_ICON,
CONF_NAME,
CONF_UNIQUE_ID,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
EVENT_HOMEASSISTANT_STOP,
MATCH_ALL,
)
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.template import Template
from homeassistant.helpers.trigger_template_entity import (
CONF_AVAILABILITY,
CONF_PICTURE,
ManualTriggerSensorEntity,
)
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN
from .models import SQLData
from .util import redact_credentials, resolve_db_url
_LOGGER = logging.getLogger(__name__)
_SQL_LAMBDA_CACHE: LRUCache = LRUCache(1000)
TRIGGER_ENTITY_OPTIONS = (
CONF_AVAILABILITY,
CONF_DEVICE_CLASS,
CONF_ICON,
CONF_PICTURE,
CONF_UNIQUE_ID,
CONF_STATE_CLASS,
CONF_UNIT_OF_MEASUREMENT,
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the SQL sensor from yaml."""
if (conf := discovery_info) is None:
return
name: Template = conf[CONF_NAME]
query_str: str = conf[CONF_QUERY]
value_template: Template | None = conf.get(CONF_VALUE_TEMPLATE)
column_name: str = conf[CONF_COLUMN_NAME]
unique_id: str | None = conf.get(CONF_UNIQUE_ID)
db_url: str = resolve_db_url(hass, conf.get(CONF_DB_URL))
trigger_entity_config = {CONF_NAME: name}
for key in TRIGGER_ENTITY_OPTIONS:
if key not in conf:
continue
trigger_entity_config[key] = conf[key]
await async_setup_sensor(
hass,
trigger_entity_config,
query_str,
column_name,
value_template,
unique_id,
db_url,
True,
async_add_entities,
)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the SQL sensor from config entry."""
db_url: str = resolve_db_url(hass, entry.options.get(CONF_DB_URL))
name: str = entry.options[CONF_NAME]
query_str: str = entry.options[CONF_QUERY]
template: str | None = entry.options.get(CONF_VALUE_TEMPLATE)
column_name: str = entry.options[CONF_COLUMN_NAME]
value_template: Template | None = None
if template is not None:
try:
value_template = Template(template, hass)
value_template.ensure_valid()
except TemplateError:
value_template = None
name_template = Template(name, hass)
trigger_entity_config = {CONF_NAME: name_template, CONF_UNIQUE_ID: entry.entry_id}
for key in TRIGGER_ENTITY_OPTIONS:
if key not in entry.options:
continue
trigger_entity_config[key] = entry.options[key]
await async_setup_sensor(
hass,
trigger_entity_config,
query_str,
column_name,
value_template,
entry.entry_id,
db_url,
False,
async_add_entities,
)
@callback
def _async_get_or_init_domain_data(hass: HomeAssistant) -> SQLData:
"""Get or initialize domain data."""
if DOMAIN in hass.data:
sql_data: SQLData = hass.data[DOMAIN]
return sql_data
session_makers_by_db_url: dict[str, scoped_session] = {}
#
# Ensure we dispose of all engines at shutdown
# to avoid unclean disconnects
#
# Shutdown all sessions in the executor since they will
# do blocking I/O
#
def _shutdown_db_engines(event: Event) -> None:
"""Shutdown all database engines."""
for sessmaker in session_makers_by_db_url.values():
sessmaker.connection().engine.dispose()
cancel_shutdown = hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, _shutdown_db_engines
)
sql_data = SQLData(cancel_shutdown, session_makers_by_db_url)
hass.data[DOMAIN] = sql_data
return sql_data
async def async_setup_sensor(
hass: HomeAssistant,
trigger_entity_config: ConfigType,
query_str: str,
column_name: str,
value_template: Template | None,
unique_id: str | None,
db_url: str,
yaml: bool,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the SQL sensor."""
try:
instance = get_instance(hass)
except KeyError: # No recorder loaded
uses_recorder_db = False
else:
uses_recorder_db = db_url == instance.db_url
sessmaker: scoped_session | None
sql_data = _async_get_or_init_domain_data(hass)
use_database_executor = False
if uses_recorder_db and instance.dialect_name == SupportedDialect.SQLITE:
use_database_executor = True
assert instance.engine is not None
sessmaker = scoped_session(sessionmaker(bind=instance.engine, future=True))
# For other databases we need to create a new engine since
# we want the connection to use the default timezone and these
# database engines will use QueuePool as its only sqlite that
# needs our custom pool. If there is already a session maker
# for this db_url we can use that so we do not create a new engine
# for every sensor.
elif db_url in sql_data.session_makers_by_db_url:
sessmaker = sql_data.session_makers_by_db_url[db_url]
elif sessmaker := await hass.async_add_executor_job(
_validate_and_get_session_maker_for_db_url, db_url
):
sql_data.session_makers_by_db_url[db_url] = sessmaker
else:
return
upper_query = query_str.upper()
if uses_recorder_db:
redacted_query = redact_credentials(query_str)
issue_key = unique_id if unique_id else redacted_query
# If the query has a unique id and they fix it we can dismiss the issue
# but if it doesn't have a unique id they have to ignore it instead
if (
"ENTITY_ID," in upper_query or "ENTITY_ID " in upper_query
) and "STATES_META" not in upper_query:
_LOGGER.error(
"The query `%s` contains the keyword `entity_id` but does not "
"reference the `states_meta` table. This will cause a full table "
"scan and database instability. Please check the documentation and use "
"`states_meta.entity_id` instead",
redacted_query,
)
ir.async_create_issue(
hass,
DOMAIN,
f"entity_id_query_does_full_table_scan_{issue_key}",
translation_key="entity_id_query_does_full_table_scan",
translation_placeholders={"query": redacted_query},
is_fixable=False,
severity=ir.IssueSeverity.ERROR,
)
raise ValueError(
"Query contains entity_id but does not reference states_meta"
)
ir.async_delete_issue(
hass, DOMAIN, f"entity_id_query_does_full_table_scan_{issue_key}"
)
# MSSQL uses TOP and not LIMIT
if not ("LIMIT" in upper_query or "SELECT TOP" in upper_query):
if "mssql" in db_url:
query_str = upper_query.replace("SELECT", "SELECT TOP 1")
else:
query_str = query_str.replace(";", "") + " LIMIT 1;"
async_add_entities(
[
SQLSensor(
trigger_entity_config,
sessmaker,
query_str,
column_name,
value_template,
yaml,
use_database_executor,
)
],
)
def _validate_and_get_session_maker_for_db_url(db_url: str) -> scoped_session | None:
"""Validate the db_url and return a session maker.
This does I/O and should be run in the executor.
"""
sess: Session | None = None
try:
engine = sqlalchemy.create_engine(db_url, future=True)
sessmaker = scoped_session(sessionmaker(bind=engine, future=True))
# Run a dummy query just to test the db_url
sess = sessmaker()
sess.execute(sqlalchemy.text("SELECT 1;"))
except SQLAlchemyError as err:
_LOGGER.error(
"Couldn't connect using %s DB_URL: %s",
redact_credentials(db_url),
redact_credentials(str(err)),
)
return None
else:
return sessmaker
finally:
if sess:
sess.close()
def _generate_lambda_stmt(query: str) -> StatementLambdaElement:
"""Generate the lambda statement."""
text = sqlalchemy.text(query)
return lambda_stmt(lambda: text, lambda_cache=_SQL_LAMBDA_CACHE)
class SQLSensor(ManualTriggerSensorEntity):
"""Representation of an SQL sensor."""
_unrecorded_attributes = frozenset({MATCH_ALL})
def __init__(
self,
trigger_entity_config: ConfigType,
sessmaker: scoped_session,
query: str,
column: str,
value_template: Template | None,
yaml: bool,
use_database_executor: bool,
) -> None:
"""Initialize the SQL sensor."""
super().__init__(self.hass, trigger_entity_config)
self._query = query
self._template = value_template
self._column_name = column
self.sessionmaker = sessmaker
self._attr_extra_state_attributes = {}
self._use_database_executor = use_database_executor
self._lambda_stmt = _generate_lambda_stmt(query)
if not yaml and (unique_id := trigger_entity_config.get(CONF_UNIQUE_ID)):
self._attr_name = None
self._attr_has_entity_name = True
self._attr_device_info = DeviceInfo(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, unique_id)},
manufacturer="SQL",
name=self._rendered.get(CONF_NAME),
)
@property
def name(self) -> str | None:
"""Name of the entity."""
if self.has_entity_name:
return self._attr_name
return self._rendered.get(CONF_NAME)
async def async_added_to_hass(self) -> None:
"""Call when entity about to be added to hass."""
await super().async_added_to_hass()
await self.async_update()
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return extra attributes."""
return dict(self._attr_extra_state_attributes)
async def async_update(self) -> None:
"""Retrieve sensor data from the query using the right executor."""
if self._use_database_executor:
data = await get_instance(self.hass).async_add_executor_job(self._update)
else:
data = await self.hass.async_add_executor_job(self._update)
self._process_manual_data(data)
def _update(self) -> Any:
"""Retrieve sensor data from the query."""
data = None
self._attr_extra_state_attributes = {}
sess: scoped_session = self.sessionmaker()
try:
result: Result = sess.execute(self._lambda_stmt)
except SQLAlchemyError as err:
_LOGGER.error(
"Error executing query %s: %s",
self._query,
redact_credentials(str(err)),
)
sess.rollback()
sess.close()
return None
for res in result.mappings():
_LOGGER.debug("Query %s result in %s", self._query, res.items())
data = res[self._column_name]
for key, value in res.items():
if isinstance(value, decimal.Decimal):
value = float(value)
elif isinstance(value, date):
value = value.isoformat()
elif isinstance(value, (bytes, bytearray)):
value = f"0x{value.hex()}"
self._attr_extra_state_attributes[key] = value
if data is not None and isinstance(data, (bytes, bytearray)):
data = f"0x{data.hex()}"
if data is not None and self._template is not None:
self._attr_native_value = (
self._template.async_render_with_possible_json_value(data, None)
)
else:
self._attr_native_value = data
if data is None:
_LOGGER.warning("%s returned no results", self._query)
sess.close()
return data

View File

@@ -0,0 +1,141 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]"
},
"error": {
"db_url_invalid": "Database URL invalid",
"query_invalid": "SQL Query invalid",
"query_no_read_only": "SQL query must be read-only",
"multiple_queries": "Multiple SQL queries are not supported",
"column_invalid": "The column `{column}` is not returned by the query"
},
"step": {
"user": {
"data": {
"db_url": "Database URL",
"name": "[%key:common::config_flow::data::name%]",
"query": "Select Query",
"column": "Column",
"unit_of_measurement": "Unit of Measure",
"value_template": "Value Template",
"device_class": "Device Class",
"state_class": "State Class"
},
"data_description": {
"db_url": "Database URL, leave empty to use HA recorder database",
"name": "Name that will be used for Config Entry and also the Sensor",
"query": "Query to run, needs to start with 'SELECT'",
"column": "Column for returned query to present as state",
"unit_of_measurement": "Unit of Measure (optional)",
"value_template": "Value Template (optional)",
"device_class": "The type/class of the sensor to set the icon in the frontend",
"state_class": "The state_class of the sensor"
}
}
}
},
"options": {
"step": {
"init": {
"data": {
"db_url": "[%key:component::sql::config::step::user::data::db_url%]",
"name": "[%key:common::config_flow::data::name%]",
"query": "[%key:component::sql::config::step::user::data::query%]",
"column": "[%key:component::sql::config::step::user::data::column%]",
"unit_of_measurement": "[%key:component::sql::config::step::user::data::unit_of_measurement%]",
"value_template": "[%key:component::sql::config::step::user::data::value_template%]",
"device_class": "[%key:component::sql::config::step::user::data::device_class%]",
"state_class": "[%key:component::sql::config::step::user::data::state_class%]"
},
"data_description": {
"db_url": "[%key:component::sql::config::step::user::data_description::db_url%]",
"name": "[%key:component::sql::config::step::user::data_description::name%]",
"query": "[%key:component::sql::config::step::user::data_description::query%]",
"column": "[%key:component::sql::config::step::user::data_description::column%]",
"unit_of_measurement": "[%key:component::sql::config::step::user::data_description::unit_of_measurement%]",
"value_template": "[%key:component::sql::config::step::user::data_description::value_template%]",
"device_class": "[%key:component::sql::config::step::user::data_description::device_class%]",
"state_class": "[%key:component::sql::config::step::user::data_description::state_class%]"
}
}
},
"error": {
"db_url_invalid": "[%key:component::sql::config::error::db_url_invalid%]",
"query_invalid": "[%key:component::sql::config::error::query_invalid%]",
"query_no_read_only": "[%key:component::sql::config::error::query_no_read_only%]",
"multiple_queries": "[%key:component::sql::config::error::multiple_queries%]",
"column_invalid": "[%key:component::sql::config::error::column_invalid%]"
}
},
"selector": {
"device_class": {
"options": {
"apparent_power": "[%key:component::sensor::entity_component::apparent_power::name%]",
"aqi": "[%key:component::sensor::entity_component::aqi::name%]",
"atmospheric_pressure": "[%key:component::sensor::entity_component::atmospheric_pressure::name%]",
"battery": "[%key:component::sensor::entity_component::battery::name%]",
"carbon_dioxide": "[%key:component::sensor::entity_component::carbon_dioxide::name%]",
"carbon_monoxide": "[%key:component::sensor::entity_component::carbon_monoxide::name%]",
"conductivity": "[%key:component::sensor::entity_component::conductivity::name%]",
"current": "[%key:component::sensor::entity_component::current::name%]",
"data_rate": "[%key:component::sensor::entity_component::data_rate::name%]",
"data_size": "[%key:component::sensor::entity_component::data_size::name%]",
"date": "[%key:component::sensor::entity_component::date::name%]",
"distance": "[%key:component::sensor::entity_component::distance::name%]",
"duration": "[%key:component::sensor::entity_component::duration::name%]",
"energy": "[%key:component::sensor::entity_component::energy::name%]",
"energy_storage": "[%key:component::sensor::entity_component::energy_storage::name%]",
"frequency": "[%key:component::sensor::entity_component::frequency::name%]",
"gas": "[%key:component::sensor::entity_component::gas::name%]",
"humidity": "[%key:component::sensor::entity_component::humidity::name%]",
"illuminance": "[%key:component::sensor::entity_component::illuminance::name%]",
"irradiance": "[%key:component::sensor::entity_component::irradiance::name%]",
"moisture": "[%key:component::sensor::entity_component::moisture::name%]",
"monetary": "[%key:component::sensor::entity_component::monetary::name%]",
"nitrogen_dioxide": "[%key:component::sensor::entity_component::nitrogen_dioxide::name%]",
"nitrogen_monoxide": "[%key:component::sensor::entity_component::nitrogen_monoxide::name%]",
"nitrous_oxide": "[%key:component::sensor::entity_component::nitrous_oxide::name%]",
"ozone": "[%key:component::sensor::entity_component::ozone::name%]",
"ph": "[%key:component::sensor::entity_component::ph::name%]",
"pm1": "[%key:component::sensor::entity_component::pm1::name%]",
"pm10": "[%key:component::sensor::entity_component::pm10::name%]",
"pm25": "[%key:component::sensor::entity_component::pm25::name%]",
"power": "[%key:component::sensor::entity_component::power::name%]",
"power_factor": "[%key:component::sensor::entity_component::power_factor::name%]",
"precipitation": "[%key:component::sensor::entity_component::precipitation::name%]",
"precipitation_intensity": "[%key:component::sensor::entity_component::precipitation_intensity::name%]",
"pressure": "[%key:component::sensor::entity_component::pressure::name%]",
"reactive_power": "[%key:component::sensor::entity_component::reactive_power::name%]",
"signal_strength": "[%key:component::sensor::entity_component::signal_strength::name%]",
"sound_pressure": "[%key:component::sensor::entity_component::sound_pressure::name%]",
"speed": "[%key:component::sensor::entity_component::speed::name%]",
"sulphur_dioxide": "[%key:component::sensor::entity_component::sulphur_dioxide::name%]",
"temperature": "[%key:component::sensor::entity_component::temperature::name%]",
"timestamp": "[%key:component::sensor::entity_component::timestamp::name%]",
"volatile_organic_compounds": "[%key:component::sensor::entity_component::volatile_organic_compounds::name%]",
"volatile_organic_compounds_parts": "[%key:component::sensor::entity_component::volatile_organic_compounds::name%]",
"voltage": "[%key:component::sensor::entity_component::voltage::name%]",
"volume": "[%key:component::sensor::entity_component::volume::name%]",
"volume_flow_rate": "[%key:component::sensor::entity_component::volume_flow_rate::name%]",
"volume_storage": "[%key:component::sensor::entity_component::volume_storage::name%]",
"water": "[%key:component::sensor::entity_component::water::name%]",
"weight": "[%key:component::sensor::entity_component::weight::name%]",
"wind_speed": "[%key:component::sensor::entity_component::wind_speed::name%]"
}
},
"state_class": {
"options": {
"measurement": "[%key:component::sensor::entity_component::_::state_attributes::state_class::state::measurement%]",
"total": "[%key:component::sensor::entity_component::_::state_attributes::state_class::state::total%]",
"total_increasing": "[%key:component::sensor::entity_component::_::state_attributes::state_class::state::total_increasing%]"
}
}
},
"issues": {
"entity_id_query_does_full_table_scan": {
"title": "SQL query does full table scan",
"description": "The query `{query}` contains the keyword `entity_id` but does not reference the `states_meta` table. This will cause a full table scan and database instability. Please check the documentation and use `states_meta.entity_id` instead."
}
}
}

View File

@@ -0,0 +1,27 @@
"""Utils for sql."""
from __future__ import annotations
import logging
from homeassistant.components.recorder import get_instance
from homeassistant.core import HomeAssistant
from .const import DB_URL_RE
_LOGGER = logging.getLogger(__name__)
def redact_credentials(data: str | None) -> str:
"""Redact credentials from string data."""
if not data:
return "none"
return DB_URL_RE.sub("//****:****@", data)
def resolve_db_url(hass: HomeAssistant, db_url: str | None) -> str:
"""Return the db_url provided if not empty, otherwise return the recorder db_url."""
_LOGGER.debug("db_url: %s", redact_credentials(db_url))
if db_url and not db_url.isspace():
return db_url
return get_instance(hass).db_url