来自非直接相关表的Postgresql死锁

时间:2020-03-02 16:08:12

标签: database postgresql database-deadlocks

运行postgresql 11.2

我有3个表,分别是Table1,Table2和Table3。

Table2和Table3链接到Table1。

因此,它们都有一个外键和一个字段:

"fk38dc51d86836z0e5" FOREIGN KEY (table1_id) REFERENCES table1(id)

尽管涉及的查询未使用外键字段,但我最近在这两个表上陷入了僵局。

Process 19819 waits for ShareLock on transaction 254244062; blocked by process 19930.
    Process 19930 waits for ShareLock on transaction 254244063; blocked by process 19819.
    Process 19819: update Table1 set lastUpdated=$1, user_id=$2 where id=$3
    Process 19930: update Table2 set lastUpdated=$1, version=$2, content=$3, extra=$4 where id=$5 and version=$6

这2个表之间的唯一链接是它们与Table1的链接。它们并不彼此直接链接。

但是没有一个查询使用Table1的外键作为查询的一部分。

这是怎么回事?为什么完全陷入僵局?

1 个答案:

答案 0 :(得分:1)

没有外键就可能发生死锁:最可能的原因是2个并发事务在同一行上以相同的锁但顺序不同。

例如在会话1中:

postgres=# begin;
BEGIN
postgres=# update t1 set x=1 where x=0;
UPDATE 1
postgres=# update t2 set x=1 where x=0;
UPDATE 1
postgres=# 

在会话2中:

postgres=# begin;
BEGIN
postgres=# update t2 set x=2 where x=0;
UPDATE 1
postgres=# update t1 set x=2 where x=0;
ERROR:  deadlock detected
DETAIL:  Process 26871 waits for ShareLock on transaction 191533; blocked by process 26777.
Process 26777 waits for ShareLock on transaction 191534; blocked by process 26871.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,3) in relation "t1"
postgres=# 
相关问题