为什么 PostgreSQL 中止这个可序列化的计划

Why does PostgreSQL abort this serializable schedule

理论指出,当且仅当它们的并发执行等同于它们可能的串行执行之一时,一组并发事务是可序列化的。

现在下面事务T1和T2的并发执行是可序列化的,因为相当于串行执行"T1 then T2"

T1: r1x   w1y  c1
T2:    w2x   c2

(i.e., T1 reads x, T2 writes x, T1 writes y, T2 commits, and finally, T1 commits)

然而,当在 PostgreSQL 10.4 中尝试时,像这样:

T1: begin
T1: set transaction isolation level serializable;
T2: begin
T2: set transaction isolation level serializable;
T2: update variables set value = value + 1 where name = 'x'
T1: update variables set value = value + 1 where name = 'y'
T2: commit
T1: commit

当此事务尝试提交时,数据库中止 T1。为什么?

PostgreSQL 使用启发式方法来确定是否中止可序列化事务,因为这很难做到准确。因此,即使存在等效的串行执行(误报),交易也会中止。

但我怀疑在这种情况下有不同的原因。如果查看执行计划,您可能会看到顺序扫描。现在顺序扫描读取 所有 行,因此 T2 在更新期间读取了 y

可序列化事务的行为取决于选择的执行计划!