Skip to content

Instantly share code, notes, and snippets.

@zelark
Last active October 17, 2016 10:12
Show Gist options
  • Save zelark/2dd34a909dd3a236c182142389e309ba to your computer and use it in GitHub Desktop.
Save zelark/2dd34a909dd3a236c182142389e309ba to your computer and use it in GitHub Desktop.
locks in postgres #nc
select
lock.locktype,
lock.relation::regclass,
lock.mode,
lock.transactionid as tid,
lock.virtualtransaction as vtid,
lock.pid,
lock.granted
from pg_catalog.pg_locks lock
left join pg_catalog.pg_database db
on db.oid = lock.database
where (db.datname = current_database() or db.datname is null)
and not lock.pid = pg_backend_pid()
order by lock.pid;
select query, state, waiting, pid
from pg_catalog.pg_stat_activity
where datname = current_database()
and not (state = 'idle' or pid = pg_backend_pid());
select
coalesce(
blocking_lock.relation::regclass::text,
blocking_lock.locktype)
as locked_item,
now() - blocked.query_start as waiting_duration,
blocked.pid as blocked_pid,
blocked.query as blocked_query,
blocked_lock.mode as blocked_mode,
blocking.pid as blocking_pid,
blocking.query as blocking_query,
blocking_lock.mode as blocking_mode
from pg_catalog.pg_locks blocked_lock
join pg_stat_activity blocked
on blocked.pid = blocked_lock.pid
join pg_catalog.pg_locks blocking_lock
on blocking_lock.pid != blocked_lock.pid
and (blocking_lock.transactionid = blocked_lock.transactionid
or blocking_lock.relation = blocked_lock.relation
and blocking_lock.locktype = blocked_lock.locktype)
join pg_stat_activity blocking
on blocking.pid = blocking_lock.pid
and blocking.datid = blocked.datid
where not blocked_lock.granted
and blocking.datname = current_database();
create view lock_monitor as (
select
coalesce(
blocking_lock.relation::regclass::text,
blocking_lock.locktype)
as locked_item,
now() - blocked.query_start as waiting_duration,
blocked.pid as blocked_pid,
blocked.query as blocked_query,
blocked_lock.mode as blocked_mode,
blocking.pid as blocking_pid,
blocking.query as blocking_query,
blocking_lock.mode as blocking_mode
from pg_catalog.pg_locks blocked_lock
join pg_stat_activity blocked
on blocked.pid = blocked_lock.pid
join pg_catalog.pg_locks blocking_lock
on blocking_lock.pid != blocked_lock.pid
and (blocking_lock.transactionid = blocked_lock.transactionid
or blocking_lock.relation = blocked_lock.relation
and blocking_lock.locktype = blocked_lock.locktype)
join pg_stat_activity blocking
on blocking.pid = blocking_lock.pid
and blocking.datid = blocked.datid
where not blocked_lock.granted
and blocking.datname = current_database()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment