gpt4 book ai didi

Elixir Repo.insert_all/2 和唯一约束

转载 作者:行者123 更新时间:2023-12-02 03:15:29 25 4
gpt4 key购买 nike

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

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

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

但就目前而言,这似乎是一个黑客。因为我知道有一个内置的变更集机制可以处理唯一的约束,但我不知道如何使用 Repo.insert_all/3

包含系统的这一部分

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

(我当然指的是unique_constraint/2)

我知道我可以:

  • 使用 Multi 来执行此操作,但这会在后端创建单独的查询,而不是将其作为一个大查询来执行

  • 使用 tryrescue block 保留代码,但我想看看是否有更 Elixir-y 的方法来解决这个问题,因为模式匹配的原理,并让它崩溃术语。

最佳答案

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 选项也可能用于提供不安全片段

关于Elixir Repo.insert_all/2 和唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com