Created
November 27, 2021 08:31
-
-
Save yuhangch/20b1b54acdc7e3c899ee86a6cb7d43df to your computer and use it in GitHub Desktop.
postgresql short id function
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
-- https://stackoverflow.com/a/41988979/10936088 | |
CREATE EXTENSION IF NOT EXISTS pgcrypto; | |
CREATE OR REPLACE FUNCTION generate_uid(size INT) RETURNS TEXT AS $$ | |
DECLARE | |
characters TEXT := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
bytes BYTEA := gen_random_bytes(size); | |
l INT := length(characters); | |
i INT := 0; | |
output TEXT := ''; | |
BEGIN | |
WHILE i < size LOOP | |
output := output || substr(characters, get_byte(bytes, i) % l + 1, 1); | |
i := i + 1; | |
END LOOP; | |
RETURN output; | |
END; | |
$$ LANGUAGE plpgsql VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment