PostgreSQL 锁判断
我们在使用 PostgreSQL 的时候经常会遇到有关锁的信息。那么如何判断是否有死锁或者锁等待呢?
WITH lock_pid AS (
SELECT DISTINCT pid
FROM pg_locks
WHERE pid <> pg_backend_pid() )
SELECT psa.*
FROM pg_stat_activity psa
INNER JOIN lock_pid lp ON psa.pid = lp.pid;
SELECT l.locktype,
l.database,
l.relation,
l.page,
l.tuple,
l.virtualxid,
l.transactionid,
l.classid,
l.objid,
l.objsubid,
l.pid AS blocking_pid,
l.mode AS lock_mode,
l.granted,
s1.datname AS database_name,
s1.usename AS blocking_user,
s1.query AS blocking_query
FROM pg_locks l
INNER JOIN pg_stat_activity s1 ON l.pid = s1.pid
INNER JOIN pg_locks l2 ON l.database = l2.database
AND l.relation = l2.relation
AND l.page = l2.page
AND l.tuple = l2.tuple
AND l.pid <> l2.pid
INNER JOIN pg_stat_activity s2 ON l2.pid = s2.pid;
l.locktype, --可锁的对象的类型
l.database, --锁目标存在的数据库的 OID
l.relation, --作为锁目标的关系的 OID
l.page, --作为锁目标的页在关系中的页号
l.tuple, --作为锁目标的元组在页中的元组号
l.virtualxid, --作为锁目标的事务虚拟 ID
l.transactionid, --作为锁目标的事务 ID
l.classid, --包含锁目标的系统目录的 OID
l.objid, --锁目标在它的系统目录中的OID
l.objsubid, --锁的目标列号
l.pid AS blocking_pid, --保持这个锁或者正在等待这个锁的服务器进程的 PID
l.mode AS lock_mode, --此进程已持有或者希望持有的锁模式
l.granted --锁已授予则为真否则为假