From 9311712a7ca90d7df8cd32f65901368dbe8b4299 Mon Sep 17 00:00:00 2001 From: Sonia Zorba <sonia.zorba@inaf.it> Date: Wed, 7 Jul 2021 15:44:08 +0200 Subject: [PATCH] Added trigger to update job start/end time on phase update --- 03-other-functions.sql | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/03-other-functions.sql b/03-other-functions.sql index 42b9105..1646ec8 100644 --- a/03-other-functions.sql +++ b/03-other-functions.sql @@ -69,3 +69,24 @@ SELECT '/' || string_agg(name, '/') FROM ( ) SELECT name FROM paths ORDER BY LEVEL DESC ) AS names $func$ LANGUAGE sql; + +-- Trigger function that automatically updates start time and end time of jobs at phase update. +-- This could be performed by business logic of each application that handles jobs but relying directly on the database ensures a better uniformity. + +CREATE OR REPLACE FUNCTION job_phase_updated() RETURNS TRIGGER +AS +$func$ +BEGIN + IF new.phase = 'EXECUTING' THEN + new.start_time := NOW(); + ELSIF new.phase = 'COMPLETED' OR new.phase = 'ERROR' OR new.phase = 'ABORTED' THEN + new.end_time := NOW(); + END IF; + RETURN new; +END; +$func$ LANGUAGE plpgsql; + +CREATE TRIGGER job_update + BEFORE UPDATE OF phase ON job + FOR EACH ROW + EXECUTE PROCEDURE job_phase_updated(); -- GitLab