Created
January 13, 2023 14:44
-
-
Save hatemogi/fb6516c23c9d0c47e33bc1c0f8c195a5 to your computer and use it in GitHub Desktop.
PG function generates a mongodb's objectId
This file contains hidden or 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 SEQUENCE IF NOT EXISTS object_id_counter AS int; | |
CREATE OR REPLACE FUNCTION generate_object_id() RETURNS CHAR(24) | |
AS $$ | |
DECLARE | |
id CHAR(24); | |
BEGIN | |
SELECT right(to_hex(floor(extract(epoch from now()))::integer), 8) | |
|| right(lpad(to_hex(pg_backend_pid()), 10, '0'), 10) | |
|| right(lpad(to_hex(nextval('object_id_counter')), 6, '0'), 6) | |
INTO STRICT id; | |
RETURN id; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment