psotgres 锁
1、因为事物产生的锁
操作:
session A
postgres=# drop table test2;
DROP TABLE
postgres=# create table test2(id int, info text);
CREATE TABLE
postgres=# insert into test2 values (1,'test');
INSERT 0 1
postgres=# begin;
BEGIN
postgres=# update test2 set info='a' where id=1;
UPDATE 1
session B
postgres=# update test2 set info='b' ;
(此时会等待)
事前配置:
配置以下内容日志中将会记录锁等待的情况
log_lock_waits = on
deadlock_timeout = 1s
解决方法:
1:通过日志
2016-12-23 14:35:35 CST [5847-9] postgres@postgres LOG: process 5847 still waiting for ShareLock on transaction 1162758 after 1007.019 ms
2016-12-23 14:35:35 CST [5847-10] postgres@postgres DETAIL: Process holding the lock: 5840. Wait queue: 5847.
2016-12-23 14:35:35 CST [5847-11] postgres@postgres CONTEXT: while updating tuple (0,3) in relation "test2"
2016-12-23 14:35:35 CST [5847-12] postgres@postgres STATEMENT: update test2 set info='b' ;
2:通过命令
session C
postgres=# select b.* from pg_class a,pg_locks b where a.oid=b.relation and a.relname='test2';
relation | 12415 | 16438 | | | | | | | | 3/14 | 5847 | RowExclusiveLock | t | t
relation | 12415 | 16438 | | | | | | | | 2/18 | 5840 | RowExclusiveLock | t | t
tuple | 12415 | 16438 | 0 | 3 | | | | | | 3/14 | 5847 | ExclusiveLock | t | f
看到锁类型为tuple,数据库oid为12415 被锁定目标为:16438
kill 掉对应的的进程即可
备注:
通过oid查看数据库名
select oid,datname from pg_database where oid=12415;
12415 | postgres
通过oid查看表名
select oid,relname from pg_class where oid=16438;
16438 | test2
查看某个pid正在执行的命令
SELECT
procpid,
start,
now() - start AS lap,
current_query
FROM
(SELECT
backendid,
pg_stat_get_backend_pid(S.backendid) AS procpid,
pg_stat_get_backend_activity_start(S.backendid) AS start,
pg_stat_get_backend_activity(S.backendid) AS current_query
FROM
(SELECT pg_stat_get_backend_idset() AS backendid) AS S
) AS S
WHERE
current_query <> '<IDLE>' and procpid=5847
ORDER BY
lap DESC;
kill 掉对应的进程即可