diff --git a/schema/create.sql b/schema/create.sql index cc689ad..cca7b07 100644 --- a/schema/create.sql +++ b/schema/create.sql @@ -49,14 +49,26 @@ create or replace function pv_stats_func () language plpgsql as $$ declare + v_stat_id pv_stats_t.id%TYPE; v_dateTypes varchar[] := array['day', 'month', 'year']; v_dateType varchar; begin foreach v_dateType in array v_dateTypes loop - insert into pv_stats_t("date", dateType, first, total) - values (date_trunc(v_dateType, NEW.time::date), v_dateType, NEW.exportEnergyActive, 0) - on conflict on constraint ddT_uk do update set total = NEW.exportEnergyActive - excluded.first; + select id + from pv_stats_t + into v_stat_id + where "date" = date_trunc(v_dateType, NEW.time::date) and + dateType = v_dateType; + if not found then + insert into pv_stats_t ("date", dateType, first) + values (date_trunc(v_dateType, NEW.time::date), v_dateType, NEW.exportEnergyActive); + else + update pv_stats_t + set total = NEW.exportEnergyActive - first + where id = v_stat_id; + end if; + end loop; return NEW; @@ -70,7 +82,7 @@ create trigger pv_stats_trig -insert into pv_stats_t("date", dateType, first, total) values ('2023-12-12', 'day', 12, 0) - on conflict on constraint ddT_uk do update set total = 15 - excluded.first; +insert into pv_stats_t("date", dateType, first, total) values (date_trunc('month', now()), 'month', 0.01, 0) + on conflict on constraint ddT_uk do update set total = 3.26 - excluded.first; ;