-- Текущие активные подключения
SELECT 
    pid,
    datname,
    usename,
    application_name,
    client_addr,
    state,
    query,
    query_start,
    state_change
FROM pg_stat_activity 
WHERE state = 'active'
ORDER BY query_start;

-- Количество подключений по клиентам
SELECT 
    client_addr,
    application_name,
    count(*) as connection_count,
    max(state) as state
FROM pg_stat_activity 
GROUP BY client_addr, application_name
ORDER BY connection_count DESC;

-- Долго выполняющиеся запросы
SELECT 
    pid,
    now() - query_start as duration,
    query,
    state
FROM pg_stat_activity 
WHERE state = 'active' 
AND now() - query_start > interval '30 seconds'
ORDER BY duration DESC;


-- Лимиты подключений
SHOW max_connections;
SHOW superuser_reserved_connections;

-- Таймауты
SHOW idle_in_transaction_session_timeout;
SHOW tcp_keepalives_idle;
SHOW tcp_keepalives_interval;


-- Проверим, что делает DBeaver
SELECT 
    pid,
    query,
    state,
    now() - query_start as running_for
FROM pg_stat_activity 
WHERE application_name LIKE '%DBeaver%'
AND state = 'active';


-- Включить pg_stat_statements на всех узлах
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Топ медленных запросов по кластеру
SELECT query, calls, total_time, mean_time, rows
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 10;

-- Проверить распределение нагрузки
SELECT datname, usename, count(*) as connections
FROM pg_stat_activity 
WHERE state = 'active'
GROUP BY datname, usename;


-- Блокирующие запросы
SELECT blocked_locks.pid AS blocked_pid,
       blocking_locks.pid AS blocking_pid,
       blocked_activity.query AS blocked_query,
       blocking_activity.query AS blocking_query
FROM pg_catalog.pg_locks blocked_locks
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 blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.granted;
