Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active January 21, 2025 12:56
Show Gist options
  • Save fabiolimace/515a0440e3e40efeb234e12644a6a346 to your computer and use it in GitHub Desktop.
Save fabiolimace/515a0440e3e40efeb234e12644a6a346 to your computer and use it in GitHub Desktop.
Functions for generating UUIDv6 and UUIDv7 on PostgreSQL
/*
* MIT License
*
* Copyright (c) 2023-2024 Fabio Lima
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Returns a time-ordered UUID with Unix Epoch (UUIDv7).
*
* Referencie: https://www.rfc-editor.org/rfc/rfc9562.html
*
* MIT License.
*
*/
create or replace function uuid7() returns uuid as $$
declare
begin
return uuid7(clock_timestamp());
end $$ language plpgsql;
create or replace function uuid7(p_timestamp timestamp with time zone) returns uuid as $$
declare
v_time double precision := null;
v_unix_t bigint := null;
v_rand_a bigint := null;
v_rand_b bigint := null;
v_unix_t_hex varchar := null;
v_rand_a_hex varchar := null;
v_rand_b_hex varchar := null;
c_milli double precision := 10^3; -- 1 000
c_micro double precision := 10^6; -- 1 000 000
c_scale double precision := 4.096; -- 4.0 * (1024 / 1000)
c_version bigint := x'0000000000007000'::bigint; -- RFC-9562 version: b'0111...'
c_variant bigint := x'8000000000000000'::bigint; -- RFC-9562 variant: b'10xx...'
begin
v_time := extract(epoch from p_timestamp);
v_unix_t := trunc(v_time * c_milli);
v_rand_a := trunc((v_time * c_micro - v_unix_t * c_milli) * c_scale);
-- v_rand_b := secure_random_bigint(); -- use when pgcrypto extension is installed
v_rand_b := trunc(random() * 2^30)::bigint << 32 | trunc(random() * 2^32)::bigint;
v_unix_t_hex := lpad(to_hex(v_unix_t), 12, '0');
v_rand_a_hex := lpad(to_hex((v_rand_a | c_version)::bigint), 4, '0');
v_rand_b_hex := lpad(to_hex((v_rand_b | c_variant)::bigint), 16, '0');
return (v_unix_t_hex || v_rand_a_hex || v_rand_b_hex)::uuid;
end $$ language plpgsql;
-------------------------------------------------------------------
-- EXAMPLE:
-------------------------------------------------------------------
--
-- select uuid7() uuid, clock_timestamp()-statement_timestamp() time_taken;
--
-- |uuid |time_taken |
-- |--------------------------------------|------------------|
-- |018da240-e0db-72e1-86f5-345c2c240387 |00:00:00.000222 |
--
-------------------------------------------------------------------
-- EXAMPLE: generate a list
-------------------------------------------------------------------
--
-- with x as (select clock_timestamp() as t from generate_series(1, 1000))
-- select uuid7(x.t) uuid, x.t::text ts from x;
--
-- |uuid |ts |
-- |------------------------------------|-----------------------------|
-- |018da235-6271-70cd-a937-0bb7d22b801e|2024-02-13 08:23:44.113054-03|
-- |018da235-6271-7214-9188-1d3191883b5d|2024-02-13 08:23:44.113126-03|
-- |018da235-6271-723d-bebe-87f66085fad7|2024-02-13 08:23:44.113143-03|
-- |018da235-6271-728f-86ba-6e277d10c0a3|2024-02-13 08:23:44.113156-03|
-- |018da235-6271-72b8-9887-f31e4ca48020|2024-02-13 08:23:44.113168-03|
-- |018da235-6271-72e1-bbeb-8b686d0d4281|2024-02-13 08:23:44.113179-03|
-- |018da235-6271-730a-96a2-73275626f72a|2024-02-13 08:23:44.113190-03|
-- |018da235-6271-7333-8a5c-9d1ab89dc489|2024-02-13 08:23:44.113201-03|
-- |018da235-6271-735c-ba64-a42b55ad7d5c|2024-02-13 08:23:44.113212-03|
-- |018da235-6271-7385-a0fb-c65f5be24073|2024-02-13 08:23:44.113223-03|
--
-------------------------------------------------------------------
-- BENCHMARK: generate 1 million UUIDs and print the time taken
-------------------------------------------------------------------
-- DO $$
-- DECLARE
-- v_start double precision;
-- v_end double precision;
-- v_count bigint;
-- BEGIN
-- v_start := extract(epoch from clock_timestamp());
-- with x as (select uuid7() id from generate_series(1, 1000000))
-- select count(id) into v_count from x;
-- v_end := extract(epoch from clock_timestamp());
-- raise notice 'Time taken: %s', v_end - v_start;
-- END
-- $$ language plpgsql;
-- SYSTEM OUTPUT
-- Time taken: 2.848252058029175s [with PostgreSQL's random() ]
-- Time taken: 5.202008008956909s [with secure_random_bigint()]
-------------------------------------------------------------------
-- FOR TEST: the expected result is an empty result set
-------------------------------------------------------------------
--
-- with t as (select uuid7() as id from generate_series(1, 1000))
-- select * from t where (id is null or id::text !~ '^[a-f0-9]{8}-[a-f0-9]{4}-7[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$');
--
/*
* MIT License
*
* Copyright (c) 2023-2024 Fabio Lima
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Returns a time-ordered UUID with Unix Epoch (UUIDv7).
*
* Referencie: https://www.rfc-editor.org/rfc/rfc9562.html
*
* MIT License.
*
*/
create or replace function uuid7() returns uuid as $$
declare
begin
return uuid7(clock_timestamp());
end $$ language plpgsql;
create or replace function uuid7(p_timestamp timestamp with time zone) returns uuid as $$
declare
v_time double precision := null;
v_unix_t bigint := null;
v_rand_a bigint := null;
v_rand_b bigint := null;
v_unix_t_hex varchar := null;
v_rand_a_hex varchar := null;
v_rand_b_hex varchar := null;
c_milli double precision := 10^3; -- 1 000
c_micro double precision := 10^6; -- 1 000 000
c_scale double precision := 4.096; -- 4.0 * (1024 / 1000)
c_version bigint := x'0000000000007000'::bigint; -- RFC-9562 version: b'0111...'
c_variant bigint := x'8000000000000000'::bigint; -- RFC-9562 variant: b'10xx...'
begin
v_time := extract(epoch from p_timestamp);
v_unix_t := trunc(v_time * c_milli);
v_rand_a := trunc((v_time * c_micro - v_unix_t * c_milli) * c_scale);
-- v_rand_b := secure_random_bigint(); -- use when pgcrypto extension is installed
v_rand_b := trunc(random() * 2^30)::bigint << 32 | trunc(random() * 2^32)::bigint;
v_unix_t_hex := lpad(to_hex(v_unix_t), 12, '0');
v_rand_a_hex := lpad(to_hex((v_rand_a | c_version)::bigint), 4, '0');
v_rand_b_hex := lpad(to_hex((v_rand_b | c_variant)::bigint), 16, '0');
return (v_unix_t_hex || v_rand_a_hex || v_rand_b_hex)::uuid;
end $$ language plpgsql;
-------------------------------------------------------------------
-- EXAMPLE:
-------------------------------------------------------------------
--
-- select uuid7() uuid, clock_timestamp()-statement_timestamp() time_taken;
--
-- |uuid |time_taken |
-- |--------------------------------------|------------------|
-- |018da240-e0db-72e1-86f5-345c2c240387 |00:00:00.000222 |
--
-------------------------------------------------------------------
-- EXAMPLE: generate a list
-------------------------------------------------------------------
--
-- with x as (select clock_timestamp() as t from generate_series(1, 1000))
-- select uuid7(x.t) uuid, x.t::text ts from x;
--
-- |uuid |ts |
-- |------------------------------------|-----------------------------|
-- |018da235-6271-70cd-a937-0bb7d22b801e|2024-02-13 08:23:44.113054-03|
-- |018da235-6271-7214-9188-1d3191883b5d|2024-02-13 08:23:44.113126-03|
-- |018da235-6271-723d-bebe-87f66085fad7|2024-02-13 08:23:44.113143-03|
-- |018da235-6271-728f-86ba-6e277d10c0a3|2024-02-13 08:23:44.113156-03|
-- |018da235-6271-72b8-9887-f31e4ca48020|2024-02-13 08:23:44.113168-03|
-- |018da235-6271-72e1-bbeb-8b686d0d4281|2024-02-13 08:23:44.113179-03|
-- |018da235-6271-730a-96a2-73275626f72a|2024-02-13 08:23:44.113190-03|
-- |018da235-6271-7333-8a5c-9d1ab89dc489|2024-02-13 08:23:44.113201-03|
-- |018da235-6271-735c-ba64-a42b55ad7d5c|2024-02-13 08:23:44.113212-03|
-- |018da235-6271-7385-a0fb-c65f5be24073|2024-02-13 08:23:44.113223-03|
--
-------------------------------------------------------------------
-- BENCHMARK: generate 1 million UUIDs and print the time taken
-------------------------------------------------------------------
-- DO $$
-- DECLARE
-- v_start double precision;
-- v_end double precision;
-- v_count bigint;
-- BEGIN
-- v_start := extract(epoch from clock_timestamp());
-- with x as (select uuid7() id from generate_series(1, 1000000))
-- select count(id) into v_count from x;
-- v_end := extract(epoch from clock_timestamp());
-- raise notice 'Time taken: %s', v_end - v_start;
-- END
-- $$ language plpgsql;
-- SYSTEM OUTPUT
-- Time taken: 2.848252058029175s [with PostgreSQL's random() ]
-- Time taken: 5.202008008956909s [with secure_random_bigint()]
-------------------------------------------------------------------
-- FOR TEST: the expected result is an empty result set
-------------------------------------------------------------------
--
-- with t as (select uuid7() as id from generate_series(1, 1000))
-- select * from t where (id is null or id::text !~ '^[a-f0-9]{8}-[a-f0-9]{4}-7[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$');
--
-- install the extension
CREATE EXTENSION pgcrypto;
CREATE OR REPLACE FUNCTION secure_random_bigint() RETURNS bigint AS $$
DECLARE
v_bytes bytea;
v_value bigint := 0;
v_length integer := 8;
i integer := 0;
BEGIN
v_bytes := gen_random_bytes(v_length);
FOR i IN 0..v_length-1 LOOP
v_value := (v_value << 8) | get_byte(v_bytes, i);
END LOOP;
RETURN v_value::bigint;
END;
$$ LANGUAGE plpgsql;
@productdevbook
Copy link

@fabiolimace
Copy link
Author

fabiolimace commented Nov 7, 2023

Hi @productdevbook

The UUIDv7 generator here is in accordance with draft-14 section 5.7.

5.7.
UUIDv7 values are created by allocating a Unix timestamp in milliseconds in the most significant 48 bits and filling the remaining 74 bits, excluding the required version and variant bits, with random bits for each new UUIDv7 generated to provide uniqueness as per Section 6.9. Alternatively, implementations MAY fill the 74 bits, jointly, with a combination of the following subfields, in this order from the most significant bits to the least, to guarantee additional monotonicity within a millisecond:

An OPTIONAL sub-millisecond timestamp fraction (12 bits at maximum) as per Section 6.2 (Method 3).

The only exception is that the random() function is not a CSPRNG generator, as you may have noticed.

6.9.
Implementations SHOULD utilize a cryptographically secure pseudo-random number generator (CSPRNG) to provide values that are both difficult to predict ("unguessable") and have a low likelihood of collision ("unique"). The exception is when a suitable CSPRNG is unavailable in the execution environment.

You have to install pgcrypto to have access to crypto functions.

Thanks for asking.

@LuckyArdhika
Copy link

the uuid generated is not accurate, sometimes 1/10 condition

@fabiolimace
Copy link
Author

fabiolimace commented Nov 14, 2023

Hi @LuckyArdhika

Could you show the code used to test the accuracy?

The UUID generated by the function is accurate to the millisecond.

In the test below, I changed 2 lines of the original code. At the end there is a comparison of the millisecond in the timestamp and the millisecond embedded in the UUID.

Note that there is no significant loss of accuracy. The only difference is due to the floating-point division operation of the IEEE-754 standard.

Additionally, the microsecond variable in the function is used to add extra monotonicity, it is not intended to be precise.

-- create or replace function uuid7() returns uuid as $$                   -- ## REPLACED LINE ##
create or replace function uuid7(parameter_timestamp timestamp with time zone) returns uuid as $$
declare
	v_time timestamp with time zone:= null;
	v_secs bigint := null;
	v_msec bigint := null;
	v_usec bigint := null;

	v_timestamp bigint := null;
	v_timestamp_hex varchar := null;

	v_random bigint := null;
	v_random_hex varchar := null;

	v_bytes bytea;

	c_variant bit(64):= x'8000000000000000'; -- RFC-4122 variant: b'10xx...'
begin

	-- Get seconds and micros
--	v_time := clock_timestamp();                       -- ## REPLACED LINE ##
	v_time := parameter_timestamp;
	v_secs := EXTRACT(EPOCH FROM v_time);
	v_msec := mod(EXTRACT(MILLISECONDS FROM v_time)::numeric, 10^3::numeric);
	v_usec := mod(EXTRACT(MICROSECONDS FROM v_time)::numeric, 10^3::numeric);

	-- Generate timestamp hexadecimal (and set version 7)
	v_timestamp := (((v_secs * 10^3) + v_msec)::bigint << 12) | (v_usec << 2);
	v_timestamp_hex := lpad(to_hex(v_timestamp), 16, '0');
	v_timestamp_hex := substr(v_timestamp_hex, 2, 12) || '7' || substr(v_timestamp_hex, 14, 3);

	-- Generate the random hexadecimal (and set variant b'10xx')
	v_random := ((random()::numeric * 2^62::numeric)::bigint::bit(64) | c_variant)::bigint;
	v_random_hex := lpad(to_hex(v_random), 16, '0');

	-- Concat timestemp and random hexadecimal
	v_bytes := decode(v_timestamp_hex || v_random_hex, 'hex');

	return encode(v_bytes, 'hex')::uuid;
	
end $$ language plpgsql;

create or replace function extract_timestamp(parameter_uuid uuid) returns bigint as $$
declare
	v_uuid_hex varchar := null;
	v_timestamp bigint := null;
	v_timestamp_hex varchar := null;
begin

	v_uuid_hex := replace(parameter_uuid::varchar, '-', '');
	v_timestamp_hex := substring(v_uuid_hex, 1, 12) || substring(v_uuid_hex, 14, 3);
	v_timestamp := ('x'||lpad(v_timestamp_hex,16,'0'))::bit(64)::bigint;

	return mod(v_timestamp >> 12, (10^3)::bigint);

end $$ language plpgsql;
select statement_timestamp()::varchar ts, mod(EXTRACT(MILLISECONDS from statement_timestamp())::bigint, 1000) ms_from_ts, extract_timestamp(uuid7(statement_timestamp())) ms_from_uuid;
ts ms_from_ts ms_from_uuid
2023-11-14 01:53:15.61599-03 616 616

@andnorxor
Copy link

For postgres 9.2 compatibility you need to cast the following two values explicitly:

  v_secs := EXTRACT(EPOCH FROM v_time)::bigint;
  v_usec := mod(EXTRACT(MICROSECONDS FROM v_time)::numeric, 10^6::numeric)::bigint;

Otherwise you'll get

SQL Error [22P02]: ERROR: invalid input syntax for integer: "1707596980.41937304"
  Where: PL/pgSQL function uuid7() line 20 at assignment

@fabiolimace
Copy link
Author

Thank you, @andnorxor !

Functions updated.

@andnorxor
Copy link

Thank you for sharing your code; it truly was a lifesaver. In one of my projects I realized too late that postgresql-contrib was not installed on some legacy systems and it was nearly impossible to install it due security restrictions. But I had already based large parts of my module on UUIDs. Your function was the perfect workaround.

@fabiolimace
Copy link
Author

fabiolimace commented Feb 13, 2024

🚨 FIXED rounding error

Extracting epoch seconds and converting them to bigint was causing rounding errors. For example, extracting the epoch seconds from the timestamp '2024-02-12 17:49:10.827009Z' should return 1707760150, but was returning 1707760151 (+1).

To fix this, you need to truncate before converting to bigint.

See the result of this query:

select EXTRACT(EPOCH FROM '2024-02-12 17:49:10.827009Z'::timestamp)                 as seconds,
       EXTRACT(EPOCH FROM '2024-02-12 17:49:10.827009Z'::timestamp)::bigint         as seconds_bigint,    -- implicitly rounded
       TRUNC(EXTRACT(EPOCH FROM '2024-02-12 17:49:10.827009Z'::timestamp))::bigint  as seconds_truncated; -- explicitly truncated
|seconds             |seconds_bigint|seconds_truncated|
|--------------------|--------------|-----------------|
|1,707,760,150.827009|1.707.760.151 |1.707.760.150    |

The rounding issue is now fixed.

Thanks, Tobias, for letting me know about this!

@fabiolimace
Copy link
Author

fabiolimace commented Feb 13, 2024

I'm refactoring the functions. I hope they are more readable after refactoring.

@fabiolimace
Copy link
Author

Refactored.

@productdevbook
Copy link

When will v6 become stable, is there any news about it?

@fabiolimace
Copy link
Author

I don't know. I hope draft 14 is the last and the new RFC is finally completed.

There are no updates to the email archive:
https://mailarchive.ietf.org/arch/browse/uuidrev/

@ChrisJohnNewton
Copy link

I had to cast 2^12 as numeric to get this to work in PostgreSQL version 16.2

DIV(v_gregorian_t, 2^12::NUMERIC)
MOD(v_gregorian_t, 2^12::NUMERIC)

@diogobaeder
Copy link

Dude, fantastic job! \m/

@fabiolimace
Copy link
Author

fabiolimace commented Jul 3, 2024

An anonymous said and deleted later:

Getting ERROR: invalid input syntax for type uuid: "018d3f3b-4390-7375-9acd-7611c9a7c" error on some uuids generated by these functions.

The last 3 hex digits are missing in 018d3f3b-4390-7375-9acd-7611c9a7c???.

For this error to occur inside the function, the following condition must be true for some return of random(), but I didn't find any value that would cause this.

select length(to_hex(((random()::numeric * 2^62::numeric)::bigint::bit(64) | x'8000000000000000')::bigint)) < 16;

I think rand_b can be split into two 32-bit random(), just in case of another floating point issue.

@fabiolimace
Copy link
Author

fabiolimace commented Jul 4, 2024

Instead, I just removed the decode() and encode() operations because they are no longer needed.

Diffs:

-	v_output_bytes := decode(v_gregorian_t_hex_a || v_gregorian_t_hex_b  || v_clock_sequence_and_node_hex, 'hex');
- 	return encode(v_output_bytes, 'hex')::uuid;
+ 	return (v_gregorian_t_hex_a || v_gregorian_t_hex_b  || v_clock_sequence_and_node_hex)::uuid;
-	v_output_bytes := decode(v_unix_t_hex || v_rand_a_hex || v_rand_b_hex, 'hex');
-	return encode(v_output_bytes, 'hex')::uuid;
+	return (v_unix_t_hex || v_rand_a_hex || v_rand_b_hex)::uuid;

Thanks any way, anonymous!

@eloff
Copy link

eloff commented Jul 7, 2024

v_rand_b := random()::numeric * 2^62::numeric;

This line wants to produce 62 random bits, but a double between 0 and 1 only has 52 bits in the mantissa. Casting it to numeric doesn't give you more bits of entropy.

You need to do something like:

-- Generate a random 64-bit integer
create or replace function random_bigint() returns bigint as $$
declare
    hi bigint;
    lo bigint;
begin
    -- generate a number from 0 to 4294967295 inclusive
    hi := (random() * 0x100000000)::bigint;
    lo := (random() * 0x100000000)::bigint;
    return (hi << 32) | lo;
end;
$$ language plpgsql;

@fabiolimace
Copy link
Author

fabiolimace commented Jul 7, 2024

You are right @eloff. I missed the mantissa detail.

Replaced all numeric data types with bigint or double precision. I was using numeric to resist IEEE 754 floating point arithmetic, but this resistance is futile.

Here are the diff lines related to the variable v_rand_b:

- 	v_rand_b := random()::numeric * 2^62::numeric;
+ 	v_rand_b := trunc(random() * 2^30)::bigint << 32 | trunc(random() * 2^32)::bigint;

I think the functions are simpler now (and maybe faster).

Thank you for letting me know! 👍

@LazerJesus
Copy link

hey,
ive got the biggest noob question and i am sorry to pollute this gist with it. but ...

i've created the function. ie just executed the `uuid7' sql above.
then i added the function to my prisma.schema like this:

model User {
  id          String  @id @default(dbgenerated("uuid7()"))

but trying to deploy that i get:

ERROR: function uuid7() does not exist

i get the sense that i have to turn this into an extension?!
whats wrong with my approach?

ill show myself back into my skill-issue corner.

@fabiolimace
Copy link
Author

fabiolimace commented Oct 30, 2024

I'm the biggest noob in prisma. Sorry.

But it looks like a search_path problem. Check these issues:

EDIT:

@fabiolimace
Copy link
Author

Performance validation for UUIDv7 implemented using SQL in PostgreSQL v16 (Monday, July 8, 2024)

https://www.dbaglobe.com/2024/07/performance-validation-for-uuidv7.html

@fabiolimace
Copy link
Author

Choosing Primary Key Type in PostgreSQL (June 23, 2022)

https://shekhargulati.com/2022/06/23/choosing-a-primary-key-type-in-postgres/

@fabiolimace
Copy link
Author

fabiolimace commented Nov 30, 2024

@jdconley
Copy link

jdconley commented Jan 9, 2025

I'm not a postgres or crypto expert, so there is probably a better way to do this, but could you use something like this to replace random() if pgcrypto is available to satisfy section 6.9's SHOULD? This should be 64 bits of randomness in a 0-1 range, though I just wrote it and looked at some anecdotal output, haven't ran it against a test suite.

CREATE OR REPLACE FUNCTION secure_random() RETURNS double precision AS $$
DECLARE
    -- Use 8 bytes (64 bits) for high precision
    v_bytes bytea;
    v_int bigint;
BEGIN
    v_bytes := gen_random_bytes(8);
    -- Convert bytes to bigint (using bitwise AND to ensure positive number)
    v_int := ((get_byte(v_bytes, 0)::bigint << 56) |
             (get_byte(v_bytes, 1)::bigint << 48) |
             (get_byte(v_bytes, 2)::bigint << 40) |
             (get_byte(v_bytes, 3)::bigint << 32) |
             (get_byte(v_bytes, 4)::bigint << 24) |
             (get_byte(v_bytes, 5)::bigint << 16) |
             (get_byte(v_bytes, 6)::bigint << 8) |
             get_byte(v_bytes, 7)::bigint) & x'7FFFFFFFFFFFFFFF'::bigint;
    -- Convert to [0, 1) range using max positive bigint value
    RETURN (v_int::numeric / (2^63)::numeric)::double precision;
END;
$$ LANGUAGE plpgsql;

@fabiolimace
Copy link
Author

fabiolimace commented Jan 9, 2025

Hi @jdconley !

I'm not an expert on any of them. I always learn valuable things from interactions here on github.

Your function is very useful! The only line we need to change is this one in the uuid7() function:

	v_unix_t := trunc(v_time * c_milli);
	v_rand_a := trunc((v_time * c_micro - v_unix_t * c_milli) * c_scale);
-	v_rand_b := trunc(random() * 2^30)::bigint << 32 | trunc(random() * 2^32)::bigint;
+	v_rand_b := trunc(secure_random() * 2^30)::bigint << 32 | trunc(secure_random() * 2^32)::bigint;

I was thinking of adding a few lines like in another GIST of mine, but your function is more generic and can be reused as well.

Also you're absolutely right about recommending a cryptographically secure generator for the random component of UUIDs. However, functions should I am of the opinion that these functions should be as simple as possible while still conforming to the standard, except for that specific point you mentioned.

Thanks for your suggestion!

@jdconley
Copy link

jdconley commented Jan 9, 2025

Also you're absolutely right about recommending a cryptographically secure generator for the random component of UUIDs. However, functions should be as simple as possible while still conforming to the standard, except for that specific point you mentioned.

I imagine it is going to slow down the benchmarks, but, would be a good option for people that want a secure option (e.g. if these id's are publicly available) assuming my implementation isn't complete 💩

@fabiolimace
Copy link
Author

fabiolimace commented Jan 11, 2025

I just added secure_random_bigint(), which can be used when pgcrypto is available.

Benchmark generating 1 million UUIDv7:

  • Using PostgreSQL's random() (twice): 2.84 s
  • Using secure_random_bigint() (once): 5.20 s

Summary: using secure_random_bigint() took 83% longer compared to using random() twice in the uuid7() function.


Also created some random functions using bytes provided by pgcrypto. The secure_random_double() took more time because I had to learn how IEEE 754 deals with the mantissa's 52 bits. Today I learned.

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