dkulchenko

dkulchenko

Performing a find-or-create in Ecto?

I can’t seem to figure out a good way of doing this safely. I need to do a find-or-create, so I first check to see if a given row exists in the table, if it doesn’t, I try and insert it, and if a uniqueness constraint fails, I try fetching it again (meaning it was created in between my initial fetch and my insert attempt).

The options that come to mind are:

  1. Try and insert it anyway and just handle the unique constraint changeset error. This doesn’t work because the failed constraint on the insert aborts the entire surrounding transaction forcing a rollback.

  2. Insert with an on_conflict: :nothing. I haven’t found any way to tell by the returned struct from Ecto whether or not the insert actually happened in this situation, making me unable to know if I’m working with the actual inserted row or if I need to refetch. The docs suggest checking for id being nil, but as Ecto is autogenerating my ID in either case, id will never be nil.

  3. Insert with an on_conflict: [set: …] to force a dummy update. I have no safe column to set in a DO UPDATE, as any column I’m using that could conflict could be inadvertently changed in this situation.

Any ideas?

First Post!

kokolegorille

kokolegorille

I find easier to do a create_or_find…

Most Liked

LostKobrakai

LostKobrakai

Do you really need to know if the insert did happen? Can you insert or do nothing and afterwards simply query for the upserted item without any of the results of the insert operation?

ryanwinchester

ryanwinchester

I’m just playing around with code here, but maybe something like this? :sweat_smile:

@spec fetch_or_create_thing(keyword, map) :: {:ok, Thing.t} | {:error, Ecto.Changeset.t}
def fetch_or_create_thing(fetch_by, attrs) do
  with nil <- get_thing_by(fetch_by),
       {:ok, thing} <- create_thing(attrs) do
    {:ok, thing}
  else
    %Thing{} = thing ->
      {:ok, thing}

    {:error, %Ecto.Changeset{} = changeset} ->
      if changeset.errors[:my_unique_field] == {"has already been taken", []} do
        fetch_or_create_thing(fetch_by, attrs)
      else
        {:error, changeset}
      end
  end
end

(assuming these functions exist)

@spec get_thing_by(keyword) :: Thing.t | nil
def get_thing_by(by) do
  Repo.get_by(Thing, by)
end

@spec create_thing(map) :: {:ok, Thing.t} | {:error, Ecto.Changeset.t}
def create_thing(attrs) do
  %Thing{}
  |> Thing.changeset(attrs)
  |> Repo.insert()
end

Although, with this code, if the my_unique_field is not part of the fetch_by keyword list and the unique field already exists or is in the keyword but also in the attrs map but they aren’t the same value, then that could cause infinite recursion, so you might want to check for that and raise an error… ¯\(ツ)

Where Next?

Popular in Questions Top

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
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
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
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
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

New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
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
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

We're in Beta

About us Mission Statement