DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `util`.`log_clean`()
BEGIN
/**
 * Hace limpieza de los datos de las tablas log,
 * dejando únicamente los días de retención configurados.
 */
	DECLARE vSchemaName VARCHAR(65);
	DECLARE vSchemaNameQuoted VARCHAR(65);
	DECLARE vTableName VARCHAR(65);
	DECLARE vTableNameQuoted VARCHAR(65);
	DECLARE vRetentionDays INT;
	DECLARE vStarted DATETIME;
	DECLARE vDated DATE;
	DECLARE vDone BOOL;

	DECLARE vQueue CURSOR FOR
		SELECT schemaName, tableName, retentionDays
			FROM logCleanMultiConfig
			ORDER BY `order`;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	OPEN vQueue;
	l: LOOP
		SET vDone = FALSE;
		FETCH vQueue INTO vSchemaName, vTableName, vRetentionDays;

		IF vDone THEN
			LEAVE l;
		END IF;

		IF vRetentionDays THEN
			SET vStarted = VN_NOW();
			SET vSchemaNameQuoted = quoteIdentifier(vSchemaName);
			SET vTableNameQuoted = quoteIdentifier(vTableName);
			SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY;

			EXECUTE IMMEDIATE CONCAT(
				'DELETE FROM ', vSchemaNameQuoted,
						'.', vTableNameQuoted,
					" WHERE creationDate < '", vDated, "'"
			);

			UPDATE logCleanMultiConfig
				SET `started` = vStarted,
					`finished` = VN_NOW()
				WHERE schemaName = vSchemaName
					AND tableName = vTableName;
		END IF;
	END LOOP;
	CLOSE vQueue;
END$$
DELIMITER ;
