Skip to content

Instantly share code, notes, and snippets.

@matschik
Last active January 27, 2024 15:37
Show Gist options
  • Save matschik/2b1671e224fe59909bdb35a9b6163585 to your computer and use it in GitHub Desktop.
Save matschik/2b1671e224fe59909bdb35a9b6163585 to your computer and use it in GitHub Desktop.
PostgreSQL function for automatic Object IDs. Inspired by Stripe: https://dev.to/stripe/designing-apis-for-humans-object-ids-3o5a
CREATE OR REPLACE FUNCTION random_string(length INTEGER) RETURNS TEXT AS $$
DECLARE
chars TEXT[] := ARRAY['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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
result TEXT := '';
i INTEGER;
BEGIN
FOR i IN 1..length LOOP
result := result || chars[1 + RANDOM() * (array_length(chars, 1) - 1)];
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql VOLATILE;
CREATE OR REPLACE FUNCTION prefixed_random_id(prefix TEXT)
RETURNS TEXT AS $$
BEGIN
RETURN prefix || '_' || random_string(24);
END;
$$ LANGUAGE plpgsql;
CREATE TABLE "user" (
"id" TEXT NOT NULL DEFAULT prefixed_random_id('u'::text),
);
-- example of `id` value: u_k81fapyf1l7b8wc2kd94fc05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment