PostgreSQL deadlock problem solving

I. Overview

Two, postgreSQL deadlock solution

1. Query the SQL being executed

See which SQLs are currently being executed in the database, or have just finished executing, from which you can analyze whether there is resource competition.

-- 查询正在进行的SQL操作
select * from pg_stat_activity;

In the above query results:

  • pidIt is the unique identification of ACTIVITY
  • stateis the active state
  • querysqlis the statement being executed
  • query_startis the time to start execution

2. Query table lock

(1) Query deadlock

select 
	* 
from 
	pg_stat_activity
where 
	datname = 'vcloud' 
AND wait_event_type = 'Lock'

(2) Query tables that may be locked

select * from pg_locks where relation= (select oid from pg_class where relname='可能锁表了的表');

3. Cancel function and interrupt function

-- 取消后台操作,回滚未提交事物 
select pg_cancel_backend(上面查到的pid)

-- 中断session,回滚未提交事物(pg_stat_activity表state字段中值为idle in transaction的,可以使用下面的中断函数解锁)
select pg_terminate_backend(上面查到的pid)

4. Query blocked sql

-- 查询阻塞的sql(死锁了,没有执行通过的sql)
select 
	pg_stat_activity.*,
	pg_locks.locktype,
	pg_locks.database,
	pg_locks.pid,
	pg_locks.mode,
	pg_locks.relation,
	pg_class.relname
from 
	pg_stat_activity,pg_locks,pg_class
where
	pg_stat_activity.pid=pg_locks.pid
and pg_locks.relation=pg_class.oid
and pg_stat_activity.waiting='t'
and upper(pg_class.relname)='AS_ASSETS_EXT'
SELECT
	w1.pid AS 等待进程,
	w1.MODE AS 等待锁模式,
	w2.usename AS 等待用户,
	w2.query AS 等待会话,
	b1.pid AS 锁的进程,
	b1.MODE 锁的锁模式,
	b2.usename AS 锁的用户,
	b2.query AS 锁的会话,
	b2.application_name 锁的应用,
	b2.client_addr 锁的 IP地址,
	b2.query_start 锁的语句执行时间 
FROM
	pg_locks w1
	JOIN pg_stat_activity w2 ON w1.pid = w2.pid
	JOIN pg_locks b1 ON w1.transactionid = b1.transactionid 
	AND w1.pid != b1.pid
	JOIN pg_stat_activity b2 ON b1.pid = b2.pid 
WHERE
	NOT w1.GRANTED;

3. Reference

Query ongoing SQL operations in the Postgresql database
https://blog.csdn.net/weixin_40991510/article/details/87255621

PostgreSQL modify table structure stuck
https://blog.csdn.net/qq_43458533/article/details/120438960

postgresql deadlock problem solving record
https://blog.csdn.net/weixin_33905756/article/details/92021743

Guess you like

Origin blog.csdn.net/qq_25775675/article/details/130808745