Created
July 12, 2016 19:51
-
-
Save mavencode01/56708e6f17b48574dba6cf9d718bf4cf to your computer and use it in GitHub Desktop.
Postgresql unique id generator
This file contains hidden or 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 | |
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; | |
BEGIN | |
SELECT nextval('shard_1.global_id_sequence') % 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); | |
END; | |
$$ LANGUAGE PLPGSQL; | |
select shard_1.id_generator(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference http://rob.conery.io/2014/05/29/a-better-id-generator-for-postgresql/