gmocamilotd
12/4/2017 - 1:38 AM

generate a unique string per record in a table in Postgres

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

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

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.