Created
June 19, 2018 11:38
-
-
Save spidgorny/b174c7a8fc74f6eb6da0a194c106f03a to your computer and use it in GitHub Desktop.
YouTube like unique ID in PostgreSQL without plugins
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
-- function returns random string key like: cg8rP, QUdfX, 4veH7 | |
CREATE OR REPLACE FUNCTION you_id() | |
RETURNS varchar AS $$ | |
DECLARE | |
num FLOAT; | |
key TEXT; | |
bin BYTEA; | |
BEGIN | |
num := random() * 2147483647; | |
key := md5(num::text); | |
bin := decode(key, 'hex'); | |
key := encode(bin, 'base64'); | |
key := replace(key, '+', '-'); | |
key := replace(key, '/', '_'); | |
key := substring(key from 1 for 5); | |
RETURN key; | |
END; | |
$$ | |
language 'plpgsql'; | |
SELECT you_id(); | |
-- RNfTL | |
-- inspiration from | |
-- https://blog.andyet.com/2016/02/23/generating-shortids-in-postgres |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment