Skip to content

Commit

Permalink
Fix possible integrity error
Browse files Browse the repository at this point in the history
IntegrityError can occurr if there is a registered state (StatesMeta
table) but no states (States table) yet.
  • Loading branch information
ldotlopez committed Jun 21, 2023
1 parent a9878a2 commit 7e2e151
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
14 changes: 12 additions & 2 deletions homeassistant_historical_sensor/recorderutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 4 additions & 4 deletions homeassistant_historical_sensor/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = homeassistant-historical-sensor
version = 1.0.0
version = 1.0.1
author = Luis López
author_email = [email protected]
description = Historical sensors for HomeAssistant
Expand Down

0 comments on commit 7e2e151

Please sign in to comment.