I have a table in Postgres that contains columns for a userid and an external id that will be used in API calls to an external service. I have to create the external id on my side, validate that is unique, and store it in PG before calling the external API. This article comes close to what I want: How can I generate a unique string per record in a table in Postgres? However, there's the possibility of conflict if two concurrent calls generate the same id. What I would like to do is have a loop that generates a random string, then attempts to insert that with the user id into the table. It should fail if the random string already exists (there is a unique constraint on the column). If it fails, it should generate another id and attempt to insert that (once I get working code I will add a counter to prevent hammering the db).
How would you go about writing that loop? The loop should continue if the INSERT returns an error (constraint check), otherwise loop again. I've checked the Postgres docs and can't seem to find (or am missing) the way to check the error code/status on a query.
UPDATE
I've come up with a possible solution, but need to flesh it out. The following is in pidgeon-sql, just me thinking around the problem:
success = true;
LOOP
-- create random string function
BEGIN
insert string
EXCEPTION
success = false;
EXIT WHEN success;
END;