How can repeated keys atomically add to one event counter?

UPSERT can update an existing row on a unique-key conflict. The excluded row supplies the proposed increment.

SQLite example and interpretation

Class A has two events and receives three more, giving five. Replaying the same message adds again, so message deduplication is a separate concern.

CREATE TABLE c(k TEXT PRIMARY KEY,n INTEGER);
INSERT INTO c VALUES('A',2);
INSERT INTO c VALUES('A',3) ON CONFLICT(k) DO UPDATE SET n=c.n+excluded.n;
SELECT n FROM c;

Result [[5]]

中文

重复键到达时如何原子地累加同一类事件?

UPSERT 可在唯一键冲突时执行更新。excluded 代表拟插入的行,可把其增量加到现有值。

SQLite 示例与适用条件

类别 A 原有 2 次,又收到 3 次,计数合为 5。重复投递同一消息仍会重复累加,消息去重需单独设计。

CREATE TABLE c(k TEXT PRIMARY KEY,n INTEGER);
INSERT INTO c VALUES('A',2);
INSERT INTO c VALUES('A',3) ON CONFLICT(k) DO UPDATE SET n=c.n+excluded.n;
SELECT n FROM c;

结果 [[5]]

References / 参考来源

Keep reading / 继续阅读