Last active
May 23, 2025 08:21
-
-
Save leiless/2bde68bc0817094256273e0acfd76c0f to your computer and use it in GitHub Desktop.
RANDOM_BYTES implementation for MariaDB < 10.10.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DROP FUNCTION RANDOM_BYTES; | |
DELIMITER $$ | |
CREATE FUNCTION RANDOM_BYTES(length INT) RETURNS VARBINARY(1024) | |
NOT DETERMINISTIC NO SQL | |
BEGIN | |
DECLARE output VARBINARY(1024); | |
IF length < 1 OR length > 1024 THEN | |
RETURN NULL; | |
END IF; | |
-- XXX: SELECT CONCAT(NULL, '123') -> RETURNS NULL | |
SET output = ''; | |
WHILE LENGTH(output) < length DO | |
-- Make sure 1024 / UNHEX(...) is dividable | |
-- 32 random bytes at a time | |
SET output = CONCAT(output, UNHEX(SHA2(RAND(), 256))); | |
END WHILE; | |
RETURN LEFT(output, length); | |
END$$ | |
DELIMITER ; | |
-- length in range | |
SELECT RANDOM_BYTES(15) AS t; | |
SELECT RANDOM_BYTES(16) AS t; | |
-- length < 1, NULL | |
SELECT RANDOM_BYTES(0) AS t; | |
-- length > 1024, NULL | |
SELECT RANDOM_BYTES(1025) AS t; | |
-- length in range, corner cases | |
SELECT RANDOM_BYTES(1) AS t; | |
SELECT RANDOM_BYTES(1024) AS t; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment