【发布时间】:2020-04-16 04:13:44
【问题描述】:
我试图弄清楚 PostgreSQL 中可序列化的隔离级别是如何工作的。理论上,根据 PostgreSQL 自己的文档,PostgreSQL 应该足够聪明,能够以某种方式检测序列化冲突并自动回滚有问题的事务。然而,当我自己尝试使用可序列化隔离级别时,我偶然发现了很多误报,并开始怀疑我自己对可序列化概念或 PostgreSQL 实现它的理解。您可以在下面找到此类误报的最简单示例之一:
create table mytab(
class integer,
value integer not null
);
create index mytab_class_idx on mytab (class);
insert into mytab (class, value) values (1, 10);
insert into mytab (class, value) values (1, 20);
insert into mytab (class, value) values (2, 100);
insert into mytab (class, value) values (2, 200);
表格数据如下:
class | value
-------+-------
1 | 10
1 | 20
2 | 100
2 | 200
然后我运行两个并发事务。代码中的Step n cmets 显示了我执行语句的顺序。根据https://stackoverflow.com/a/42303225/3249257 的建议,我明确禁用了顺序扫描以强制 PostgreSQL 使用索引:
SET enable_seqscan=off;
交易A:
begin; -- step 1
select sum(value) from mytab where class = 1; -- step 2
insert into mytab(class, value) values (3, 30); -- step 5
commit; -- step 7
事务 B:
begin; -- step 3
select sum(value) from mytab where class = 2; -- step 4
insert into mytab(class, value) values (4, 300); -- step 6
commit; -- step 8
据我了解,这两个交易之间不应该有任何冲突。他们不接触相同的行。但是,当我提交第二个事务时,它会失败并出现以下错误:
[40001] ERROR: could not serialize access due to read/write dependencies among transactions
Detail: Reason code: Canceled on identification as a pivot, during commit attempt.
Hint: The transaction might succeed if retried.
这里发生了什么?我对可序列化隔离级别的理解有缺陷吗?这是这个答案https://stackoverflow.com/a/50809788/3249257中提到的PostgreSQL启发式的失败吗?
我正在使用PostgreSQL 11.5 on x86_64-apple-darwin18.6.0, compiled by Apple LLVM version 10.0.1 (clang-1001.0.46.4), 64-bit。
【问题讨论】:
-
你用的是什么版本?你能告诉我们你是如何交错命令的吗?如果我运行 A 的前 3 行,然后运行 B 的前 3 行,然后提交 A,然后提交 B,我没有得到问题。
-
@jjanes 我已编辑问题以回答您的问题。
-
@LukaszSzozda 这不是整个表的排他锁,但您的评论极大地帮助我了解这里发生了什么。我已经在下面发布了我的答案。
-
@DenisStafichuk 很高兴我能提供帮助。干得好:)
标签: postgresql transactions serializable