Convert decimals from SQL results (#13059)

This commit is contained in:
Paulus Schoutsen 2018-03-10 10:40:28 -08:00 committed by GitHub
parent ae47da7bce
commit 0e00de8a33
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 4 deletions

View file

@ -4,6 +4,7 @@ Sensor from an SQL Query.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.sql/
"""
import decimal
import logging
import voluptuous as vol
@ -131,17 +132,20 @@ class SQLSensor(Entity):
try:
sess = self.sessionmaker()
result = sess.execute(self._query)
self._attributes = {}
if not result.returns_rows or result.rowcount == 0:
_LOGGER.warning("%s returned no results", self._query)
self._state = None
self._attributes = {}
return
for res in result:
_LOGGER.debug("result = %s", res.items())
data = res[self._column_name]
self._attributes = {k: v for k, v in res.items()}
for key, value in res.items():
if isinstance(value, decimal.Decimal):
value = float(decimal)
self._attributes[key] = value
except sqlalchemy.exc.SQLAlchemyError as err:
_LOGGER.error("Error executing query %s: %s", self._query, err)
return

View file

@ -29,7 +29,7 @@ class TestSQLSensor(unittest.TestCase):
'db_url': 'sqlite://',
'queries': [{
'name': 'count_tables',
'query': 'SELECT count(*) value FROM sqlite_master;',
'query': 'SELECT 5 as value',
'column': 'value',
}]
}
@ -38,7 +38,8 @@ class TestSQLSensor(unittest.TestCase):
assert setup_component(self.hass, 'sensor', config)
state = self.hass.states.get('sensor.count_tables')
self.assertEqual(state.state, '0')
assert state.state == '5'
assert state.attributes['value'] == 5
def test_invalid_query(self):
"""Test the SQL sensor for invalid queries."""