Skip to content

Instantly share code, notes, and snippets.

@golgote
Last active September 6, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save golgote/548f0b0b6fd4acf2b75e to your computer and use it in GitHub Desktop.
Save golgote/548f0b0b6fd4acf2b75e to your computer and use it in GitHub Desktop.
Random string function for PL/Lua
CREATE OR REPLACE FUNCTION random_string_pllua(string_length INTEGER, lowercase BOOLEAN DEFAULT false) RETURNS text
LANGUAGE pllua VOLATILE
AS $$
-- math.randomseed(socket.gettime()) -- seems to be needed by luajit only
local alnum = {
'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
}
local alnumlen = #alnum
local output = {}
local rand = math.random
if lowercase then
alnumlen = alnumlen - 26
end
local pos = rand(1, alnumlen - 10) + 10
table.insert(output, alnum[pos])
if (string_length > 1) then
for i = 2, string_length do
pos = rand(1, alnumlen)
table.insert(output, alnum[pos])
end
end
output = table.concat(output)
return output
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment