Last active
November 29, 2022 17:37
-
-
Save fabiolimace/db3a7b17dc46521e033d6995fdf7160b to your computer and use it in GitHub Desktop.
Function for generating Time Sortable ID with microsecond precision on PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a Time Sortable ID with microsecond precision. | |
* | |
* Time component: 52 bits (2^52 = ~71 years) | |
* | |
* Random component: 12 bits (2^12 = 4,096) | |
* | |
* The time component is the count of microseconds since 2020-01-01T00:00:00Z. | |
* | |
* Tags: tsid ulid snowflake id-generator generator time sortable sort order id | |
*/ | |
create or replace function public.fn_tsid_micro() returns bigint as $$ | |
declare | |
-- Microseconds precision | |
C_MICRO_PREC bigint := 10^6; | |
-- Random component bit length: 12 bits | |
C_RANDOM_LEN bigint := 2^12; | |
-- TSID epoch: seconds since 2020-01-01Z | |
-- extract(epoch from '2020-01-01'::date) | |
C_TSID_EPOCH bigint := 1577836800; | |
begin | |
return ((floor((extract('epoch' from clock_timestamp()) - C_TSID_EPOCH) * C_MICRO_PREC) * C_RANDOM_LEN)::bigint) + (floor(random() * C_RANDOM_LEN)::bigint); | |
end $$ language plpgsql; | |
-- EXAMPLE 1: | |
-- select fn_tsid_micro(); | |
-- EXAMPLE 1 OUTPUT: | |
-- 51692546711091432 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment