DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `util`.`binlogQueue_getDelay`(vCode VARCHAR(255))
	RETURNS BIGINT
	READS SQL DATA
	NOT DETERMINISTIC
BEGIN
/**
 * Returns the difference between the current position of the binary log and
 * the passed queue.
 *
 * @param vCode The queue code
 * @return The difference in MB
 */
	DECLARE vCurLogName VARCHAR(255);
	DECLARE vCurPosition BIGINT;
	DECLARE vQueueLogName VARCHAR(255);
	DECLARE vQueuePosition BIGINT;
	DECLARE vDelay BIGINT;

	SELECT VARIABLE_VALUE INTO vCurLogName
		FROM information_schema.GLOBAL_STATUS
		WHERE VARIABLE_NAME = 'BINLOG_SNAPSHOT_FILE';

	SELECT VARIABLE_VALUE INTO vCurPosition
		FROM information_schema.GLOBAL_STATUS
		WHERE VARIABLE_NAME = 'BINLOG_SNAPSHOT_POSITION';

	SELECT logName, `position`
		INTO vQueueLogName, vQueuePosition
		FROM binlogQueue
		WHERE code = vCode;

	IF vQueuePosition IS NULL THEN
		RETURN NULL;
	END IF;

	SET vDelay =
		vCurPosition - CAST(vQueuePosition AS SIGNED) +
		@@max_binlog_size * (
			CAST(REGEXP_SUBSTR(vCurLogName, '[0-9]+') AS SIGNED) -
			CAST(REGEXP_SUBSTR(vQueueLogName, '[0-9]+') AS SIGNED)
		);

	RETURN ROUND(vDelay / POW(1024, 2));
END$$
DELIMITER ;
