4.5、行锁在事务中的运用

4.5.1、环境准备

  1. postgres=# create table t_row_lock(id int,mc text,primary key (id));
  2. NOTICE: Replica identity is needed for shard table, please add to this table through "alter table" command.
  3. CREATE TABLE
  4. postgres=#
  5. postgres=# insert into t_row_lock values(1,'tbase'),(2,'pgxz');
  6. INSERT 0 2
  7. postgres=# select * from t_row_lock;
  8. id | mc
  9. ----+-------
  10. 1 | tbase
  11. 2 | pgxz
  12. (2 rows)

4.5.2、直接update获取

session1

  1. postgres=# begin;
  2. BEGIN
  3. postgres=# set lock_timeout to 1;
  4. SET
  5. postgres=# update t_row_lock set mc='postgres' where mc='pgxz';
  6. UPDATE 1
  7. postgres=#

session2

  1. postgres=# begin;
  2. BEGIN
  3. postgres=# set lock_timeout to 1;
  4. SET
  5. postgres=# update t_row_lock set mc='postgresql' where mc='tbase';
  6. UPDATE 1
  7. postgres=#

上面session1与session2分别持有mc=pgxz行和mc=tbase的行锁

4.5.3、select…for update获取

session1

  1. postgres=#
  2. BEGIN
  3. postgres=# set lock_timeout to 1;
  4. SET
  5. postgres=# select * from t_row_lock where mc='pgxz' for update;
  6. id | mc
  7. ----+------
  8. 2 | pgxz
  9. (1 row)

session2

  1. postgres=# begin;
  2. BEGIN
  3. postgres=# set lock_timeout to 1;
  4. SET
  5. postgres=# select * from t_row_lock where mc='tbase' for update;
  6. id | mc
  7. ----+------
  8. 2 | pgxz
  9. (1 row)

上面session1与session2分别持有mc=pgxz行和mc=tbase的行锁

4.5.4、排它锁检查

  1. postgres=# select pid,pg_blocking_pids(pid),wait_event_type,query from pg_stat_activity where wait_event_type = 'Lock' and pid!=pg_backend_pid()