luzaranza

luzaranza

How to update a record in table using Repo without race conditions?

According to the stock example cited in elixir Ecto 3.4.6 docs …

post = MyRepo.get!(Post, 42)
post = Ecto.Changeset.change post, title: "New title"
case MyRepo.update post do
  {:ok, struct}       -> # Updated with success
  {:error, changeset} -> # Something went wrong
end

This code appears to be telling me that I must first attempt to get a record from the “Repo”, and only then if it deems my request acceptable, consider updating it with the proposed changes (this because Elixir insists that all changes/updates go via a changeset struct, and since the request may not have this struct in place while making its request, must first go about inventing it before the actual request).

So 2 steps.

Does Elixir have a single step way of doing this?

Most Liked

mbuhot

mbuhot

In addition to @Ninigi’s suggestion, you can avoid race conditions using locking:

Query.lock to lock a record during a transaction:

Repo.transaction(fn -> 
  post = 
    Post
    |> where(id: 42)
    |> lock("FOR UPDATE")
    |> Repo.one()

  changeset = Ecto.Changeset.change post, title: “New title”
  ... 
end)

Or Changeset.optimistic_lock to use a version field to detect races:

post = MyRepo.get!(Post, 42)
post = 
  post
  |> Changeset.change(title: “New title”)
  |> Changeset.optimistic_lock(:version)

case MyRepo.update post do
  {:ok, struct} -> # Updated with success
  {:error, changeset} -> # Something went wrong
end
Ninigi

Ninigi

If you want to use changesets to validate your changes before firing the database update, then yes, you need to load it first.

If you are willing to skip changesets, then you can use Repo.update_all/3.

{1, [updated_post]} =
  from(p in Post, where: p.id == 42, select: p)
  |> MyRepo.update_all(set: [title: "New title"])

This will fire a query that looks something like this

UPDATE "posts" AS p0 SET "title" = $1 WHERE (p0."id" = 42) RETURNING p0."id" ... ['New title']

Not all databases support the returning option, I know for a fact that postgresql does, but not sure about other databases.

EDIT: @mbuhot has a nicer solution that would not skip the changeset. Running the update in one database query might have its applications, but in this particular use-case I’d suggest his solution instead of mine.

demem123

demem123

Where Next?

Popular in Questions Top

earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
RisingFromAshes
I've read in another post that it may be possible with a router helper - but I couldn't find an appropriate one, and tbh, I'm still just ...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement