Skip to content

Instantly share code, notes, and snippets.

@mavencode01
Created July 12, 2016 19:51
Show Gist options
  • Save mavencode01/56708e6f17b48574dba6cf9d718bf4cf to your computer and use it in GitHub Desktop.
Save mavencode01/56708e6f17b48574dba6cf9d718bf4cf to your computer and use it in GitHub Desktop.
Postgresql unique id generator
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();
@mavencode01
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment