Search code examples
elixirecto

Put simply, how does Ecto know that a struct is "Stale"


In the Changeset documentation, it says:

When a conflict happens (a record which has been previously fetched is being updated, but that same record has been modified since it was fetched), an Ecto.StaleEntryError exception is raised.

There are a number of conversations on StackOverflow, GitHub, and other places about how to fix various scenarios that involve a StaleEntryError. But there is no explanation of how Ecto knows that a struct is stale.

What is the underlying mechanism?


Solution

  • The Ecto.Changeset documentation you linked to is pretty self explanatory:

    Optimistic locking works by keeping a “version” counter for each record; this counter gets incremented each time a modification is made to a record. Hence, in order to use optimistic locking, a field must exist in your schema for versioning purpose. Such field is usually an integer but other types are supported.

    Here's the Ecto implementation.