Fix db_url issue in SQL (#92324)
* db_url fix * Add test * assert entry.options
This commit is contained in:
parent
7b5d26d3fa
commit
9795699669
5 changed files with 145 additions and 20 deletions
|
@ -1,6 +1,8 @@
|
|||
"""The sql component."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.recorder import CONF_DB_URL, get_instance
|
||||
|
@ -24,6 +26,9 @@ import homeassistant.helpers.config_validation as cv
|
|||
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:
|
||||
|
@ -85,6 +90,11 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||
|
||||
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)
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ from sqlalchemy.orm import Session, scoped_session, sessionmaker
|
|||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.recorder import CONF_DB_URL
|
||||
from homeassistant.components.recorder import CONF_DB_URL, get_instance
|
||||
from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.data_entry_flow import FlowResult
|
||||
|
@ -159,13 +159,9 @@ class SQLConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||
)
|
||||
|
||||
|
||||
class SQLOptionsFlowHandler(config_entries.OptionsFlow):
|
||||
class SQLOptionsFlowHandler(config_entries.OptionsFlowWithConfigEntry):
|
||||
"""Handle SQL options."""
|
||||
|
||||
def __init__(self, entry: config_entries.ConfigEntry) -> None:
|
||||
"""Initialize SQL options flow."""
|
||||
self.entry = entry
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> FlowResult:
|
||||
|
@ -177,7 +173,7 @@ class SQLOptionsFlowHandler(config_entries.OptionsFlow):
|
|||
db_url = user_input.get(CONF_DB_URL)
|
||||
query = user_input[CONF_QUERY]
|
||||
column = user_input[CONF_COLUMN_NAME]
|
||||
name = self.entry.options.get(CONF_NAME, self.entry.title)
|
||||
name = self.options.get(CONF_NAME, self.config_entry.title)
|
||||
|
||||
try:
|
||||
validate_sql_select(query)
|
||||
|
@ -193,21 +189,26 @@ class SQLOptionsFlowHandler(config_entries.OptionsFlow):
|
|||
except ValueError:
|
||||
errors["query"] = "query_invalid"
|
||||
else:
|
||||
new_user_input = user_input
|
||||
if new_user_input.get(CONF_DB_URL) and db_url == db_url_for_validation:
|
||||
new_user_input.pop(CONF_DB_URL)
|
||||
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)
|
||||
return self.async_create_entry(
|
||||
title="",
|
||||
data={
|
||||
CONF_NAME: name,
|
||||
**new_user_input,
|
||||
**user_input,
|
||||
},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="init",
|
||||
data_schema=self.add_suggested_values_to_schema(
|
||||
OPTIONS_SCHEMA, user_input or self.entry.options
|
||||
OPTIONS_SCHEMA, user_input or self.options
|
||||
),
|
||||
errors=errors,
|
||||
description_placeholders=description_placeholders,
|
||||
|
|
|
@ -42,20 +42,15 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
|||
from homeassistant.helpers.template import Template
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
|
||||
from .const import CONF_COLUMN_NAME, CONF_QUERY, DB_URL_RE, DOMAIN
|
||||
from .const import CONF_COLUMN_NAME, CONF_QUERY, DOMAIN
|
||||
from .models import SQLData
|
||||
from .util import resolve_db_url
|
||||
from .util import redact_credentials, resolve_db_url
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_SQL_LAMBDA_CACHE: LRUCache = LRUCache(1000)
|
||||
|
||||
|
||||
def redact_credentials(data: str) -> str:
|
||||
"""Redact credentials from string data."""
|
||||
return DB_URL_RE.sub("//****:****@", data)
|
||||
|
||||
|
||||
async def async_setup_platform(
|
||||
hass: HomeAssistant,
|
||||
config: ConfigType,
|
||||
|
|
|
@ -1,12 +1,26 @@
|
|||
"""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
|
||||
|
|
|
@ -464,3 +464,108 @@ async def test_options_flow_db_url_empty(
|
|||
"column": "size",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
|
||||
async def test_full_flow_not_recorder_db(
|
||||
recorder_mock: Recorder, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test full config flow with not using recorder db."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["errors"] == {}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
), patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"name": "Get Value",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result2["title"] == "Get Value"
|
||||
assert result2["options"] == {
|
||||
"name": "Get Value",
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": None,
|
||||
"value_template": None,
|
||||
}
|
||||
|
||||
entry = hass.config_entries.async_entries(DOMAIN)[0]
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result["type"] == FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.sql.async_setup_entry",
|
||||
return_value=True,
|
||||
), patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value",
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MiB",
|
||||
}
|
||||
|
||||
# Need to test same again to mitigate issue with db_url removal
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
with patch(
|
||||
"homeassistant.components.sql.config_flow.sqlalchemy.create_engine",
|
||||
):
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
"query": "SELECT 5 as value",
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MB",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] == FlowResultType.CREATE_ENTRY
|
||||
assert result["data"] == {
|
||||
"name": "Get Value",
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MB",
|
||||
}
|
||||
|
||||
assert entry.options == {
|
||||
"name": "Get Value",
|
||||
"db_url": "sqlite://path/to/db.db",
|
||||
"query": "SELECT 5 as value",
|
||||
"column": "value",
|
||||
"unit_of_measurement": "MB",
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue