-- Copyright 2019 Michel Petit / Cogito Ergo Dev
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.

--
-- Exemples pour MySQL de l’article <https://cogito-ergo-dev.fr/blog/63363/des-jetons-qui-remplacent-des-id/>
-- 


DROP FUNCTION IF EXISTS short_token;

DELIMITER $$

CREATE FUNCTION short_token(base VARCHAR(6), size INT)
RETURNS VARCHAR(255)
BEGIN
  DECLARE token VARCHAR(255);
  ELSEIF base = "hex" THEN
    SELECT LOWER(HEX(RANDOM_BYTES(size)))
    INTO token;
  ELSEIF base = "dec" THEN
    SELECT CONV(HEX(RANDOM_BYTES(size)), 16, 10)
    INTO token;
  ELSE
    SIGNAL SQLSTATE '45000'
      SET MESSAGE_TEXT = 'Bad value for "base" argument. It must be "base64", "hex" or "dec".';
  END IF;

  RETURN token;
END$$
 
DELIMITER ;





DROP PROCEDURE IF EXISTS unique_short_token;

DELIMITER $$
 
CREATE PROCEDURE unique_short_token(
    IN base VARCHAR(6),
    IN size INT,
    IN table_name VARCHAR(255),
    OUT token VARCHAR(255)
)
BEGIN
    ok: LOOP
        SET token = short_token(base, size);
        END IF;

        IF @found IS NULL THEN
            LEAVE ok;
        END IF;
    END LOOP;
END$$
 
DELIMITER ;



DROP TRIGGER IF EXISTS trigger_unique_short_token;

DELIMITER $$

    SET NEW.token = token;
END$$
 
DELIMITER ;



DROP TRIGGER IF EXISTS trigger_unique_short_token2;

DELIMITER $$

    SET NEW.token = token;
END$$
 
DELIMITER ;



DROP TRIGGER IF EXISTS trigger_unique_short_token3;

DELIMITER $$

    SET NEW.token = token;
END$$
 
DELIMITER ;