Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save klumhru/863fac68052a282921df82330b6c934f to your computer and use it in GitHub Desktop.
Save klumhru/863fac68052a282921df82330b6c934f 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
The MIT License (MIT)
Copyright (c) 2013 Jamar Parris
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
CREATE OR REPLACE FUNCTION generate_object_id() RETURNS varchar AS $$
DECLARE
time_component bigint;
machine_id bigint := FLOOR(random() * 16777215);
process_id bigint;
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