I want to insert a record which has a field for a unique slug. I want to check if it already exists in the database and, if it does, add a number to the end. Check it again and if it still exists, increment the number and try again. I do this until it doesn’t exist.
eg. myslug, myslug1, myslug2, myslug3, etc.
I’m thinking that the way to do this is with a While action but I can’t find any documentation on how to use it.
Should I put a query within the while loop? If so, what goes in the Expression?
Set Value (global) slug = "myslug"
Set Value (global) inserted = false
Set Value (global) i = 0
While !inserted:
Set Value currentSlug = slug
Condition i > 0:
Set Value currentSlug = slug + i
slugExists = Database Single Query: SELECT id WHERE slug = :currentSlug
if slugExists:
Set Value (global) i = i+1
else:
Database Insert (...) slug = :currentSlug
Set Value (global) inserted = true
The code above is susceptible to a race condition and could be enhanced further. Instead of doing a SELECT to check if the slug exists, do an INSERT directly and see if it failed to insert (assuming the column slug has the “unique” property toggled in the database manager). I didn’t show you the pseudocode with INSERT because I don’t remember how to check if it failed, so I’d rather give you a working solution