benonymus

benonymus

Unexpected Multi transaction result? Different value in Multi result compared to db value

Hey there,

I have the relatively simple Multi:

  def set_user_team_is_default(%UserTeam{user_id: user_id, team_id: team_id}) do
    Multi.new()
    |> Multi.update_all(
      :set_other_teams_to_non_default,
      from(ut in UserTeam, where: ut.user_id == ^user_id and ut.is_default == true),
      set: [is_default: false]
    )
    |> Multi.update(
      :set_to_default,
       # getting the user_team here or not getting and using the received one results in the same
      UserTeam.changeset(get_user_team(user_id, team_id), %{is_default: true})
    )
    |> Repo.transaction()
  end

It is used to set every user_team(that is default) is_default to false and then set one as default.

Now the following unexpected thing happened:

  1. User opened the page in browser A and then opened the same page in browser B at the same time.

  2. User selects team A as default in browser A - works as expected

  3. User selects same team A as default in browser B - user ends up without a default team.

Why does this happen?

The result of the multi when this occurs is this:

{:ok,
 %{
   set_other_teams_to_non_default: {1, nil},
   set_to_default: %XXX.UsersTeams.UserTeam{
     __meta__: #Ecto.Schema.Metadata<:loaded, "users_teams">,
     id: 3,
     inserted_at: ~N[2022-03-01 09:28:23],
     is_default: true,
     role: :admin,
     status: :active,
     team: #Ecto.Association.NotLoaded<association :team is not loaded>,
     team_id: 3,
     updated_at: ~N[2022-04-07 05:54:59],
     user: #Ecto.Association.NotLoaded<association :user is not loaded>,
     user_id: 2
   }
 }}

As you see in the result of the multi is_default is true for the user_team.
But!
If I fetch the user_team right after the multi it shows this:

%XXX.UsersTeams.UserTeam{
  __meta__: #Ecto.Schema.Metadata<:loaded, "users_teams">,
  id: 3,
  inserted_at: ~N[2022-03-01 09:28:23],
  is_default: false,
  role: :admin,
  status: :active,
  team: #Ecto.Association.NotLoaded<association :team is not loaded>,
  team_id: 3,
  updated_at: ~N[2022-04-07 05:54:59],
  user: #Ecto.Association.NotLoaded<association :user is not loaded>,
  user_id: 2
}

While the multi returns that is_default is true, in the database it is false!

According to the multi docs: Ecto.Multi — Ecto v3.14.0

If a multi is valid (i.e. all the changesets in it are valid), all operations will be executed in the order they were added.

Can someone explain as to why does this happen?

Fixing it is easy(patter match on the incoming user_team, if is_default: true ignore it), I am not asking for that, I want to understand why does it happen.

Marked As Solved

benonymus

benonymus

Something interesting:
If I change step 2 to be like this:

    |> Multi.update(:set_to_default, fn _ ->
      UserTeam.changeset(get_user_team(user_id, team_id), %{is_default: true})
    end)

It works as expected, always.

Also Liked

LostKobrakai

LostKobrakai

Multi.update / Repo.update is considered a noop (no query to the db) if there are no changes on the schema. If you have a user_team, which is the default, and then add a change of making it the default, then this is such a case of “no change present”. So you might not always get two queries here. It might be just one.

This doesn’t set “other” teams to not be defaults. This unsets all default teams not matter if it’s the current one or not.

What I can’t understand is why doing get_user_team(user_id, team_id) in the second step didn’t help resolve issues. Nothing should be a default, so making the current userteam the default should always work.

LostKobrakai

LostKobrakai

Step 2 only sets the default if the base data for the changeset have the user_team not be the default already (unless you use force_change). Otherwise the changeset sees a value to be set to the value already on the schema, which makes step 2 a noop. Not sure if that’s happening here / for you though.

LostKobrakai

LostKobrakai

Yes. I didn’t notice that. Without the anonymous function the code runs when defining the step, rather then when executing the step within the transaction.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement