使用外键约束锁定更新行

时间:2017-11-29 10:22:49

标签: postgresql locking

我尝试过两次执行相同的UPDATE查询。

第一次事务没有锁,但我可以在第二次查询后看到一个行锁。

架构:

test=# \d t1
                 Table "public.t1"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 i      | integer |           | not null | 
 j      | integer |           |          | 
Indexes:
    "t1_pkey" PRIMARY KEY, btree (i)
Referenced by:
    TABLE "t2" CONSTRAINT "t2_j_fkey" FOREIGN KEY (j) REFERENCES t1(i)

test=# \d t2
                 Table "public.t2"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 i      | integer |           | not null | 
 j      | integer |           |          | 
 k      | integer |           |          | 
Indexes:
    "t2_pkey" PRIMARY KEY, btree (i)
Foreign-key constraints:
    "t2_j_fkey" FOREIGN KEY (j) REFERENCES t1(i)

现有数据:

test=# SELECT * FROM t1 ORDER BY i;
 i | j 
---+---
 1 | 1
 2 | 2
(2 rows)

test=# SELECT * FROM t2 ORDER BY i;
 i | j | k 
---+---+---
 3 | 1 |  
 4 | 2 |  
(2 rows)

更新查询和行锁状态:

test=# BEGIN;
BEGIN
test=# UPDATE t2 SET k = 123 WHERE i = 3;
UPDATE 1
test=# SELECT * FROM t1 AS t, pgrowlocks('t1') AS p WHERE p.locked_row = t.ctid;
 i | j | locked_row | locker | multi | xids | modes | pids 
---+---+------------+--------+-------+------+-------+------
(0 rows)

test=# UPDATE t2 SET k = 123 WHERE i = 3;
UPDATE 1
test=# SELECT * FROM t1 AS t, pgrowlocks('t1') AS p WHERE p.locked_row = t.ctid;
 i | j | locked_row | locker | multi |   xids   |       modes       | pids 
---+---+------------+--------+-------+----------+-------------------+------
 1 | 1 | (0,1)      | 107239 | f     | {107239} | {"For Key Share"} | {76}
(1 row)

test=# 

为什么postgres只在第二次尝试获取行锁?

顺便说一下,更新列t2.j的查询会立即在t1行创建新锁(ForKeyShare)。这种行为是有道理的,因为t2.j具有外键约束引用t1.i.但上面的查询似乎没有。

有人能解释这个锁吗?

PostgreSQL版本:9.6.3

1 个答案:

答案 0 :(得分:0)

好的,我明白了。

http://blog.nordeus.com/dev-ops/postgresql-locking-revealed.htm

  

这是Postgres中存在的优化。如果锁定管理器可以从第一个查询中找出外键未更改(在更新查询中未提及或设置为相同值),则它不会锁定父表。但是在第二个查询中,它的行为与文档中描述的一样(它将在ROW SHARE锁定模式下锁定父表,在FOR SHARE模式下引用行)

似乎MySQL对外键锁更明智,因为相同的UPDATE查询不会对MySQL进行此类锁定。