salix/db/routines/srt/procedures/moving_clean.sql

73 lines
1.5 KiB
MySQL
Raw Normal View History

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`moving_clean`()
BEGIN
/**
* Elimina movimientos por inactividad
*/
DECLARE vExpeditionFk INT;
DECLARE vBufferToFk INT;
DECLARE vBufferFromFk INT;
2024-07-18 12:12:37 +00:00
DECLARE vStateOutFk INT
DEFAULT (SELECT id FROM expeditionState WHERE `description` = 'OUT');
DECLARE vDone BOOL DEFAULT FALSE;
DECLARE vSorter CURSOR FOR
SELECT m.expeditionFk, m.bufferToFk, m.bufferFromFk
FROM moving m
JOIN (
SELECT bufferFk, SUM(isActive) hasBox
FROM photocell
GROUP BY bufferFk
) sub ON sub.bufferFk = m.bufferFromFk
WHERE m.created < (util.VN_NOW() - INTERVAL (SELECT movingMaxLife FROM config) MINUTE)
AND NOT sub.hasBox;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
OPEN vSorter;
l: LOOP
SET vDone = FALSE;
FETCH vSorter INTO vExpeditionFk, vBufferToFk, vBufferFromFk;
IF vDone THEN
LEAVE l;
END IF;
START TRANSACTION;
SELECT id
FROM moving
WHERE expeditionFk = vExpeditionFk
FOR UPDATE;
DELETE FROM moving
WHERE expeditionFk = vExpeditionFk;
SELECT id
FROM expedition
WHERE id = vExpeditionFk
OR (bufferFk = vBufferFromFk AND `position` > 0)
FOR UPDATE;
2024-07-18 12:12:37 +00:00
UPDATE expedition
SET bufferFk = NULL,
`position` = NULL,
2024-07-18 12:12:37 +00:00
stateFk = vStateOutFk
WHERE id = vExpeditionFk;
UPDATE expedition
SET `position` = `position` - 1
WHERE bufferFk = vBufferFromFk
AND `position` > 0;
COMMIT;
END LOOP l;
CLOSE vSorter;
END$$
DELIMITER ;