From f16b7c0d71620fc32a856e23f4da350b56376d88 Mon Sep 17 00:00:00 2001 From: Wolfgang Hottgenroth Date: Sat, 11 Feb 2023 11:23:13 +0100 Subject: [PATCH] use insert on conflict --- schema/create.sql | 20 ++++++++++++-------- schema/queries02.sql | 3 +++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/schema/create.sql b/schema/create.sql index 1ad2b67..c69e151 100644 --- a/schema/create.sql +++ b/schema/create.sql @@ -36,9 +36,10 @@ create table pv_stats_t ( id serial not null primary key, "date" date not null, dateType varchar(5) not null, - first double precision not null, - total double precision default 0 + first numeric(10,2) not null default 0, + total numeric(10,2) not null default 0 ); +alter table pv_stats_t add constraint ddT_uk unique ("date", dateType); grant insert, select, update on pv_stats_t to nodered; grant select, update on pv_stats_t_id_seq to nodered; @@ -54,12 +55,9 @@ declare begin foreach v_dateType in array v_dateTypes loop - 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; + 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; end loop; return NEW; @@ -71,3 +69,9 @@ create trigger pv_stats_trig for each row execute function pv_stats_func(); + + +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; + +; diff --git a/schema/queries02.sql b/schema/queries02.sql index 1694a74..c054e86 100644 --- a/schema/queries02.sql +++ b/schema/queries02.sql @@ -5,3 +5,6 @@ select time_bucket('1 day', time) as interval, group by interval order by interval; + + +-- daily stats of current month