Created
April 26, 2021 08:15
-
-
Save Adron/f37ae1f28d2f87153d617183a9c4b43c to your computer and use it in GitHub Desktop.
Short URL Safe IDs for Postgres
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 OR REPLACE FUNCTION gen_unique_short_id() returns text | |
language plpgsql | |
as $$ | |
DECLARE | |
id text; | |
BEGIN | |
id := encode(gen_random_bytes(6), 'base64'); | |
id := replace(id, '/', '_'); | |
id := replace(id, '+', '_'); | |
RETURN id; | |
END; | |
$$; | |
alter function gen_unique_short_id() owner to postgres; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You also might be able to get by with:
encode(gen_random_bytes(6), 'hex');