Locking Records with Elixir’s Ecto

As a followup to a previous post about locking records with transactions, I’m now going to show how it’s done with Elixir, and specifically the Ecto library (comparable to ActiveRecord).

Instead of using:

lock: true
Ecto asks you to pass the specific type of locking scheme. In the case of pessimistic locking, that is:
lock: "FOR UPDATE"
That can just be passed into your query with the other parameters.

And of course, be sure to wrap all of this in a transaction, otherwise your lock will not stick around until you’re done working with the record:


Repo.transaction(fn ->
...
end)

Full example:


import Ecto.Query
alias MyRepo.Repo

Repo.transaction(fn ->
query = from a in Account,
where: a.company_id == ^1,
lock: "FOR UPDATE"

account = Repo.all(query) |> List.first

new_balance = account.balance + 5
Repo.update!(%{account | balance: new_balance})
end)

Found here:
https://hexdocs.pm/ecto/0.2.5/Ecto.Query.html#lock/2

Posted in Ecto, Elixir

Leave a Reply

Your email address will not be published. Required fields are marked *

*