diff --git a/homeassistant/components/sql/sensor.py b/homeassistant/components/sql/sensor.py index 8609e2c17c2..0b5e6be6ab9 100644 --- a/homeassistant/components/sql/sensor.py +++ b/homeassistant/components/sql/sensor.py @@ -261,15 +261,12 @@ async def async_setup_sensor( # MSSQL uses TOP and not LIMIT mod_query_template = query_template - if "LIMIT" not in upper_query and not upper_query.startswith("SELECT TOP"): + if not ("LIMIT" in upper_query or "SELECT TOP" in upper_query): if "mssql" in db_url: - mod_query_template = ValueTemplate( - f"SELECT TOP 1{query_template.template[6:]}", hass - ) + _query = query_template.template.replace("SELECT", "SELECT TOP 1") else: - mod_query_template = ValueTemplate( - f"{query_template.template.replace(';', '')} LIMIT 1;", hass - ) + _query = query_template.template.replace(";", "") + " LIMIT 1;" + mod_query_template = ValueTemplate(_query, hass) async_add_entities( [ @@ -386,7 +383,7 @@ class SQLSensor(ManualTriggerSensorEntity): rendered_query = check_and_render_sql_query(self.hass, self._query) _lambda_stmt = _generate_lambda_stmt(rendered_query) result: Result = sess.execute(_lambda_stmt) - except TemplateError as err: + except ValueError as err: _LOGGER.error( "Error rendering query %s: %s", redact_credentials(self._query.template), diff --git a/tests/components/sql/test_sensor.py b/tests/components/sql/test_sensor.py index ffb9cee967b..ccc7376b610 100644 --- a/tests/components/sql/test_sensor.py +++ b/tests/components/sql/test_sensor.py @@ -155,6 +155,40 @@ async def test_broken_template_query( assert not state +async def test_broken_template_query_2( + recorder_mock: Recorder, + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the SQL sensor with a query template.""" + hass.states.async_set("sensor.input1", "5") + await hass.async_block_till_done(wait_background_tasks=True) + + config = { + "db_url": "sqlite://", + "query": "SELECT {{ states.sensor.input1.state | int / 1000}} as value", + "column": "value", + "name": "count_tables", + } + await init_integration(hass, config) + + state = hass.states.get("sensor.count_tables") + assert state.state == "0.005" + + hass.states.async_set("sensor.input1", "on") + freezer.tick(timedelta(minutes=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + state = hass.states.get("sensor.count_tables") + assert state.state == "0.005" + assert ( + "Error rendering query SELECT {{ states.sensor.input1.state" + " | int / 1000}} as value LIMIT 1;: Invalid template" in caplog.text + ) + + async def test_query_limit(recorder_mock: Recorder, hass: HomeAssistant) -> None: """Test the SQL sensor with a query containing 'LIMIT' in lowercase.""" config = {