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

you can also try to use Ecto.Multi — Ecto v3.14.0

Last Post!

DarckBlezzer

DarckBlezzer

Your code is ok,
I want to add another way to do the same result

Note: For others that want to learn elixir like me

Form
|> where(id: ^form_id)
|> Repo.update_all(set: [deleted_at: DateTime.utc_now])
# ^this returns `{1, nil}` because 1 row was updated.
# or return `{0, nil}` If no records were updated.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
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
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
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
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

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 130286 1222
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement