ryanditjia

ryanditjia

Deadlock detected when inserting multiple (Postgrex.Error 40P01)

Hello everyone, when I run my unit test, I sometimes (not all the time) run into this error:

(Postgrex.Error) ERROR 40P01 (deadlock_detected) deadlock detected

     hint: See server log for query details.
 
 Process 11437 waits for ShareLock on transaction 56033; blocked by process 11436.
 Process 11436 waits for ShareLock on transaction 56040; blocked by process 11437.

The test attempts to insert 3 records:

work_orders =
  for _ <- 1..3 do
    {:ok, work_order} = Documents.create_work_order(attrs)
    work_order
  end

expected_counters = [1, 2, 3]
assert expected_counters == work_orders |> Enum.map(& &1.counter)

create_work_order is an Ecto.Multi that:

  1. Inserts counter to counters DB (business requirement dictates that counter restarts from 1 every year)
  2. Grabs the returned counter to insert together to work_orders DB
  3. Repo.transaction()

Is the above loop a bad way to test? Or is my transaction function incorrect even though it works (pasted below)?

def create_work_order(attrs \\ %{}) do
  counter_changeset = Counter.changeset(%Counter{}, attrs)
  work_order_changeset = WorkOrder.creation_changeset(%WorkOrder{}, attrs)

  Multi.new()
  # Get the next counter of the year
  # If year doesn’t yet exist, create one and set counter to 1 (database default)
  |> Multi.insert(:next_counter, counter_changeset,
    # If year exists, increment the counter by 1
    conflict_target: :year,
    on_conflict: [inc: [counter: 1]]
  )
  # Insert work order, with counter added to the changeset
  |> Multi.insert(
    :work_order,
    fn %{next_counter: %{counter: counter}} ->
      work_order_changeset
      |> Ecto.Changeset.put_change(:counter, counter)
    end
  )
  |> Repo.transaction()
  |> case do
    {:ok, %{work_order: work_order}} ->
      {:ok, work_order}

    {:error, :next_counter, _changeset, _changes} ->
      # Return work_order_changeset for more thorough field checks
      {:error, %{work_order_changeset | action: :insert}}

    {:error, :work_order, changeset, _changes} ->
      {:error, changeset}
  end
end

First Post!

kip

kip

ex_cldr Core Team

Have you configured the Ecto Sandbox?

It will isolate each test in a transaction and rollback the transaction so each test has a consistent view of the data. It will also make it much less likely you will encounter deadlocks.

Where Next?

Popular in Questions Top

Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
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
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Other popular topics Top

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
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
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
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement