Postgresql 9.5 alter table在没有其他长时间运行的查询的情况下获得锁定超时

时间:2019-07-18 02:02:59

标签: postgresql locking postgresql-9.5 alter

我试图执行alter table mydb.r_group drop constraint test;,但是花了2分钟以上的时间才能获得排他锁。该表是繁忙表,有许多进程在查询该表。 (进程使用jdbc访问数据库)

我尝试使用以下查询语句找到运行时间较长的查询,但除某些处于idle状态的查询外,找不到其他查询。

SELECT
  pid,
  now() - pg_stat_activity.query_start AS duration,
  query,
  state
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes';

我还尝试使用以下查询语句来查找阻止更改表查询的查询,但该查询也被阻止,因此无法获取数据。

SELECT blocked_locks.pid     AS blocked_pid,
         blocked_activity.usename  AS blocked_user,
         blocking_locks.pid     AS blocking_pid,
         blocking_activity.usename AS blocking_user,
         blocked_activity.query    AS blocked_statement,
         blocking_activity.query   AS current_statement_in_blocking_process
   FROM  pg_catalog.pg_locks         blocked_locks
    JOIN pg_catalog.pg_stat_activity blocked_activity  ON blocked_activity.pid = blocked_locks.pid
    JOIN pg_catalog.pg_locks         blocking_locks 
        ON blocking_locks.locktype = blocked_locks.locktype
        AND blocking_locks.DATABASE IS NOT DISTINCT FROM blocked_locks.DATABASE
        AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
        AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
        AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
        AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
        AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
        AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
        AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
        AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
        AND blocking_locks.pid != blocked_locks.pid

    JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
   WHERE NOT blocked_locks.GRANTED;

有人知道我可以采取什么其他步骤来找到根本原因吗?

1 个答案:

答案 0 :(得分:1)

首先,尝试查找相关表的对象ID:

location="(1)Basking Ridge, NJ"
"".join(location.split("(1)"))

然后找到此表上的所有锁:

SELECT tableoid
FROM mydb.r_group
LIMIT 1;

然后,您将获得所有阻止SELECT pid, mode, granted FROM pg_locks WHERE database = current_database() AND locktype = 'relation' AND relation = <the number from above>; 的会话的列表。

ALTER TABLE中查找这些pid,以查看它们在做什么。特别有趣的是pg_stat_activity,即活动事务开始的时间。

如果您无法在xact_start中找到阻止进程,则它也可能是后台进程,最有可能是反环绕式自动清理工作程序。在外壳上使用pg_stat_activity查找阻塞进程ID。