Skip to content

Instantly share code, notes, and snippets.

@yuhangch
Created November 27, 2021 08:31
Show Gist options
  • Save yuhangch/20b1b54acdc7e3c899ee86a6cb7d43df to your computer and use it in GitHub Desktop.
Save yuhangch/20b1b54acdc7e3c899ee86a6cb7d43df to your computer and use it in GitHub Desktop.
postgresql short id function
-- 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