How to not rollback transaction on failed insert because of unique constraint

The issue is that this behavior is database dependent, it isn’t something that Ecto is choosing to do. When you have a constraint violation in a postgres transaction this poisons the whole transaction, Ecto has no way to prevent this from happening.

However, you do! If you want to do an insert and not rollback, you can Repo.insert(on_conflict: :nothing) and check the return value. If the return value has no id value then no new record was inserted because the record already exists. If it does have an id, then it inserted a new record.

1 Like