Skip to content

Instantly share code, notes, and snippets.

@coreybutler
Last active December 29, 2022 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coreybutler/e4034d18ffeb8d73f0ac1583939dd013 to your computer and use it in GitHub Desktop.
Save coreybutler/e4034d18ffeb8d73f0ac1583939dd013 to your computer and use it in GitHub Desktop.
PostgreSQL NANOID
CREATE FUNCTION "nanoid"("size" int4 DEFAULT 21)
RETURNS text
LANGUAGE plpgsql
STABLE
AS
$$
DECLARE
id text := '';
i int := 0;
urlAlphabet char(64) := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_0123456789';
bytes bytea := gen_random_bytes(size);
byte int;
pos int;
BEGIN
WHILE i < size LOOP
byte := get_byte(bytes, i);
pos := (byte & 63) + 1; -- + 1 because substr starts at 1
id := id || substr(urlAlphabet, pos, 1);
i = i + 1;
END LOOP;
RETURN id;
END
$$
;
@coreybutler
Copy link
Author

Conceptually based on https://github.com/ai/nanoid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment