uuid / storage / mysql
Storing an UUID in MySQL efficiently:
DROP FUNCTION IF EXISTS uuidbin;
CREATE FUNCTION uuidbin(uuid_val varchar(36)) RETURNS varbinary(16)
DETERMINISTIC SQL SECURITY INVOKER
RETURN CONCAT(UNHEX(LEFT(uuid_val,8)),UNHEX(MID(uuid_val,10,4)),
UNHEX(MID(uuid_val,15,4)),UNHEX(MID(uuid_val,20,4)),
UNHEX(RIGHT(uuid_val,12)));
DROP FUNCTION IF EXISTS uuidstr;
CREATE FUNCTION uuidstr(uuid_val varbinary(16)) RETURNS varchar(36)
DETERMINISTIC SQL SECURITY INVOKER
RETURN LOWER(CONCAT(HEX(LEFT(uuid_val,4)),'-',HEX(MID(uuid_val,5,2)),
'-',HEX(MID(uuid_val,7,2)),'-',HEX(MID(uuid_val,9,2)),
'-',HEX(RIGHT(uuid_val,6))));
Now you can create your uuid
columns with type binary(16)
.
And conversion is easy:
mysql> select uuidstr(uuidbin(uuidstr(uuidbin(uuidstr(uuidbin(
'a89e6d7b-f2ec-11e3-bcfb-5c514fe65f2f'))))))
as uuid_back_and_forth;
+--------------------------------------+
| uuid_back_and_forth |
+--------------------------------------+
| a89e6d7b-f2ec-11e3-bcfb-5c514fe65f2f |
+--------------------------------------+