2022-04-24 18:50:32 +00:00
|
|
|
"""Adds config flow for SQL integration."""
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import logging
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
import sqlalchemy
|
|
|
|
from sqlalchemy.engine import Result
|
2023-04-15 22:54:56 +00:00
|
|
|
from sqlalchemy.exc import NoSuchColumnError, SQLAlchemyError
|
2023-02-08 14:17:32 +00:00
|
|
|
from sqlalchemy.orm import Session, scoped_session, sessionmaker
|
2022-04-24 18:50:32 +00:00
|
|
|
import voluptuous as vol
|
|
|
|
|
|
|
|
from homeassistant import config_entries
|
2023-05-01 14:17:01 +00:00
|
|
|
from homeassistant.components.recorder import CONF_DB_URL, get_instance
|
2022-04-24 18:50:32 +00:00
|
|
|
from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE
|
2022-05-12 23:40:00 +00:00
|
|
|
from homeassistant.core import callback
|
2022-04-24 18:50:32 +00:00
|
|
|
from homeassistant.data_entry_flow import FlowResult
|
|
|
|
from homeassistant.helpers import selector
|
|
|
|
|
|
|
|
from .const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN
|
2023-03-14 03:41:32 +00:00
|
|
|
from .util import resolve_db_url
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2023-04-12 19:03:14 +00:00
|
|
|
OPTIONS_SCHEMA: vol.Schema = vol.Schema(
|
2022-04-24 18:50:32 +00:00
|
|
|
{
|
2023-04-12 19:03:14 +00:00
|
|
|
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(),
|
2022-04-24 18:50:32 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2023-04-12 19:03:14 +00:00
|
|
|
CONFIG_SCHEMA: vol.Schema = vol.Schema(
|
|
|
|
{
|
|
|
|
vol.Required(CONF_NAME, default="Select SQL Query"): selector.TextSelector(),
|
|
|
|
}
|
|
|
|
).extend(OPTIONS_SCHEMA.schema)
|
|
|
|
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
def validate_sql_select(value: str) -> str | None:
|
|
|
|
"""Validate that value is a SQL SELECT query."""
|
|
|
|
if not value.lstrip().lower().startswith("select"):
|
|
|
|
raise ValueError("Incorrect Query")
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
def validate_query(db_url: str, query: str, column: str) -> bool:
|
|
|
|
"""Validate SQL query."""
|
|
|
|
|
2022-05-12 23:40:00 +00:00
|
|
|
engine = sqlalchemy.create_engine(db_url, future=True)
|
|
|
|
sessmaker = scoped_session(sessionmaker(bind=engine, future=True))
|
2023-02-08 14:17:32 +00:00
|
|
|
sess: Session = sessmaker()
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
try:
|
2022-05-12 03:45:47 +00:00
|
|
|
result: Result = sess.execute(sqlalchemy.text(query))
|
2022-04-24 18:50:32 +00:00
|
|
|
except SQLAlchemyError as error:
|
2022-05-12 23:40:00 +00:00
|
|
|
_LOGGER.debug("Execution error %s", error)
|
2022-04-24 18:50:32 +00:00
|
|
|
if sess:
|
|
|
|
sess.close()
|
2023-04-15 22:54:56 +00:00
|
|
|
engine.dispose()
|
2022-04-24 18:50:32 +00:00
|
|
|
raise ValueError(error) from error
|
|
|
|
|
2022-05-12 23:40:00 +00:00
|
|
|
for res in result.mappings():
|
2023-04-15 22:54:56 +00:00
|
|
|
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.")
|
|
|
|
|
2022-05-12 23:40:00 +00:00
|
|
|
data = res[column]
|
|
|
|
_LOGGER.debug("Return value from query: %s", data)
|
|
|
|
|
2022-04-24 18:50:32 +00:00
|
|
|
if sess:
|
|
|
|
sess.close()
|
2023-04-13 00:24:55 +00:00
|
|
|
engine.dispose()
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
class SQLConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|
|
|
"""Handle a config flow for SQL integration."""
|
|
|
|
|
|
|
|
VERSION = 1
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
@callback
|
|
|
|
def async_get_options_flow(
|
|
|
|
config_entry: config_entries.ConfigEntry,
|
|
|
|
) -> SQLOptionsFlowHandler:
|
|
|
|
"""Get the options flow for this handler."""
|
|
|
|
return SQLOptionsFlowHandler(config_entry)
|
|
|
|
|
|
|
|
async def async_step_user(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
|
|
|
"""Handle the user step."""
|
|
|
|
errors = {}
|
2023-04-15 22:54:56 +00:00
|
|
|
description_placeholders = {}
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
if user_input is not None:
|
2023-03-14 03:41:32 +00:00
|
|
|
db_url = user_input.get(CONF_DB_URL)
|
2022-04-24 18:50:32 +00:00
|
|
|
query = user_input[CONF_QUERY]
|
|
|
|
column = user_input[CONF_COLUMN_NAME]
|
|
|
|
uom = user_input.get(CONF_UNIT_OF_MEASUREMENT)
|
|
|
|
value_template = user_input.get(CONF_VALUE_TEMPLATE)
|
2022-04-29 17:00:44 +00:00
|
|
|
name = user_input[CONF_NAME]
|
2023-03-14 03:41:32 +00:00
|
|
|
db_url_for_validation = None
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
validate_sql_select(query)
|
2023-03-14 03:41:32 +00:00
|
|
|
db_url_for_validation = resolve_db_url(self.hass, db_url)
|
2022-04-24 18:50:32 +00:00
|
|
|
await self.hass.async_add_executor_job(
|
2023-03-14 03:41:32 +00:00
|
|
|
validate_query, db_url_for_validation, query, column
|
2022-04-24 18:50:32 +00:00
|
|
|
)
|
2023-04-15 22:54:56 +00:00
|
|
|
except NoSuchColumnError:
|
|
|
|
errors["column"] = "column_invalid"
|
|
|
|
description_placeholders = {"column": column}
|
2022-04-24 18:50:32 +00:00
|
|
|
except SQLAlchemyError:
|
|
|
|
errors["db_url"] = "db_url_invalid"
|
|
|
|
except ValueError:
|
|
|
|
errors["query"] = "query_invalid"
|
|
|
|
|
2023-03-14 03:41:32 +00:00
|
|
|
add_db_url = (
|
|
|
|
{CONF_DB_URL: db_url} if db_url == db_url_for_validation else {}
|
|
|
|
)
|
|
|
|
|
2022-04-24 18:50:32 +00:00
|
|
|
if not errors:
|
|
|
|
return self.async_create_entry(
|
|
|
|
title=name,
|
|
|
|
data={},
|
|
|
|
options={
|
2023-03-14 03:41:32 +00:00
|
|
|
**add_db_url,
|
2022-04-24 18:50:32 +00:00
|
|
|
CONF_QUERY: query,
|
|
|
|
CONF_COLUMN_NAME: column,
|
|
|
|
CONF_UNIT_OF_MEASUREMENT: uom,
|
|
|
|
CONF_VALUE_TEMPLATE: value_template,
|
|
|
|
CONF_NAME: name,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
return self.async_show_form(
|
|
|
|
step_id="user",
|
2023-04-12 19:03:14 +00:00
|
|
|
data_schema=self.add_suggested_values_to_schema(CONFIG_SCHEMA, user_input),
|
2022-04-24 18:50:32 +00:00
|
|
|
errors=errors,
|
2023-04-15 22:54:56 +00:00
|
|
|
description_placeholders=description_placeholders,
|
2022-04-24 18:50:32 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2023-05-01 14:17:01 +00:00
|
|
|
class SQLOptionsFlowHandler(config_entries.OptionsFlowWithConfigEntry):
|
2022-04-24 18:50:32 +00:00
|
|
|
"""Handle SQL options."""
|
|
|
|
|
|
|
|
async def async_step_init(
|
|
|
|
self, user_input: dict[str, Any] | None = None
|
|
|
|
) -> FlowResult:
|
|
|
|
"""Manage SQL options."""
|
|
|
|
errors = {}
|
2023-04-15 22:54:56 +00:00
|
|
|
description_placeholders = {}
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
if user_input is not None:
|
2023-03-14 03:41:32 +00:00
|
|
|
db_url = user_input.get(CONF_DB_URL)
|
2022-04-24 18:50:32 +00:00
|
|
|
query = user_input[CONF_QUERY]
|
|
|
|
column = user_input[CONF_COLUMN_NAME]
|
2023-05-01 14:17:01 +00:00
|
|
|
name = self.options.get(CONF_NAME, self.config_entry.title)
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
validate_sql_select(query)
|
2023-03-14 03:41:32 +00:00
|
|
|
db_url_for_validation = resolve_db_url(self.hass, db_url)
|
2022-04-24 18:50:32 +00:00
|
|
|
await self.hass.async_add_executor_job(
|
2023-03-14 03:41:32 +00:00
|
|
|
validate_query, db_url_for_validation, query, column
|
2022-04-24 18:50:32 +00:00
|
|
|
)
|
2023-04-15 22:54:56 +00:00
|
|
|
except NoSuchColumnError:
|
|
|
|
errors["column"] = "column_invalid"
|
|
|
|
description_placeholders = {"column": column}
|
2022-04-24 18:50:32 +00:00
|
|
|
except SQLAlchemyError:
|
|
|
|
errors["db_url"] = "db_url_invalid"
|
|
|
|
except ValueError:
|
|
|
|
errors["query"] = "query_invalid"
|
|
|
|
else:
|
2023-05-01 14:17:01 +00:00
|
|
|
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,
|
|
|
|
)
|
|
|
|
if db_url and db_url_for_validation == recorder_db:
|
|
|
|
user_input.pop(CONF_DB_URL)
|
2022-05-07 21:18:40 +00:00
|
|
|
return self.async_create_entry(
|
|
|
|
data={
|
2022-09-28 06:49:37 +00:00
|
|
|
CONF_NAME: name,
|
2023-05-01 14:17:01 +00:00
|
|
|
**user_input,
|
2022-05-07 21:18:40 +00:00
|
|
|
},
|
|
|
|
)
|
2022-04-24 18:50:32 +00:00
|
|
|
|
|
|
|
return self.async_show_form(
|
|
|
|
step_id="init",
|
2023-04-12 19:03:14 +00:00
|
|
|
data_schema=self.add_suggested_values_to_schema(
|
2023-05-01 14:17:01 +00:00
|
|
|
OPTIONS_SCHEMA, user_input or self.options
|
2022-04-24 18:50:32 +00:00
|
|
|
),
|
|
|
|
errors=errors,
|
2023-04-15 22:54:56 +00:00
|
|
|
description_placeholders=description_placeholders,
|
2022-04-24 18:50:32 +00:00
|
|
|
)
|