From a128555e0bcad2ae04300f7398b44e24f32bd4cc Mon Sep 17 00:00:00 2001
From: Olivier Maury <Olivier.Maury@inrae.fr>
Date: Tue, 14 Jan 2025 11:35:35 +0100
Subject: [PATCH] =?UTF-8?q?feat:=20Ajouter=20une=20fonction=20SQL=20pour?=
 =?UTF-8?q?=20mettre=20=C3=A0=20jour=20les=20normales=20d'une=20p=C3=A9rio?=
 =?UTF-8?q?de.=20refs=20#115?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 sql/schema.functions.postgresql.sql | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/sql/schema.functions.postgresql.sql b/sql/schema.functions.postgresql.sql
index fced875..7f9d50b 100644
--- a/sql/schema.functions.postgresql.sql
+++ b/sql/schema.functions.postgresql.sql
@@ -20,3 +20,20 @@ BEGIN
 END;
 $$ LANGUAGE plpgsql;
 COMMENT ON FUNCTION update_comparedvalue() IS 'Update the compared value in dailyvalue, useful when normalvalue is changed.';
+
+CREATE OR REPLACE FUNCTION agrometinfo.update_comparedvalue_for_period(period_code VARCHAR)
+RETURNS void AS $$
+DECLARE
+    updated_count INTEGER;
+BEGIN
+	UPDATE dailyvalue AS d
+	SET comparedvalue=COALESCE(d.computedvalue - n."medianvalue", 0)
+	FROM normalvalue AS n
+	JOIN "indicator" AS i ON i.id=n."indicator"
+	JOIN "period" AS p ON p.id=i."period"
+	WHERE n."indicator"=d.indicator AND n.cell=d.cell AND n.doy=EXTRACT(doy FROM d.date) AND p.code=period_code;
+	GET DIAGNOSTICS updated_count = ROW_COUNT;
+	RAISE INFO '% % updates rows', TIMEOFDAY(), updated_count;
+END;
+$$ LANGUAGE plpgsql;
+COMMENT ON FUNCTION update_comparedvalue_for_period(VARCHAR) IS 'Update the compared value in dailyvalue only for a period, useful when normalvalue is changed.';
-- 
GitLab