Skip to content

Instantly share code, notes, and snippets.

@Tostino
Created January 22, 2021 20:09
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Tostino/ca104bff40e704b6db70b9af492664ef to your computer and use it in GitHub Desktop.
Save Tostino/ca104bff40e704b6db70b9af492664ef to your computer and use it in GitHub Desktop.
PL/PGSQL Function for uuid_time_nextval
CREATE FUNCTION uuid_time_nextval(interval_length int default 60, interval_count int default 65536)
RETURNS uuid
LANGUAGE plpgsql
AS $$
DECLARE
v_i int;
v_prefix_bytes int = 0;
v_time bigint;
v_bytes int[16] = '{}';
v_hex text[16] = '{}';
BEGIN
IF interval_length < 1
THEN
RAISE EXCEPTION 'length of interval must be a positive integer';
END IF;
IF interval_count < 1
THEN
RAISE EXCEPTION 'number of intervals must be a positive integer';
END IF;
v_time := floor(extract(epoch FROM clock_timestamp()) / interval_length);
v_i := interval_count;
WHILE v_i > 1 LOOP
v_i := v_i / 256;
v_prefix_bytes := v_prefix_bytes + 1;
END LOOP;
v_i := 1;
WHILE v_i <= v_prefix_bytes LOOP
v_bytes[v_i] := v_time >> (8 * (v_prefix_bytes - v_i)) & 255;
v_i := v_i + 1;
END LOOP;
WHILE v_i <= 16 LOOP
v_bytes[v_i] := floor(random() * 256);
v_i := v_i + 1;
END LOOP;
FOR v_i IN 1..16 LOOP
v_hex[v_i] := lpad(to_hex(v_bytes[v_i]), 2, '0');
END LOOP;
RETURN array_to_string(v_hex, '');
END $$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment