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?

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

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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
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
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
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

Other popular topics Top

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
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

We're in Beta

About us Mission Statement