Skip to content

Instantly share code, notes, and snippets.

@minoritea
Last active April 21, 2022 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minoritea/ea0e7a953ce8ffc3884532668d026ffd to your computer and use it in GitHub Desktop.
Save minoritea/ea0e7a953ce8ffc3884532668d026ffd to your computer and use it in GitHub Desktop.
uuid generator for uuid v7(draft3)
-- generator function for UUID v7 (draft3).
-- https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03
-- it also depends on gen_random_uuid.
create or replace function uuid_v7() returns uuid as $$
declare
l_unixts_text text := lpad(
to_hex(
(
extract(epoch from clock_timestamp()) * 1000
)::bigint & x'FFFFFFFFFFFF'::bigint
), 12, '0');
begin
return (
substring(l_unixts_text from 1 for 8)
|| '-'
|| substring(l_unixts_text from 9 for 4)
|| '-7'
|| substring(gen_random_uuid()::text from 16 for 21))::uuid;
end $$ language plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment