Skip to content

Instantly share code, notes, and snippets.

@AntonioCS
Created September 22, 2021 13:22
Show Gist options
  • Save AntonioCS/d864e21922faf993bdb621c918656429 to your computer and use it in GitHub Desktop.
Save AntonioCS/d864e21922faf993bdb621c918656429 to your computer and use it in GitHub Desktop.
Functions for MariaDB to be able to convert to and from uuid v4 which is normally stored as BINARY(16)
DROP FUNCTION IF EXISTS uuid_v4;
DROP FUNCTION IF EXISTS BIN_TO_UUID;
DROP FUNCTION IF EXISTS UUID_TO_BIN;
-- Change delimiter so that the function body doesn't end the function declaration
DELIMITER //
CREATE FUNCTION uuid_v4()
RETURNS CHAR(36) NO SQL
BEGIN
-- Generate 8 2-byte strings that we will combine into a UUIDv4
SET @h1 = LPAD(HEX(FLOOR(RAND() * 0xffff)), 4, '0');
SET @h2 = LPAD(HEX(FLOOR(RAND() * 0xffff)), 4, '0');
SET @h3 = LPAD(HEX(FLOOR(RAND() * 0xffff)), 4, '0');
SET @h6 = LPAD(HEX(FLOOR(RAND() * 0xffff)), 4, '0');
SET @h7 = LPAD(HEX(FLOOR(RAND() * 0xffff)), 4, '0');
SET @h8 = LPAD(HEX(FLOOR(RAND() * 0xffff)), 4, '0');
-- 4th section will start with a 4 indicating the version
SET @h4 = CONCAT('4', LPAD(HEX(FLOOR(RAND() * 0x0fff)), 3, '0'));
-- 5th section first half-byte can only be 8, 9 A or B
SET @h5 = CONCAT(HEX(FLOOR(RAND() * 4 + 8)),
LPAD(HEX(FLOOR(RAND() * 0x0fff)), 3, '0'));
-- Build the complete UUID
RETURN LOWER(CONCAT(
@h1, @h2, '-', @h3, '-', @h4, '-', @h5, '-', @h6, @h7, @h8
));
END
//
-- Switch back the delimiter
DELIMITER ;
DELIMITER //
CREATE FUNCTION BIN_TO_UUID(b BINARY(16))
RETURNS CHAR(36)
BEGIN
DECLARE hexStr CHAR(32);
SET hexStr = HEX(b);
RETURN LOWER(CONCAT(
SUBSTR(hexStr, 1, 8), '-',
SUBSTR(hexStr, 9, 4), '-',
SUBSTR(hexStr, 13, 4), '-',
SUBSTR(hexStr, 17, 4), '-',
SUBSTR(hexStr, 21)
));
END//
CREATE FUNCTION UUID_TO_BIN(uuid CHAR(36))
RETURNS BINARY(16)
BEGIN
RETURN UNHEX(REPLACE(uuid, '-', ''));
END//
DELIMITER ;
@AntonioCS
Copy link
Author

You would then use this like:

SELECT 
	*, BIN_TO_UUID(product.uuid)
FROM 
	product
;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment