Ecto changeset shows errors One by one

Both actually offer the same level of guarantee anyways. Neither can use a proper db constraint to do it’s check on insert as information is still missing.

Which I do know. But the race is more obvious to the programmer and (some of) the users when doing it the JavaScript way…

I don’t know who is supposed to use my API then they are not forced to use Js like AJAX to send username and email to check. at least I think the unique_constraint is here and filter bad content, you think it is unsafe while unique_constraint is in my changeset pipeline ?

No, I do consider it usnafe to use a function with unsafe in its name when one doesn’t know about the implications and does understand them.

Also you still need both. For every field you check via unsafe_validate_unique you need a unique_constraint as well, as also a corresponding index.

Having a unsafe_validate_unique without its unique_constraint might cause corrupted databases (if also the unique index on the DB is missing) or crashing processes (if the index is there).

1 Like

Completely agree. I actually think having “unsafe” in the name is great, since it highlights a little care is required, similar to the ! at the end of some functions. The docs for unsafe_validate_unique highlight the point quite well:

This function exists to provide quick feedback to users of your application. It should not be relied on for any data guarantee as it has race conditions and is inherently unsafe. For example, if this check happens twice in the same time interval (because the user submitted a form twice), both checks may pass and you may end-up with duplicate entries in the database. Therefore, a unique_constraint/3 should also be used to ensure your data won’t get corrupted.

3 Likes