Skip to content

Instantly share code, notes, and snippets.

@gmocamilotd
Last active December 4, 2017 04:54
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 gmocamilotd/ef900c6937c67dd8c9c22b862c4d4d80 to your computer and use it in GitHub Desktop.
Save gmocamilotd/ef900c6937c67dd8c9c22b862c4d4d80 to your computer and use it in GitHub Desktop.
Ideally there would be a way for Postgres to handle both of these concerns: generate the string ensure its uniqueness source: https://stackoverflow.com/questions/19530736/how-can-i-generate-a-unique-string-per-record-in-a-table-in-postgres
CREATE FUNCTION make_uid() RETURNS text AS $$
DECLARE
new_uid text;
done bool;
BEGIN
done := false;
WHILE NOT done LOOP
new_uid := md5(''||now()::text||random()::text);
done := NOT exists(SELECT 1 FROM my_table WHERE uid=new_uid);
END LOOP;
RETURN new_uid;
END;
$$ LANGUAGE PLPGSQL VOLATILE;
I don't claim the following is efficient, but it is how we have done this sort of thing in the past.
make_uid() can be used as the default for a column in my_table. Something like:
*******
ALTER TABLE my_table ADD COLUMN uid text NOT NULL DEFAULT make_uid();
************
md5(''||now()::text||random()::text) can be adjusted to taste.
You could consider encode(...,'base64') except some of the characters used in base-64 are not URL friendly.
piedes encontrar otras respuestas es:
https://github.com/conjurinc/pg_random_id
ó
https://github.com/norman/friendly_id
considerar
https://stackoverflow.com/questions/41970461/how-to-generate-a-random-unique-alphanumeric-id-of-length-n-in-postgres-9-6?noredirect=1&lq=1
https://stackoverflow.com/questions/40006558/generate-unique-random-strings-in-plpgsql?noredirect=1&lq=1
https://stackoverflow.com/questions/43348846/unique-string-with-at-least-two-differences?noredirect=1&lq=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment