// updated in a long time
states_alias = orm.aliased(States, name="StatesAlias")
protected_states = session.query(States.state_id, States.event_id)\
.filter(~exists()
.where(States.entity_id ==
states_alias.entity_id)
.where(states_alias.last_updated >
States.last_updated))\
.all()
After Change
// For each entity, the most recent state is protected from deletion
// s.t. we can properly restore state even if the entity has not been
// updated in a long time
protected_states = session.query(func.max(States.state_id)) \
.group_by(States.entity_id).all()
protected_state_ids = tuple((state[0] for state in protected_states))
deleted_rows = session.query(States) \
.filter((States.last_updated < purge_before)) \
.filter(~States.state_id.in_(
protected_state_ids)) \
.delete(synchronize_session=False)
_LOGGER.debug("Deleted %s states", deleted_rows)
// We also need to protect the events belonging to the protected states.
// Otherwise, if the SQL server has "ON DELETE CASCADE" as default, it
// will delete the protected state when deleting its associated
// event. Also, we would be producing NULLed foreign keys otherwise.
protected_events = session.query(States.event_id) \
.filter(States.state_id.in_(protected_state_ids)) \
.filter(States.event_id.isnot(None)) \
.all()
protected_event_ids = tuple((state[0] for state in protected_events))
deleted_rows = session.query(Events) \