MagicStack / MagicStack/asyncpg

advice: best bulk upsert method that still allows to track # of affected rows?

未关闭
#755 8 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
8.1k
派生
468
PR 合并指标
30 天内没有已合并 PR

描述

I've been relying on the newest implementation of executemany() to perform bulk upserts, but it has the shortcoming that it will not allow to easily determine the number of affected rows by parsing the statusmsg.

The number of effectively upserted rows can easily be less than the number of rows I attempt to upsert, since I qualify my ON CONFLICT clause with a further WHERE clause specifying that the update should only happen if the new and excluded tuples are distinct.

```
INSERT INTO "table_name" AS __destination_row (
id,
other_column
) VALUES ($1, $2)
ON CONFLICT (id)
DO UPDATE SET
id = excluded.id,
other_column = excluded.other_column
WHERE
(__destination_row.id IS DISTINCT FROM excluded.id)
OR
(__destination_row.other_column IS DISTINCT FROM excluded.other_column)
;
```

(regular Postgres would allow for a much terser syntax, but this is the only syntax that is accepted by CockroachDB)

Suppose that at times knowing the exact number of effectively upserted rows is more crucial than the bulk performance, and yet I would prefer not to go to the extreme of upserting one row at a time, what would be the best compromise?

Should I rely on a temporary table and then upserting into the physical tables from that temporary table?

```
INSERT INTO "table_name" AS __destination_row (
id,
other_column
) SELECT (
id,
other_column
) FROM "__temp_table_name"
ON CONFLICT (id)
DO UPDATE SET
id = excluded.id,
other_column = excluded.other_column
WHERE
(__destination_row.id IS DISTINCT FROM excluded.id)
OR
(__destination_row.other_column IS DISTINCT FROM excluded.other_column)
;
```

Should I instead use a transaction with several individual upserts of values once again provided by the client?

Are there other approaches I should explore?

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先查看 asyncpg 的 executemany() 入口点以及 issue 中描述的 statusmsg 行为。比较通过临时表执行批量 upsert 与在事务中逐个执行 upsert 的方式,然后记录受支持的折中方案,以便在不要求逐行操作的情况下获取确切的受影响行数。

由索引模型根据 Issue 内容生成。

评估

技术栈
postgresql, python
领域
databases
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。