use insert on conflict

This commit is contained in:
2023-02-11 11:23:13 +01:00
parent da76cf5f6f
commit f16b7c0d71
2 changed files with 15 additions and 8 deletions

View File

@ -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;
;

View File

@ -5,3 +5,6 @@ select time_bucket('1 day', time) as interval,
group by interval
order by interval;
-- daily stats of current month