/* | |
* MIT License | |
* | |
* Copyright (c) 2023 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 (UUIDv6). | |
* | |
* Referencies: | |
* - https://github.com/uuid6/uuid6-ietf-draft | |
* - https://github.com/ietf-wg-uuidrev/rfc4122bis | |
* | |
* MIT License. | |
* | |
* Tags: uuid guid uuid-generator guid-generator generator time order rfc4122 rfc-4122 | |
*/ | |
create or replace function uuid6() returns uuid as $$ | |
declare | |
v_time timestamp with time zone:= null; | |
v_secs bigint := null; | |
v_usec bigint := null; | |
v_timestamp bigint := null; | |
v_timestamp_hex varchar := null; | |
v_clkseq_and_nodeid bigint := null; | |
v_clkseq_and_nodeid_hex varchar := null; | |
v_bytes bytea; | |
c_epoch bigint := -12219292800; -- RFC-4122 epoch: '1582-10-15 00:00:00' | |
c_variant bit(64):= x'8000000000000000'; -- RFC-4122 variant: b'10xx...' | |
begin | |
-- Get seconds and micros | |
v_time := clock_timestamp(); | |
v_secs := EXTRACT(EPOCH FROM v_time); | |
v_usec := mod(EXTRACT(MICROSECONDS FROM v_time)::numeric, 10^6::numeric); | |
-- Generate timestamp hexadecimal (and set version 6) | |
v_timestamp := (((v_secs - c_epoch) * 10^6) + v_usec) * 10; | |
v_timestamp_hex := lpad(to_hex(v_timestamp), 16, '0'); | |
v_timestamp_hex := substr(v_timestamp_hex, 2, 12) || '6' || substr(v_timestamp_hex, 14, 3); | |
-- Generate clock sequence and node identifier hexadecimal (and set variant b'10xx') | |
v_clkseq_and_nodeid := ((random()::numeric * 2^62::numeric)::bigint::bit(64) | c_variant)::bigint; | |
v_clkseq_and_nodeid_hex := lpad(to_hex(v_clkseq_and_nodeid), 16, '0'); | |
-- Concat timestemp, clock sequence and node identifier hexadecimal | |
v_bytes := decode(v_timestamp_hex || v_clkseq_and_nodeid_hex, 'hex'); | |
return encode(v_bytes, 'hex')::uuid; | |
end $$ language plpgsql; | |
-- EXAMPLE: | |
-- | |
-- select uuid6() uuid, clock_timestamp()-statement_timestamp() time_taken; | |
-- EXAMPLE OUTPUT: | |
-- | |
-- |uuid |time_taken | | |
-- |--------------------------------------|------------------| | |
-- |1ed58ca7-060a-62a0-aa64-951dd4e5bb8a |00:00:00.000104 | | |
------------------------------------------------------------------- | |
-- FOR TEST: the expected result is an empty result set | |
------------------------------------------------------------------- | |
-- with t as ( | |
-- select uuid6() 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}-6[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$'); | |
/* | |
* MIT License | |
* | |
* Copyright (c) 2023 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 with Unix Epoch UUID (UUIDv7). | |
* | |
* Referencies: | |
* - https://github.com/uuid6/uuid6-ietf-draft | |
* - https://github.com/ietf-wg-uuidrev/rfc4122bis | |
* | |
* MIT License. | |
* | |
* Tags: uuid guid uuid-generator guid-generator generator time order rfc4122 rfc-4122 | |
*/ | |
create or replace function uuid7() returns uuid as $$ | |
declare | |
v_time timestamp with time zone:= null; | |
v_secs 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(); | |
v_secs := EXTRACT(EPOCH FROM v_time); | |
v_usec := mod(EXTRACT(MICROSECONDS FROM v_time)::numeric, 10^6::numeric); | |
-- Generate timestamp hexadecimal (and set version 7) | |
v_timestamp := (((v_secs * 1000) + div(v_usec, 1000))::bigint << 12) | (mod(v_usec, 1000) << 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; | |
-- EXAMPLE: | |
-- | |
-- select uuid7() uuid, clock_timestamp()-statement_timestamp() time_taken; | |
-- EXAMPLE OUTPUT: | |
-- | |
-- |uuid |time_taken | | |
-- |--------------------------------------|------------------| | |
-- |01878208-432f-7f04-8a23-345dade2b96b |00:00:00.000062 | | |
------------------------------------------------------------------- | |
-- 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}$'); | |
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.
the uuid generated is not accurate, sometimes 1/10 condition
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 |
https://www.ietf.org/archive/id/draft-ietf-uuidrev-rfc4122bis-14.html
does
draft-14
support all ofUUIDv7