Last active
August 18, 2022 06:05
-
-
Save shellj/b985e25fff1396ef6cf5068f3f0aaaf5 to your computer and use it in GitHub Desktop.
Postgresql snowflake id generator
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
create schema shard_1; | |
create sequence shard_1.global_id_sequence; | |
CREATE OR REPLACE FUNCTION shard_1.id_generator(OUT result bigint) AS $$ | |
DECLARE | |
seq_len int := 14; | |
shard_len int := 1; | |
seq_max bigint := pow(2, seq_len); | |
-- 2022-08-08 | |
our_epoch bigint := 1659888000000; | |
seq_id bigint; | |
now_millis bigint; | |
-- the id of this DB shard, must be set for each | |
-- schema shard you have - you could pass this as a parameter too | |
shard_id int := 1; | |
BEGIN | |
SELECT nextval('shard_1.global_id_sequence') % seq_max INTO seq_id; | |
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis; | |
result := (now_millis - our_epoch) << (seq_len + shard_len); | |
result := result | (shard_id << seq_len); | |
result := result | (seq_id); | |
END; | |
$$ LANGUAGE PLPGSQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notice: this only support generating seq_max id in one millisecond, otherwise, the id will be duplicated, for this example, the seq_max is 16384