mysql выражение для случайного uuid4? - PullRequest
0 голосов
/ 09 апреля 2020

Mysql предлагает функцию UUID(), которая возвращает rf c 4122 версию 1. Это легко угадываемая строка времени + бит_узла.

Как мы можем вставить рандомизированные версия 4 направляющих?

(определение новой функции требует разрешений и выходит за рамки. Бен Джонсон предлагает выражение , которое очень приятно, но немного многословно.)

1 Ответ

0 голосов
/ 09 апреля 2020

Вставляет случайную строку версии 4 без тире. Для краткости используется только 25% пространства клавиш или 120 бит.

-- Produces version 4 guids for mysql, as its UUID() only offers version 1.
--
-- See https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
-- We consider variant 1 only, ignoring the Microsoft proprietary variant 2.
-- Version 1 is predictable timestamp.
-- Version 4 is 122 random bits + 6 constant bits.
--
-- The nil guid comes out like this:
-- UUID('00000000-0000-4000-8000-000000000000')  # 8-4-4-4-12
-- The nybble '4' is constant version.
-- The nybble '8' has hi bit set, next bit cleared, plus two wasted bits.
-- We deliberately choose to emit just 120 random bits, for simplicity.
-- The RAND() function returns about 53 bits of entropy in the mantissa,
-- so for 15 nybbles we call it twice to obtain 106 ( > 60 ) unguessable bits.
-- The standard spelling of a guid, with four '-' dashes, is 36 characters.
-- We emit 32 hex characters, sans dashes.

INSERT INTO guid_test (guid) VALUES (
  concat(substr(sha2(rand(), 256),                 1, 12),
    '4', substr(sha2(rand(), 256),                 1,  3),
    '8', substr(sha2(concat(rand(), rand()), 256), 1, 15)
  )
);
...