How to detect query which holds the lock in Postgres?

前端 未结 5 2048
醉话见心
醉话见心 2020-12-07 08:51

I want to track mutual locks in postgres constantly.

I came across Locks Monitoring article and tried to run the following query:

SELECT bl.pid     A         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 09:41

    From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.

    CREATE VIEW lock_monitor AS(
    SELECT
      COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
      now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
      blockeda.query as blocked_query, blockedl.mode as blocked_mode,
      blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
      blockingl.mode as blocking_mode
    FROM pg_catalog.pg_locks blockedl
    JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
    JOIN pg_catalog.pg_locks blockingl ON(
      ( (blockingl.transactionid=blockedl.transactionid) OR
      (blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
      ) AND blockedl.pid != blockingl.pid)
    JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
      AND blockinga.datid = blockeda.datid
    WHERE NOT blockedl.granted
    AND blockinga.datname = current_database()
    );
    
    SELECT * from lock_monitor;
    

    As the query is long but useful, the article author has created a view for it to simplify it's usage.

提交回复
热议问题