Skip to content

Instantly share code, notes, and snippets.

@shanginn
Last active October 22, 2024 07:09
Show Gist options
  • Save shanginn/169f59db543c0f9cfd90c434c7c966ca to your computer and use it in GitHub Desktop.
Save shanginn/169f59db543c0f9cfd90c434c7c966ca to your computer and use it in GitHub Desktop.
Fast unique smol ID generator
-- Function: smolid
-- Generates a random string of a specified size using the provided alphabet
-- size: The length of the generated string (default is 21)
-- alphabet: A string of characters from which the random string will be created (default is upper/lower case letters and digits)
CREATE OR REPLACE FUNCTION smolid(
size INTEGER DEFAULT 21,
alphabet TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
)
RETURNS TEXT AS $$
DECLARE
result TEXT := '';
i INTEGER;
BEGIN
FOR i IN 1..size LOOP
result := result || substr(alphabet, floor(random() * length(alphabet) + 1)::int, 1);
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;
import random
def smolid(self, size: int = 21, alphabet: str = string.ascii_letters + string.digits) -> str:
"""
Generate a random ID of the given size using the specified alphabet.
:param size: Length of the random ID to generate, defaults to 21
:param alphabet: Characters to use for generating the ID, defaults to alphanumeric characters
:return: Randomly generated ID as a string
"""
return ''.join(random.choice(alphabet) for _ in range(size))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment