-- While it comes with a default configuration, the function is designed to be flexible,
-- allowing for customization to meet specific needs.
DROPFUNCTIONIFEXISTSnanoid(int,text,float);
CREATEORREPLACEFUNCTIONnanoid(
sizeintDEFAULT21,-- The number of symbols in the NanoId String. Must be greater than 0.
alphabettextDEFAULT'_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',-- The symbols used in the NanoId String. Must contain between 1 and 255 symbols.
additionalBytesFactorfloatDEFAULT1.6-- The additional bytes factor used for calculating the step size. Must be equal or greater then 1.
)
RETURNStext-- A randomly generated NanoId String
LANGUAGEplpgsql
VOLATILE
LEAKPROOF
PARALLELSAFE
AS
$$
DECLARE
alphabetArraytext[];
alphabetLengthint:=64;
maskint:=63;
stepint:=34;
BEGIN
IFsizeISNULLORsize<1THEN
RAISEEXCEPTION'The size must be defined and greater than 0!';
sizeint,-- The desired length of the generated string.
alphabettext,-- The set of characters to choose from for generating the string.
maskint,-- The mask used for mapping random bytes to alphabet indices. Should be `(2^n) - 1` where `n` is a power of 2 less than or equal to the alphabet size.
stepint-- The number of random bytes to generate in each iteration. A larger value may speed up the function but increase memory usage.