Last active
January 27, 2024 15:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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