Created
January 17, 2022 19:13
-
-
Save yerffejytnac/c30c346a00145975065a984c3cb9744d to your computer and use it in GitHub Desktop.
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 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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nano ID Collision Calculator: https://zelark.github.io/nano-id-cc/