pg_locks блокировки в PostgreSQL

Представление (VIEW) pg_locks содержит подробную информацию о блокировках в базе данных. Список текущих блокировок с указанием типа блокировки, таблицы и базы данных, на которой она выставлена и номера транзакции, которая выставила блокировку. Не стоит пугаться, если запрос выдает длинный список lock-ов -не все они являются критическими и блокирующими таблицу от всех возможных изменений и даже чтения. Для анализа списка блокировок обязательно стоит ознакомиться с Уровни блокировок таблиц и о том, когда и какими запросами они выставляются.

Один из распространенных случаев, когда список блокировок может пригодиться: выполняя команду ps aux | grep ^postgres вы видите, что в статусе одного из процессов postgres написано waiting - это как раз и означает, что данный процесс ждет, когда будет снята нужная ему блокировка. Какая именно можно выяснить запустив данный запрос:

select l.database, d.datname, l.relation, c.relname,
l.locktype, 
l.virtualxid, l.virtualtransaction, l.transactionid,
l.pid, l.mode, l.granted,
c.relacl
from pg_locks as l
LEFT JOIN pg_database AS d ON l.database= d.oid
LEFT JOIN pg_class AS c ON l.relation = c.oid
order by c.relname;

или так

select pg_class.relname, pg_locks.locktype, pg_locks.database, pg_locks.relation, 
pg_locks.virtualtransaction, pg_locks.pid, pg_locks.mode, pg_locks.granted 
from pg_class,pg_locks
where pg_class.relfilenode = pg_locks.relation 
order by pg_class.relname;

Запросы

NameTypeReferencesDescription
locktypetext type of the lockable object: relation, extend, page, tuple, transactionid, virtualxid, object, userlock, or advisoryТип блокировки объекта: relation (связь)
databaseoidpg_database.oidOID of the database in which the object exists, or zero if the object is a shared object, or NULL if the object is a transaction IDOID базы данных, в которой находится объект, или нуль, если объект является общим объектом, или NULL, если транзакция
relationoidpg_class.oidOID of the relation, or NULL if the object is not a relation or part of a relation
pageinteger Page number within the relation, or NULL if the object is not a tuple or relation page
tuplesmallint Tuple number within the page, or NULL if the object is not a tuple
virtualxidtext Virtual ID of a transaction, or NULL if the object is not a virtual transaction ID
transactionidxid ID of a transaction, or NULL if the object is not a transaction ID
classidoidpg_class.oidOID of the system catalog containing the object, or NULL if the object is not a general database object
objidoidany OID columnOID of the object within its system catalog, or NULL if the object is not a general database object
objsubidsmallint For a table column, this is the column number (the classid and objid refer to the table itself). For all other object types, this column is zero. NULL if the object is not a general database object
virtualtransactiontext Virtual ID of the transaction that is holding or awaiting this lock
pidinteger Process ID of the server process holding or awaiting this lock. NULL if the lock is held by a prepared transactionИдентификатор процесса в ОС соответствует выводу команды Использование ps для мониторинга процессов, например:
watch -n 1 'ps auxww | grep ^postgres'
modetext Name of the lock mode held or desired by this processТекстовое описание уровней блокировки таблиц.
grantedboolean True if lock is held, false if lock is awaitedЗначение t (true) значит установлена, блокировка, если значение поля f(false) ожидание освобождения таблицы от предшествующей блокировки(вероятны deadlock).
# select * from pg_locks;
  locktype  | database | relation | page | tuple | virtualxid | transactionid | classid | objid | objsubid | virtualtransaction | pid  |      mode       | granted 
------------+----------+----------+------+-------+------------+---------------+---------+-------+----------+--------------------+------+-----------------+---------
 relation   |    17592 |    18098 |      |       |            |               |         |       |          | 9/73689            | 9762 | AccessShareLock | t
 virtualxid |          |          |      |       | 9/73689    |               |         |       |          | 9/73689            | 9762 | ExclusiveLock   | t
 virtualxid |          |          |      |       | 8/46998    |               |         |       |          | 8/46998            | 9739 | ExclusiveLock   | t
 relation   |    17592 |    10969 |      |       |            |               |         |       |          | 8/46998            | 9739 | AccessShareLock | t
 relation   |    17592 |     2605 |      |       |            |               |         |       |          | 9/73689            | 9762 | AccessShareLock | t
PQ VPS сервера в 28+ странах.