Skip to content

Instantly share code, notes, and snippets.

@hatemogi
Created January 13, 2023 14:44
Show Gist options
  • Save hatemogi/fb6516c23c9d0c47e33bc1c0f8c195a5 to your computer and use it in GitHub Desktop.
Save hatemogi/fb6516c23c9d0c47e33bc1c0f8c195a5 to your computer and use it in GitHub Desktop.
PG function generates a mongodb's objectId
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