rebuild consumpton baselaline
Some checks failed
CI and deploy / migration-check (push) Failing after 10s
CI and deploy / deploy (push) Has been skipped

This commit is contained in:
Dusan Vojacek
2026-05-02 13:56:35 +02:00
parent b20cb6e0f9
commit 343f2f9847
7 changed files with 262 additions and 3 deletions

View File

@@ -78,7 +78,8 @@ $$;
COMMENT ON FUNCTION ems.fn_update_baseline_stats(INT, INT) IS
'Aktualizuje průměry bazální spotřeby z telemetrie posledních N dní.
Používá exponenciální klouzavý průměr (EMA 70/30) pro postupné zpřesňování.
Volat denně po půlnoci. Pro první naplnění: fn_update_baseline_stats(2, 90).';
Volat denně po půlnoci. Pro první naplnění: fn_update_baseline_stats(2, 90).
Pro úplný reset bucketů bez „ocasu“ EMA smaž řádky a znovu volej, nebo ems.fn_rebuild_consumption_baseline_stats.';
CREATE OR REPLACE FUNCTION ems.fn_get_baseline_forecast(

View File

@@ -0,0 +1,54 @@
-- Přepnutí profilu bazální spotřeby bez EMA ocasu z předchozích běhů:
-- smaže řádky consumption_baseline_stats a znovu je naplní fn_update_baseline_stats.
create or replace function ems.fn_rebuild_consumption_baseline_stats(
p_site_id int default null,
p_lookback_days int default 30
)
returns table (
site_id int,
buckets_upserted int
)
language plpgsql
volatile
as $fn$
declare
r record;
begin
if p_lookback_days is null or p_lookback_days < 1 then
raise exception using
message = 'p_lookback_days musí být kladný int (např. 30)',
errcode = '22023';
end if;
if p_site_id is null then
delete from ems.consumption_baseline_stats;
for r in
select s.id as sid from ems.site s order by s.id
loop
site_id := r.sid::int;
buckets_upserted := ems.fn_update_baseline_stats(r.sid::int, p_lookback_days);
return next;
end loop;
return;
end if;
if not exists (select 1 from ems.site s where s.id = p_site_id) then
raise exception using
message = format('site_id %s neexistuje v ems.site', p_site_id),
errcode = 'P0001';
end if;
delete from ems.consumption_baseline_stats c
where c.site_id = p_site_id;
site_id := p_site_id;
buckets_upserted := ems.fn_update_baseline_stats(p_site_id, p_lookback_days);
return next;
end;
$fn$;
comment on function ems.fn_rebuild_consumption_baseline_stats is
'Maze řádky v consumption_baseline_stats pro jednu site (nenull p_site_id) nebo celou tabulku při p_site_id NULL, pak pro každý ems.site volá fn_update_baseline_stats. Řeší zaseknutí starého avg díky EMA 70/30 v fn_update. Příklad jedné lokality: select * from ems.fn_rebuild_consumption_baseline_stats(2, 30); všechny lokality: select * from ems.fn_rebuild_consumption_baseline_stats(null::int, 14); Nepředávej jen jednu číslici bez pojmenovaných argumentů — první pozice je site_id ne lookback.';