From a054505c585c44e162a1faba288835eb6dd1e205 Mon Sep 17 00:00:00 2001
From: Donald Buczek <buczek@molgen.mpg.de>
Date: Tue, 9 May 2017 10:26:40 +0200
Subject: [PATCH] sql: Avoid time running backwards

The value of NOW() and friends is fixed during the execution
of a statement. When other threads update the group record and
increase group_mtime, the current thread might see a group_mtime
greater than its NOW().

The calculations sometimes produced negative delta values and
overflowed when added to a UNSIGNED type.

Make sure we never decrease group_mtime.
---
 mysql/create_trigger.sql | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/mysql/create_trigger.sql b/mysql/create_trigger.sql
index 86d41fc8..5eecee40 100644
--- a/mysql/create_trigger.sql
+++ b/mysql/create_trigger.sql
@@ -15,7 +15,7 @@ CREATE TRIGGER mxq_add_group BEFORE INSERT ON mxq_group
 DROP TRIGGER IF EXISTS mxq_update_group|
 CREATE TRIGGER mxq_update_group BEFORE UPDATE ON mxq_group
     FOR EACH ROW BEGIN
-        SET NEW.group_mtime = NOW();
+        SET NEW.group_mtime = GREATEST(OLD.group_mtime, NOW());
 
         IF OLD.group_jobs_inq > 0 AND OLD.group_jobs_running = 0 THEN
             SET NEW.stats_wait_sec = OLD.stats_wait_sec + (UNIX_TIMESTAMP(NEW.group_mtime) - UNIX_TIMESTAMP(OLD.group_mtime));