diff --git a/homeassistant_historical_sensor/recorderutil.py b/homeassistant_historical_sensor/recorderutil.py index e7d401d..4e2d981 100644 --- a/homeassistant_historical_sensor/recorderutil.py +++ b/homeassistant_historical_sensor/recorderutil.py @@ -70,10 +70,20 @@ def _entity_id_states_stmt(session: Session, entity: Entity) -> Select: def get_entity_states_meta(session: Session, entity: Entity) -> db_schema.StatesMeta: - res = session.execute(_entity_id_states_stmt(session, entity)).scalar() + # Don't re-use _entity_id_states_stmt. + # It's posible to have a StatesMeta for the current entity but zero States in the + # database. + # In that case the _entity_id_states_stmt will return zero rows but it doesn't mean + # that we need to create a new StatesMeta + + res = session.execute( + select(db_schema.StatesMeta).where( + db_schema.StatesMeta.entity_id == entity.entity_id + ) + ).scalar() if res: - return res.states_meta_rel + return res else: ret = db_schema.StatesMeta(entity_id=entity.entity_id) diff --git a/homeassistant_historical_sensor/sensor.py b/homeassistant_historical_sensor/sensor.py index 24b8538..51c41e0 100644 --- a/homeassistant_historical_sensor/sensor.py +++ b/homeassistant_historical_sensor/sensor.py @@ -310,10 +310,10 @@ async def _async_write_statistic_data( hist_states, latest=latest ) - for stat in statistics_data: - tmp = dict(stat) - start_dt = dtutil.as_local(tmp.pop("start")) - _LOGGER.debug(f"new statistic: start={start_dt}, value={tmp!r}") + # for stat in statistics_data: + # tmp = dict(stat) + # start_dt = dtutil.as_local(tmp.pop("start")) + # _LOGGER.debug(f"new statistic: start={start_dt}, value={tmp!r}") if valid_statistic_id(self.statatistic_id): async_add_external_statistics(self.hass, statistics_meta, statistics_data) diff --git a/setup.cfg b/setup.cfg index 93075bc..0de256f 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [metadata] name = homeassistant-historical-sensor -version = 1.0.0 +version = 1.0.1 author = Luis López author_email = luis@cuarentaydos.com description = Historical sensors for HomeAssistant