Skip to content

Instantly share code, notes, and snippets.

@lookis
Last active September 8, 2023 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lookis/d1771d8816018305b70fde3591638ba8 to your computer and use it in GitHub Desktop.
Save lookis/d1771d8816018305b70fde3591638ba8 to your computer and use it in GitHub Desktop.
snowflake in postgresql
CREATE SEQUENCE IF NOT EXISTS public.global_id_sequence;
CREATE OR REPLACE FUNCTION id_generator()
RETURNS bigint
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE
epoch BIGINT := 1688745600000;
seq_id BIGINT;
now_millis BIGINT;
shard_id INT := 0; -- before sharding, all use 0 as shard id
result bigint:= 0;
BEGIN
SELECT nextval('public.global_id_sequence') % 1024 INTO seq_id;
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_millis;
result := (now_millis - epoch) << 23;
result := result | (shard_id << 10);
result := result | (seq_id);
return result;
END;
$BODY$;
ALTER FUNCTION public.id_generator() OWNER TO yochat;
alter sequence public.global_id_sequence owner to yochat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment