Skip to content

Instantly share code, notes, and snippets.

@JuneKelly
Last active August 29, 2015 13:56
Show Gist options
  • Save JuneKelly/9307404 to your computer and use it in GitHub Desktop.
Save JuneKelly/9307404 to your computer and use it in GitHub Desktop.
-- generate a string suitable for use as a random identifier
-- ex: "C9SLcH4r", "xlnU4Vu-", "Cb-7kWtY"
SELECT CAST(regexp_replace(
encode(gen_random_bytes(6), 'base64'),
'[/=+]',
'-', 'g'
) AS text);
-- as a function
CREATE OR REPLACE FUNCTION random_slug()
RETURNS text
AS
$$ SELECT CAST(regexp_replace(
encode(gen_random_bytes(6), 'base64'),
'[/=+]',
'-', 'g'
) AS text);$$
LANGUAGE SQL
-- or just as hex
SELECT CAST(encode(gen_random_bytes(8), 'hex') as varchar(16));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment