Hi,
I have the same issue. On Jun 18th I lost all my energy data, but now I know how to recover.
1. Important (I missed that and corrupted my db a couple times): STOP HA Core in ssh with “ha core stop” or via service call!
2. download the current home-assistant_v2.db and home-assistant_v2.db.corrupt.* databases and open the current db in SQLite Browser and attach also the corrupt database as corrupt
3. As some statistics_meta record could be missing, get those from corrupt db:
-- insert possibly missing statistics_meta records
insert into statistics_meta
select row_number() over () + (select max(id) from statistics_meta) as id, c.statistic_id, c.source, c.unit_of_measurement, c.has_mean, c.has_sum, c.name
from corrupt.statistics_meta c
left outer join statistics_meta m on m.statistic_id = c.statistic_id
where m.id is null;
4. Before inserting the records, update the id column of the existing data:
-- move existing ids, as all corrupt records are older
update statistics
set id = id + (select max(id) from corrupt.statistics);
5. Now, the statistics table is missing all those records from the corrupt database, so we import those with this sql:
-- import statistics from corrupt db
insert into statistics
select c.id, c.created, c.created_ts, m.new_id as metadata_id, c.start, c.start_ts, c.mean, c.min, c.max, c.last_reset, c.last_reset_ts, c.state, c.sum
from corrupt.statistics c
inner join (
select o.id as old_id
, n.id as new_id
, case when row_number() over (partition by o.id) > 1 or row_number() over (partition by n.id) > 1 then 0 else 1 end as test
from corrupt.statistics_meta o
inner join statistics_meta n on n.statistic_id = o.statistic_id
) m on m.old_id = c.metadata_id and m.test = 1
6. As the sum is incorrect for new values in current db, we update those as well:
-- update sum values causing mega negative values for day of corruption in Energy Dashboard
update statistics
set sum = sum + a.add_sum
from (
select s.id, a.statistic_id, sum(a.lag_sum) as add_sum
from statistics s
inner join (
select *
from (
select m.statistic_id, s.*, lag(s.sum) over (partition by s.metadata_id order by s.start_ts) as lag_sum
from statistics s
inner join statistics_meta m on m.id = s.metadata_id
where s.sum is not null
) t
where t.sum < t.lag_sum
) a on a.metadata_id = s.metadata_id and s.start_ts >= a.start_ts
group by s.id, a.statistic_id
) a
where a.id = statistics.id
7. Rebuild statistics_short_term from today’s statistics - it is needed so new statistic records have correct sum value
-- rebuild statistics_short_term
delete from statistics_short_term;
insert into statistics_short_term
select row_number() over () as id, c.created, c.created_ts, c.metadata_id, c.start, c.start_ts, c.mean, c.min, c.max, c.last_reset, c.last_reset_ts, c.state, c.sum
from statistics c
where date(c.start_ts, 'unixepoch') = DATE('now')
order by c.start_ts, c.id;
8. Start ha core again
All my history in Energy Dashboard is now back again - running smooth for many hours now…