postgresql 生成雪花id

CREATE SEQUENCE table_id_seq increment by 1 maxvalue 99999999 minvalue 1 start 1 cycle;


CREATE OR REPLACE FUNCTION snow_next_id(OUT result bigint) AS $$
DECLARE
our_epoch bigint := 1314220021721;
seq_id bigint;
now_millis bigint;
shard_id int := 5;
BEGIN
seq_id := nextval('table_id_seq') % 1024;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - our_epoch) << 23;
result := result | (shard_id << 10);
result := result | (seq_id);
END;
$$ LANGUAGE PLPGSQL;

 

posted @ 2021-06-24 17:32  Thenext  阅读(1116)  评论(0编辑  收藏  举报