PostgreSQL Tutorial: Table Locks and Row Locks

There are two main types of locks in PostgreSQL, a table lock and a row lock.

PostgreSQL also provides page locks and advisory locks. But, you don’t need to pay attention to this. It is for the integrity of the lock.

table lock

Table locking is obvious, it locks the entire table. Table locks are also divided into many modes.

There are many modes of table locking, among which the two most core ones are:

  • ACCESS SHARE: Shared lock (read lock), read operations are not blocked, but parallel write operations are not allowed.
  • ACCESS EXCLUSIVE: Mutual exclusion lock (write lock), no matter what operation comes in, it will block.

For details, please view the official website documentation: http://postgres.cn/docs/12/explicit-locking.html

Implementation of table lock:

Check out a wave of grammar firstimage.png

It is to open the table lock based on LOCK, specify the name of the table, and then specify the lock mode in MODE. NOWAIT can specify whether to wait consistently when the lock is not obtained.

-- 111号连接
-- 基于互斥锁,锁住test表
-- 先开启事务
begin;
-- 基于默认的ACCESS EXCLUSIVE锁住test表
lock test in ACCESS SHARE mode;
-- 操作
select * from test;
-- 提交事务,锁释放
commit;

When connection No. 111 is opened based on a transaction and the current table is locked, if the default ACCESS EXCLUSIVE is used, other connections will be directly blocked when operating the table.

If No. 111 is based on ACCESS SHARE shared lock, other threads will not be locked when querying the current table.

row lock

PostgreSQL's row locks are basically the same as MySQL's. Row locks can be specified based on select for update.

There is a concept in MySQL. During for update, if the select query does not hit the index, the table may be locked.

PostgerSQL has a characteristic. Generally, when the select query does not hit the index, it may not necessarily lock the table, but will still implement row locks.

There are only two row locks in PostgreSQL, one for update and one for share.
After starting the transaction, directly execute select * from table where condition for update;

-- 先开启事务
begin;
-- 基于for update 锁住id为3的数据
select * from test where id = 3 for update;
update test set name = 'v1' where id = 3;
-- 提交事务,锁释放
commit;

Other connections will lock the current row and will be blocked.

Guess you like

Origin blog.csdn.net/a772304419/article/details/132929325