Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active November 23, 2021 16:51
Show Gist options
  • Save fabiolimace/88d2700764c9782fec9b825d1441f148 to your computer and use it in GitHub Desktop.
Save fabiolimace/88d2700764c9782fec9b825d1441f148 to your computer and use it in GitHub Desktop.
Function for generating random-based UUIDs (v4) on PostgreSQL
/**
* Generate a random-based UUID (v4)
*
* RFC-4122 compliant.
*
* Tags: uuid guid uuid-generator guid-generator generator random rfc4122 rfc-4122
*/
create or replace function fn_uuid_random_based() returns uuid as $$
declare
v_bytes bytea;
begin
-- generate a pseudo random byte array
v_bytes := decode(md5(clock_timestamp()::text || random()::text || random()::text), 'hex');
-- Set version bits (0100)
v_bytes := set_bit(v_bytes, 55, 0);
v_bytes := set_bit(v_bytes, 54, 1);
v_bytes := set_bit(v_bytes, 53, 0);
v_bytes := set_bit(v_bytes, 52, 0);
-- Set variant bits (10xx)
v_bytes := set_bit(v_bytes, 71, 1);
v_bytes := set_bit(v_bytes, 70, 0);
return encode(v_bytes, 'hex')::uuid;
end $$ language plpgsql;
-- EXAMPLE:
--
-- select fn_uuid_random_based() uuid, clock_timestamp()-statement_timestamp() time_taken;
--
-- |uuid |time_taken |
-- |--------------------------------------|------------------|
-- |3a901c1c-5aaf-488a-9a94-55e6cf933cab |00:00:00.000189 |
--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment