On_conflict on new item?

Hey there,

I have a Multi where I create and insert a business and some other structs that depend on it such as admin relation to the creating user.

In the business changeset I am generating a slug using:

with unique constraint on the slug.
If the slug is used the Multi fails and the user needs to change the slug and retry, nothing surprising here.

Now business requirements changed and if the unique constraint fails it should keep retrying by appending
_x+1 until it gets a unique slug.
Essentially append a number and keep increasing it until it is unique.

This could be done in many ways like checking the slug before attempting to insert in the multi and then passing the slug that would be accepted but that feels a bit manual.

I was looking at on_conflict
https://hexdocs.pm/ecto/3.5.5/Ecto.Adapter.Schema.html#t:on_conflict/0
https://hexdocs.pm/ecto/Ecto.Repo.html#c:insert/2

But it updates the one in the db, not the item I am trying to insert, is it possible to have the on_conflict applied to the item that I am trying to insert?

1 Like

I don’t think so, the on_conflict Elixir option maps to the postgres feature ON CONFLICT which has the available actions: DO NOTHING and DO UPDATE SET, both of which apply to the existing row. This makes sense because the feature is called “upsert” which is basically “insert or update”.

2 Likes

Yes the more I started to look into it, this seems less and less likely to work, thanks for the comment!