DROP PROCEDURE IF EXISTS `stp_counterGetNext`;

CREATE PROCEDURE stp_counterGetNext(
	IN `pYear` INT,
	IN `pName` VARCHAR(100),
	OUT `pValue` INT
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Ritorna il prossimo valore di contatore per il flusso richiesto con upsert'

BEGIN
    DECLARE vOld INT;

    -- Provo a leggere il valore corrente
    SELECT Counter INTO vOld
    FROM utils_counter
    WHERE RefYear = pYear AND CountName = pName
    FOR UPDATE;

    IF vOld IS NULL THEN
        -- Primo valore
        SET vOld = 1;

        INSERT INTO utils_counter (RefYear, CountName, Counter)
        VALUES (pYear, pName, vOld)
        ON DUPLICATE KEY UPDATE Counter = VALUES(Counter);

    ELSE
        -- Incremento
        SET vOld = vOld + 1;

        UPDATE utils_counter
        SET Counter = vOld
        WHERE RefYear = pYear AND CountName = pName;
    END IF;

    SET pValue = vOld;
END
