Elixir Repo.insert_all/2 和唯一约束

Elixir Repo.insert_all/2 and unique constraint

我今天有一个相当有趣的问题。我正在尝试使用 Ecto 函数将 CSV 文件批量插入到我的数据库中 Repo.insert_all/2 但是,有一件事困扰着我。

问题出在我的上下文中的以下代码:

defmodule AppName.Roles do
  def bulk_insert(array_of_maps) do
    try do 
      Repo.insert_all(Role, array_of_maps)
    rescue
      exception in Postgrex.Error ->
        _handle_exception(exception) # or whatever
    end
  end
end 

虽然现在,这似乎是 hack。因为我知道有一个内置的变更集机制可以处理独特的约束,但我不知道如何用 Repo.insert_all/3

包含系统的那部分

但是由于 insert_all 函数不关心 变更集 这使得这变得更加困难。

(我当然指的是unique_constraint/2

我知道我可以:

Ecto.Repo.insert_all/3 接受选项列表,其中之一是

  • :on_conflict — It may be one of :raise (the default), :nothing, :replace_all, :replace_all_except_primary_key, {:replace, fields}, a keyword list of update instructions or an Ecto.Query query for updates.

通常,无论人们是否想处理冲突,他们都会将该选项设置为有一定帮助,而不是引发异常。

也可能使用 :conflict_target 选项来提供 不安全的片段