Ecto - update_all 错误期间返回值的格式

Ecto - format of returned value during error on update_all

使用Ecto的update_all更新所有匹配记录时,错误情况下返回值的格式是什么?该文档对预期返回的内容有点模糊 - 'It returns a tuple containing the number of entries and any returned result as second element.'

例如,假设有 10 条匹配记录,无论出于何种原因,update 操作对其中 2 条记录失败。我的假设是返回值如下所示:

{8, [{:error, error info}, {:error, error info}]}

对吗?错误会作为元组列表返回吗?

否,如果 UPDATE 查询失败,Repo.update_all 会抛出错误。如果发生这种情况,实际上不会在数据库中保存任何更改。

returned 元组第二个元素中的列表是您使用 RETURNING 子句要求查询 return 的数据,例如query |> Repo.update_all([], returning: [:id]) 将 return 仅填充 id 字段的更新结构,returning: true 将 return 填充所有字段的结构。

下面是更新查询的一条记录中发生错误的示例:

iex(1)> from(p in Post, select: p.id) |> Repo.all
[debug] QUERY OK source="posts" db=1.1ms queue=0.1ms
SELECT p0."id" FROM "posts" AS p0 []
[1, 2, 3]

iex(2)> from(p in Post, where: p.id in [2, 3], update: [set: [id: fragment("CASE WHEN ? = 3 THEN 1 ELSE ? END", p.id, p.id)]]) |> Repo.update_all([])
** (Postgrex.Error) ERROR 23505 (unique_violation): duplicate key value violates unique constraint "posts_pkey"

    table: posts
    constraint: posts_pkey

Key (id)=(1) already exists.
[debug] QUERY ERROR source="posts" db=4.8ms
UPDATE "posts" AS p0 SET "id" = CASE WHEN p0."id" = 3 THEN 1 ELSE p0."id" END WHERE (p0."id" IN (2,3)) []
    (ecto) lib/ecto/adapters/sql.ex:436: Ecto.Adapters.SQL.execute_and_cache/7