From e2f9873db4da7e8663bf93dcd30c574d08a112f4 Mon Sep 17 00:00:00 2001 From: finlab Date: Fri, 29 Jan 2021 03:52:16 +0800 Subject: [PATCH] add example3: postgres implemented --- example3/snowflake-id.sql | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 example3/snowflake-id.sql diff --git a/example3/snowflake-id.sql b/example3/snowflake-id.sql new file mode 100644 index 0000000..9b6f32a --- /dev/null +++ b/example3/snowflake-id.sql @@ -0,0 +1,37 @@ +CREATE SEQUENCE public.global_id_seq; +ALTER SEQUENCE public.global_id_seq OWNER TO postgres; + +CREATE OR REPLACE FUNCTION public.id_generator() + RETURNS bigint + LANGUAGE 'plpgsql' +AS $BODY$ +DECLARE + our_epoch bigint := 1314220021721; + 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; + result bigint:= 0; +BEGIN + SELECT nextval('public.global_id_seq') % 1024 INTO seq_id; + + 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); + return result; +END; +$BODY$; + +ALTER FUNCTION public.id_generator() OWNER TO postgres; + +create schema shard_1 +create table users( + id bigint not null default id_generator(), + email varchar(255) not null unique, + first varchar(50), + last varchar(50) +); + +-- select id_generator();