· 6 years ago · May 13, 2019, 05:58 PM
1The MIT License (MIT)
2Copyright (c) 2013 Jamar Parris
3
4Permission 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:
5
6The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
8THE 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.
9
10CREATE OR REPLACE FUNCTION generate_object_id() RETURNS varchar AS $$
11 DECLARE
12 time_component bigint;
13 machine_id bigint := FLOOR(random() * 16777215);
14 process_id bigint;
15 seq_id bigint := FLOOR(random() * 16777215);
16 result varchar:= '';
17 BEGIN
18 SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp())) INTO time_component;
19 SELECT pg_backend_pid() INTO process_id;
20
21 result := result || lpad(to_hex(time_component), 8, '0');
22 result := result || lpad(to_hex(machine_id), 6, '0');
23 result := result || lpad(to_hex(process_id), 4, '0');
24 result := result || lpad(to_hex(seq_id), 6, '0');
25 RETURN result;
26 END;
27$$ LANGUAGE PLPGSQL;
28
29Example Use:
30
31CREATE TABLE IF NOT EXISTS users
32(
33 id varchar(24) NOT NULL default generate_object_id(),
34 name varchar(255) NOT NULL,
35);