Skip to content

Instantly share code, notes, and snippets.

@yerffejytnac
Created January 17, 2022 19:13
Show Gist options
  • Save yerffejytnac/c30c346a00145975065a984c3cb9744d to your computer and use it in GitHub Desktop.
Save yerffejytnac/c30c346a00145975065a984c3cb9744d to your computer and use it in GitHub Desktop.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE OR REPLACE FUNCTION nanoid(size int DEFAULT 12)
RETURNS text AS $$
DECLARE
id text := '';
idx int := 0;
alphabet char(62) := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
bytes bytea := gen_random_bytes(size);
byte int;
pos int;
BEGIN
WHILE idx < size LOOP
byte := get_byte(bytes, idx);
pos := (byte & 61) + 1;
id := id || substr(alphabet, pos, 1);
idx = idx + 1;
END LOOP;
RETURN id;
END
$$ LANGUAGE PLPGSQL STABLE;
-- SELECT nanoid(9);
-- Output: 'SmOiLHnGP'
@yerffejytnac
Copy link
Author

Nano ID Collision Calculator: https://zelark.github.io/nano-id-cc/

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