A solução que encontrei é adicionar um gatilho ao MySQL da seguinte forma:
Em article_attachement
CREATE TRIGGER bi_article_attachement_each BEFORE INSERT ON article_attachment
FOR EACH ROW
BEGIN
DECLARE newdate datetime;
SET newdate = null;
SELECT create_time INTO newdate FROM article_plain ap WHERE ap.article_id = new.article_id LIMIT 1;
IF newdate IS NOT NULL THEN
SET new.create_time = newdate;
SET new.change_time = newdate;
END IF;
END
Em article_plain
CREATE TRIGGER bi_article_plain_each BEFORE INSERT ON article_plain
FOR EACH ROW
BEGIN
DECLARE datestr CHAR(40);
DECLARE newdate DATETIME;
DECLARE mindate DATETIME;
DECLARE myticket BIGINT;
SET datestr = mid(new.body,locate('Date: ',new.body)+6,40);
SET newdate = coalesce(str_to_date(datestr,'%a, %e %M %Y %k:%i:%s'),str_to_date(datestr,'%e %M %Y %k:%i:%s'),new.create_time);
SET new.create_time = newdate;
UPDATE article a SET a.create_time = newdate WHERE a.id = new.article_id;
SELECT a.ticket_id INTO myticket FROM article a WHERE a.id = new.article_id LIMIT 1;
SELECT least(min(a.create_time),new.create_time) INTO mindate FROM article a WHERE a.ticket_id = myticket;
UPDATE ticket t
SET t.create_time = least(t.create_time, mindate)
, t.create_time_unix = unix_timestamp(least(t.create_time, mindate))
WHERE t.id = myticket;
END
Mesma tabela, mas após atualização
CREATE TRIGGER ua_article_plain_each AFTER UPDATE ON article_plain
FOR EACH ROW
BEGIN
IF old.create_time <> new.create_time THEN BEGIN
UPDATE article a SET a.create_time = new.create_time, a.change_time = new.create_time WHERE a.id = new.article_id;
END; END IF;
END
Finalmente, um acionador em ticket
:
CREATE TRIGGER bu_ticket_each BEFORE UPDATE ON ticket
FOR EACH ROW
BEGIN
DECLARE newtn varchar(50);
DECLARE newdate varchar(12);
DECLARE filter varchar(13);
SET newdate = date_format(old.create_time,'%Y%m%d%H%i');
SET filter = concat(newdate,'%');
SELECT concat(newdate,ifnull(right(concat('0000',right(max(tn),4)+1),4),'0001')) INTO newtn
FROM ticket
WHERE tn LIKE filter;
SET new.tn = newtn;
END