Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save michaeldelorenzo/2bc4967d086f42ebd3a4 to your computer and use it in GitHub Desktop.
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
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