-
-
Save ShonFrazier/3e862fa029a5846377362355bb15d2c6 to your computer and use it in GitHub Desktop.
PostgreSQL NANOID
This file contains 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 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 | |
$$ | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment