Ecto.Changeset.optimistic_lock and Ecto.Multi

I’m trying to make sense of something and the fact that I don’t understand it might prove that I’m using it wrong.

I’ve got various changeset functions exposed for an Ecto Schema. They add an optimistic lock check to the changeset structs.

As part of a large Ecto Multi, I noticed that when the update fails because of a lock mismatch, an exception is raised rather than an error tuple.
This kind of defeats the purpose of using an Ecto Multi in the first place, as the goal is to have the result of multi |> Repo.transaction() piped into a case statement, to gracefully let the user know what’s happening.

What is wrong in my logic?

So the issue with optimistic locks is that you don’t get to know that the lock field was the actual issue causing the more general error of trying to update a stale record. E.g. the original record could’ve been deleted in the meantime as well. So the changeset functionality around optimistic_lock cannot handle the resulting error. There is a stale_error_field config on Repo.update though, which you can use to catch the exception and instead have it reported as an error.

2 Likes

Thanks a lot @LostKobrakai . Sorry for the late answer!