diff --git a/homeassistant/components/recorder/purge.py b/homeassistant/components/recorder/purge.py index fee4480e134..43e84785f7d 100644 --- a/homeassistant/components/recorder/purge.py +++ b/homeassistant/components/recorder/purge.py @@ -68,6 +68,7 @@ def purge_old_data(instance, purge_days: int, repack: bool) -> bool: deleted_rows = ( session.query(RecorderRuns) .filter(RecorderRuns.start < purge_before) + .filter(RecorderRuns.run_id != instance.run_info.run_id) .delete(synchronize_session=False) ) _LOGGER.debug("Deleted %s recorder_runs", deleted_rows) diff --git a/tests/components/recorder/test_purge.py b/tests/components/recorder/test_purge.py index 91a2299e4b6..9cb07819e79 100644 --- a/tests/components/recorder/test_purge.py +++ b/tests/components/recorder/test_purge.py @@ -62,6 +62,22 @@ def test_purge_old_events(hass, hass_recorder): assert events.count() == 2 +def test_purge_old_recorder_runs(hass, hass_recorder): + """Test deleting old recorder runs keeps current run.""" + hass = hass_recorder() + _add_test_recorder_runs(hass) + + # make sure we start with 7 recorder runs + with session_scope(hass=hass) as session: + recorder_runs = session.query(RecorderRuns) + assert recorder_runs.count() == 7 + + # run purge_old_data() + finished = purge_old_data(hass.data[DATA_INSTANCE], 0, repack=False) + assert finished + assert recorder_runs.count() == 1 + + def test_purge_method(hass, hass_recorder): """Test purge method.""" hass = hass_recorder()