Created
May 4, 2021 14:07
-
-
Save ItsWendell/1989ef0a84993d3a2415e5511f05730e to your computer and use it in GitHub Desktop.
NanoID Implementation in PL/pgSQL for Postgres.
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
-- Highly performant NanoID implementation in PL/pgSQL. | |
-- | |
-- NOTE: This is a concept implementation, hasn't been battle tested. | |
-- | |
-- Version: 0.1 | |
-- Inspired by https://github.com/Jakeii/nanoid-postgres | |
-- @author github.com/ItsWendell | |
CREATE OR REPLACE FUNCTION gen_nanoid(size int DEFAULT 21) | |
RETURNS text AS $$ | |
DECLARE | |
id text := ''; | |
BEGIN | |
id := encode(gen_random_bytes((3.0 * (size::float / 4.0))::int), 'base64'); -- Generate random base64 string with atleast 'size' of characters. | |
id := translate(id, '/+', '_-'); -- Translate base64 to url safe base64 | |
id := left(id, size); -- Strip all unnessesary characters. | |
RETURN id; | |
END | |
$$ LANGUAGE PLPGSQL VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any feedback would be appreciated, here's also a little benchmark: