Forked from jamarparris/Generate Mongo Object ID in PostGres
Created
October 13, 2015 13:51
-
-
Save michaeldelorenzo/2bc4967d086f42ebd3a4 to your computer and use it in GitHub Desktop.
Create ObjectIds in PostGres following the MongoDB semantics. Very similar to the Instagram approach linked below. http://docs.mongodb.org/manual/reference/object-id/ http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
This file contains 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 OR REPLACE FUNCTION generate_object_id() RETURNS varchar AS $$ | |
DECLARE | |
time_component bigint; | |
machine_id int := FLOOR(random() * 16777215); | |
process_id int; | |
seq_id bigint := FLOOR(random() * 16777215); | |
result varchar:= ''; | |
BEGIN | |
SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp())) INTO time_component; | |
SELECT pg_backend_pid() INTO process_id; | |
result := result || lpad(to_hex(time_component), 8, '0'); | |
result := result || lpad(to_hex(machine_id), 6, '0'); | |
result := result || lpad(to_hex(process_id), 4, '0'); | |
result := result || lpad(to_hex(seq_id), 6, '0'); | |
RETURN result; | |
END; | |
$$ LANGUAGE PLPGSQL; | |
Example Use: | |
CREATE TABLE IF NOT EXISTS users | |
( | |
id varchar(24) NOT NULL default generate_object_id(), | |
name varchar(255) NOT NULL, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment