G.4. pgpro_pwr — отчёты о нагрузке

Модуль pgpro_pwr предназначен для выявления наиболее ресурсоёмких операций в базе данных. (Корень pwr, произносится как «пауэр» (power), — это сокращение от Postgres Pro Workload Reporting, Отчётность по нагрузке Postgres Pro.) Данный модуль основывается на представлениях Сборщика статистики и расширении pgpro_stats или pg_stat_statements.

Примечание

Хотя pgpro_pwr может работать с расширением pg_stat_statements, по возможности рекомендуется использовать расширение pgpro_stats, так как оно выдаёт планы операторов, информацию о событиях ожидания и статистику распределения нагрузки для баз данных, ролей, клиентских узлов и приложений.

Ниже предполагается, что используется pgpro_stats, если иное не отмечено явно.

Если у вас нет возможности использовать pgpro_stats в нужной базе, но имеется расширение pg_stat_kcache, pgpro_pwr может обрабатывать выдаваемую pg_stat_kcache информацию об использовании командами ресурсов процессора и о нагрузке на уровне файловой системы (rusage).

pgpro_pwr получает сводную статистику ожидания от расширения pg_wait_sampling. Когда используется pg_wait_sampling, pgpro_pwr сбрасывает профиль выборки ожидания для каждой выборки.

Суть pgpro_pwr заключается в обработке накапливаемых статистических выборок. В каждой выборке содержится статистическая информация о наиболее активных объектах и запросах, добавленная с момента получения предыдущей выборки, или, говоря кратко, после предыдущей выборки. Впоследствии эта информация используется при построении отчётов.

pgpro_pwr предоставляет функции для получения выборок. Аккумулируемые регулярные выборки позволяют строить отчёты о нагрузке базы данных за прошедшее время.

pgpro_pwr позволяет создавать выборки явным образом во время массовой обработки данных, тестирования нагрузки и т. д.

При каждом получении выборки вызывается функция pgpro_stats_statements_reset() (она описана в pgpro_stats), чтобы статистика выполнения операторов не потерялась, когда количество операторов превысит pgpro_stats.max (см. Подраздел G.5.7.1). Кроме этого, в отчёте будет содержаться раздел, в котором можно узнать, не превышает ли количество операторов 90% от значения pgpro_stats.max.

Расширение pgpro_pwr, установленное на одном сервере Postgres Pro, может собирать статистику и с других серверов. Таким образом, на ведущем сервере можно собирать статистику нагрузки также с серверов горячего резерва. Чтобы это реализовать, необходимо указать имена всех серверов и строки подключения, а также обеспечить возможность подключения pgpro_pwr ко всем серверам.

G.4.1. Архитектура pgpro_pwr

Данное расширение состоит из следующих частей:

  • Репозиторий истории — хранилище собранных данных. В нём находится несколько таблиц расширения.

    Примечание

    Помимо прочего, в таблицах pgpro_pwr хранится текст запросов в открытом виде, который может содержать конфиденциальную информацию. Поэтому в целях безопасности ограничьте доступ к репозиторию должным образом.

  • Механизм управления выборками включает функции, позволяющие делать выборки и поддерживать актуальное состояние репозитория, удаляя устаревшие данные.

  • Механизм отчётов включает функции построения отчётов по данным, находящемся в репозитории истории.

  • Административные функции, предназначенные для создания серверов и выборочных линий, а также для управления ими.

G.4.2. Предварительные требования

Следующие требования приведены для варианта установки pgpro_pwr в целевом кластере, то есть в кластере, нагрузка которого будет анализироваться в первую очередь, хотя это расширение может собирать данные производительности и с других кластеров.

G.4.2.1. Для базы данных pgpro_pwr

Расширение pgpro_pwr зависит от языка PL/pgSQL и расширения dblink.

G.4.2.2. Для целевого сервера

Целевой сервер должен разрешать подключения ко всем базам данных с сервера, на котором работает pgpro_pwr. Вам надо будет задать строку подключения для этого сервера с указанием определённой базы данных. Эта база данных имеет особое значение, так как pgpro_pwr будет обращаться к установленному в ней расширению pgpro_stats или pg_stat_statements. Однако заметьте, что pgpro_pwr будет подключаться и ко всем остальным базам на этом сервере.

Для получения более полной статистики можно дополнительно:

  • Установить и настроить расширение pgpro_stats в вышеупомянутой базе данных, если вы хотите видеть в отчётах статистику по операторам. Полнота и точность собираемой статистики может зависеть от следующих параметров:

    • pgpro_stats.max

      При небольшом значении этого параметра некоторая статистика может теряться между выборками. Если объём попадающей в выборку статистики близок к значению pgpro_stats.max, вы увидите предупреждение об этом в отчёте.

    • pgpro_stats.track

      Оптимальным является значение по умолчанию, 'top' (заметьте, что значение 'all' повлияет на точность полей %Total (% всего) в разделах отчёта, посвящённым SQL-операторам).

  • Задать следующие параметры Сборщика статистики Postgres Pro:

            track_activities = on
            track_counts = on
            track_io_timing = on
            track_wal_io_timing = on   # Начиная с PostgreSQL 14
            track_functions = all/pl
          

G.4.3. Установка и подготовка

pgpro_pwr поставляется вместе с Postgres Pro Enterprise в виде отдельного пакета pgpro-pwr-ent-15 (подробные инструкции по установке приведены в Главе 17).

Примечание

Расширение pgpro_pwr создаёт множество объектов в базе данных, поэтому рекомендуется устанавливать его в отдельную схему.

Хотя pgpro_pwr вполне можно использовать с правами суперпользователя, наличие таких прав не является обязательным. Поэтому вы можете выбрать одну из следующих процедур установки в зависимости от ваших требований безопасности и конфигурации или разработать собственную:

G.4.3.1. Упрощённая установка

Эта процедура предназначена для случаев, когда pgpro_pwr устанавливается непосредственно на целевой сервер и будет отслеживать его нагрузку от имени суперпользователя.

Создайте схему для установки pgpro_pwr, а затем создайте расширение:

CREATE SCHEMA profile;
CREATE EXTENSION pgpro_pwr SCHEMA profile;

G.4.3.2. Развёрнутая установка

Эта процедура охватывает случаи, когда планируется использовать pgpro_pwr для отслеживания нагрузки на одном или нескольких серверах с соблюдением принципа наименьших привилегий.

G.4.3.2.1. В базе данных целевого сервера

Создайте на целевом сервере пользователя для pgpro_pwr:

CREATE USER pwr_collector PASSWORD 'collector_pwd';

Убедитесь в том, что пользователь имеет возможность подключаться к любой базе данных кластера (по умолчанию это так) и что pg_hba.conf разрешает такие подключения с сервера, где размещён pgpro_pwr. Также включите этого пользователя в роль pwr_collector и дайте ему право EXECUTE для следующих функций:

GRANT pg_read_all_stats TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgpro_stats_statements_reset TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgpro_stats_totals_reset(text,bigint) TO pwr_collector;

Также следует проверить наличие права SELECT для представления pgpro_stats_archiver:

GRANT SELECT ON pgpro_stats_archiver TO pwr_collector;
G.4.3.2.2. В базе данных pgpro_pwr

Создайте непривилегированного пользователя:

CREATE USER pwr_user;

Этот пользователь будет владельцем схемы расширения, и от его имени будут собираться статистические выборки.

Создайте схему для установки pgpro_pwr:

CREATE SCHEMA profile AUTHORIZATION pwr_user;

Дайте пользователю право USAGE для схемы, где располагается расширение dblink:

GRANT USAGE ON SCHEMA public TO pwr_user;

Создайте расширение от имени pwr_user:

\c - pwr_user
CREATE EXTENSION pgpro_pwr SCHEMA profile;

Определите параметры подключения к целевому серверу для pgpro_pwr. Например:

SELECT profile.create_server('target_server_name','host=192.168.1.100 dbname=postgres port=5432');

Указанная строка подключения будет использоваться в вызове dblink_connect() при выполнении функции take_sample().

Примечание

Строки подключения хранятся в таблице pgpro_pwr в открытом виде, поэтому следует ограничивать доступ к таблицам расширения pgpro_pwr.

G.4.3.3. Настройка ролей pgpro_pwr

В работе pgpro_pwr можно выделить до трёх ролей:

  • Роль владелец pgpro_pwr является владельцем расширения pgpro_pwr.

  • Роль сбора статистики используется pgpro_pwr для подключения к базам данных и сбора статистики.

  • Роль создания отчётов используется для создания отчётов.

Если все действия с pgpro_pwr выполняются от имени суперпользователя postgres, можно пропустить большую часть настройки, описанной ниже.

G.4.3.3.1. Владелец pgpro_pwr

Эту роль можно использовать для выполнения всех действий, связанных с pgpro_pwr. Она будет иметь доступ к строкам подключения к серверу, которые могут содержать пароли. Эту роль следует использовать для вызова функции take_sample(). Пользователю с такой ролью необходимо расширение dblink.

Рассмотрим пример, в котором каждое расширение установлено в отдельной схеме:

\c postgres postgres
CREATE SCHEMA dblink;
CREATE EXTENSION dblink SCHEMA dblink;
CREATE USER pwr_usr with password 'pwr_pwd';
GRANT USAGE ON SCHEMA dblink TO pwr_usr;
CREATE SCHEMA profile AUTHORIZATION pwr_usr;
\c postgres pwr_usr
CREATE EXTENSION pgpro_pwr SCHEMA profile;
G.4.3.3.2. Роль сбора статистики

Эта роль должна использоваться расширением pgpro_pwr для подключения к базам данных и сбора статистики. Непривилегированные пользователи не могут открывать соединения, используя dblink, без пароля, поэтому необходимо указать пароль в строке подключения для каждого сервера. Эта роль должна иметь доступ ко всем расширениям, собирающим статистику, а также иметь возможность выполнять сброс статистики для таких расширений.

Рассмотрим пример. Если для сбора статистики используется расширение pgpro_stats, настройте роль сбора статистики следующим образом:

\c postgres postgres
CREATE SCHEMA pgps;
CREATE EXTENSION pgpro_stats SCHEMA pgps;
CREATE USER pwr_collector with password 'collector_pwd';
GRANT pg_read_all_stats TO pwr_collector;
GRANT USAGE ON SCHEMA pgps TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgps.pgpro_stats_statements_reset TO pwr_collector;

Если для сбора статистики используется расширение pg_stat_statements, настройте её, как указано ниже:

\c postgres postgres
CREATE SCHEMA pgss;
CREATE SCHEMA pgsk;
CREATE SCHEMA pgws;
CREATE EXTENSION pg_stat_statements SCHEMA pgss;
CREATE EXTENSION pg_stat_kcache SCHEMA pgsk;
CREATE EXTENSION pg_wait_sampling SCHEMA pgws;
CREATE USER pwr_collector with password 'collector_pwd';
GRANT pg_read_all_stats TO pwr_collector;
GRANT USAGE ON SCHEMA pgss TO pwr_collector;
GRANT USAGE ON SCHEMA pgsk TO pwr_collector;
GRANT USAGE ON SCHEMA pgws TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgss.pg_stat_statements_reset TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgsk.pg_stat_kcache_reset TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgws.pg_wait_sampling_reset_profile TO pwr_collector;

Теперь следует задать строку подключения, указывающую на базу данных с установленными расширениями статистики:

 \c postgres pwr_usr
 SELECT profile.set_server_connstr('local','dbname=postgres port=5432 host=localhost user=pwr_collector password=collector_pwd');

В файле pg_hba.conf следует указать, что для пользователя pwr_collector требуется аутентификация по паролю.

Очевидно, что роль сбора статистики должна быть правильно настроена на всех серверах, с которых расширение pgpro_pwr собирает статистику.

Теперь можно вызывать take_sample(), используя роль pwr_usr:

\c postgres pwr_usr
SELECT * FROM take_sample();

Затем необходимо настроить планировщик задач (в нашем примере это команда crontab пользователя postgres):

*/30 * * * *   psql -U pwr_usr -d postgres -c 'SELECT profile.take_sample()' > /dev/null 2>&1

Обратите внимание, что для хранения паролей можно использовать файл паролей Postgres Pro.

G.4.3.3.3. Роль создания отчётов

Любой пользователь может собирать отчёты pgpro_pwr. Минимальные права, необходимые для создания отчётов pgpro_pwr, предоставляются роли public. Однако полный отчёт с текстами запросов доступен только члену роли pg_read_all_stats. В любом случае роль создания отчётов не имеет доступа к строкам подключения к серверу, поэтому она не может получить пароли серверов.

G.4.3.4. Настройка параметров расширения

Вы можете определить в postgresql.conf следующие параметры pgpro_pwr:

pgpro_pwr.max (integer)

Количество выбираемых первых объектов (операторов, отношений и т. д.), которое будет выдаваться в каждой отсортированной по некоторому критерию таблице отчёта. Этот параметр влияет на размер выборки: чем больше объектов необходимо отобразить в отчёте, тем больше должна быть выборка. Максимальное значение — 100. Любое значение больше максимально допустимого будет уменьшено до 100.

Значение по умолчанию — 20.

pgpro_pwr.max_sample_age (integer)

Срок хранения выборки (в днях). Выборки старее pgpro_pwr.max_sample_age дней автоматически удаляются при очередном вызове take_sample().

Значение по умолчанию — 7.

pgpro_pwr.max_query_length (integer)

Максимальная длина выводимого запроса в отчётах. Все запросы в отчётах будут сокращены до количества символов, указанного в pgpro_pwr.max_query_length.

Значение по умолчанию — 20 000 символов.

pgpro_pwr.track_sample_timings (boolean)

Включает сбор подробной информации о времени выполнения внутренних процедур pgpro_pwr. Этот параметр полезен для диагностики в случае медленного выполнения функций получения выборок. Собранные показатели можно будет просмотреть в представлении v_sample_timings.

Значение по умолчанию — off (выкл.).

pgpro_pwr.statements_reset (boolean)

Управляет сбросом статистики pgpro_stats/pg_stat_statements во время получения выборки. Позволяет не сбрасывать статистику во время получения выборки благодаря использованию новых методов. При отключении этого параметра pgpro_pwr будет отслеживать вытеснения операторов, используя значения поля calls. Однако этот метод не полностью предотвращает потерю статистики. Расширения pg_stat_statements версии 1.11 и pgpro_stats версии 1.8 имеют возможности для учёта точного времени наблюдения за выражением, которые могут уменьшить потенциальную потерю данных. Когда этот параметр отключён, его можно временно включить в сеансе, чтобы периодически выполнять сброс pgpro_stats/pg_stat_statements.

Значение по умолчанию — on (вкл.).

pgpro_pwr.relsize_collect_mode (text)

Задаёт режим сбора сведений о размерах отношений. Возможные значения:

  • off — сбор сведений о размерах отношений основан на каталоге pg_class. Хотя полученные таким образом данные являются приблизительными, их сбор почти не потребляет ресурсов.

  • on — для каждой выборки собираются точные размеры отношений с помощью функции pg_relation_size(). Такой сбор требует блокировки таблицы и довольно ресурсоёмок.

  • schedule — точные размеры отношений собираются в окне анализа размеров, определённом для каждого сервера.

Значение по умолчанию — off (выкл.).

G.4.4. Управление серверами

После установки pgpro_pwr создаёт по умолчанию активное определение сервера с именем local, соответствующее текущему кластеру. Активные определения серверов обрабатываются без явного указания при получении выборок (см. описание take_sample()). Неактивный сервер считается исключённым.

Строка локального сервера по умолчанию содержит только параметры dbname и port. Значения этих параметров берутся из свойств подключения, которое было установлено в момент создания расширения. Заданную ранее строку подключения сервера можно изменить, воспользовавшись функцией set_server_connstr().

G.4.4.1. Функции управления серверами

Для управления серверами предназначены следующие функции pgpro_pwr:

create_server(server name, connstr text, enabled boolean DEFAULT TRUE, max_sample_age integer DEFAULT NULL description text DEFAULT NULL)

Создаёт определение сервера.

Аргументы:

  • server — имя сервера, которое должно быть уникальным.

  • connstr — строка подключения. Должна содержать все необходимые параметры для подключения со стороны сервера с pgpro_pwr к базе данных целевого сервера.

  • enabled — установите этот параметр, чтобы включить сервер в число серверов, обрабатываемых функцией take_sample() без аргументов.

  • max_sample_age — срок хранения выборки (в днях). Переопределяет глобальное значение pgpro_pwr.max_sample_age для данного сервера.

  • description — описание сервера, которое будет включаться в отчёты.

Например, определение сервера можно создать так:

SELECT profile.create_server('omega','host=192.168.1.100 dbname=postgres port=5432');
drop_server(server name)

Удаляет сервер и все полученные с него выборки.

set_server_description(server name description text)

Задаёт описание для сервера.

set_server_subsampling(server name, subsample_enabled boolean, min_query_duration interval, min_xact_duration interval, min_xact_age integer, min_idle_xact_dur interval hour to second)

Определяет параметры получения промежуточных выборок для сервера.

Аргументы:

  • server — имя сервера.

  • subsample_enabled — определяет, включено ли получение промежуточных выборок для сервера, то есть должна ли функция take_subsample() фактически создавать промежуточные выборки.

  • min_query_duration — предел длительности запроса.

  • min_xact_duration — предел длительности транзакции.

  • time_range — предел возраста транзакций.

  • min_idle_xact_dur_age — предел простоя транзакции.

enable_server(server name)

Включает сервер в число серверов, обрабатываемых функцией take_sample() без аргументов.

disable_server(server name)

Исключает сервер из числа серверов, обрабатываемых функцией take_sample() без аргументов.

rename_server(server name, новое_имя name)

Переименовывает сервер.

set_server_max_sample_age(server name, max_sample_age integer)

Задаёт срок хранения выборки для сервера (в днях). Чтобы сбросить это значение, передайте NULL в параметре max_sample_age.

set_server_db_exclude(server name, exclude_db name[])

Исключает указанные базы данных на сервере из числа обрабатываемых. Это полезно, когда pgpro_pwr не может подключиться к некоторым базам в кластере (например, это возможно в кластерах Amazon RDS).

set_server_connstr(server name, server_connstr text)

Задаёт строку подключения для сервера.

set_server_setting(server name, setting text, value jsonb)

Выполняет тонкую настройку сбора статистики сервера. Настройки collect* управляют тем, какая статистика будет собираться, и для них параметр value принимает логические значения, по умолчанию равные true. Доступные настройки:

  • collect_pg_stat_statement — собирать статистику выполнения операторов с помощью расширений pg_stat_statements и pg_stat_kcache.

  • collect_pg_wait_sampling — собирать статистку событий ожидания с помощью расширения pg_wait_sampling.

  • collect_objects — собирать статистику по всем объектам схемы, то есть по таблицам, индексам и функциям, из представлений pg_stat_*.

  • collect_relations — собирать статистику по таблицам и индексам из представлений pg_stat_*.

  • collect_functions — собирать статистику по пользовательским функциям из представления pg_stat_user_functions.

  • collect_vacuum_stats — собирать расширенную статистку очистки баз данных.

show_server_settings(server name)

Возвращает параметры сбора статистки для заданного сервера.

show_servers()

Выдаёт список настроенных серверов.

G.4.5. Управление выборками

Выборка содержит статистическую информацию о нагрузке базы данных, полученную после предыдущей выборки

G.4.5.1. Функции обработки выборок

Для работы с выборками предназначены следующие функции pgpro_pwr:

take_sample()
take_sample(server name [, skip_sizes boolean])

Получает выборки.

Без параметров эта форма функции получает выборки со всех включённых серверов, обращаясь к ним последовательно, и выдаёт в результате таблицу со следующими столбцами:

  • server — имя сервера.

  • result — результат получения выборки. Может быть строкой OK, если выборка получена успешно, либо содержать текст с трассировкой ошибки в случае неудачи.

  • elapsed — время, потраченное на получение выборки.

С параметром эта функция получает выборку с указанного сервера, даже если этот сервер исключён. Она полезна, когда вам нужно получать выборки с разных серверов с разной частотой. В случае успеха она выдаёт 0.

Аргументы:

  • server — имя сервера.

  • skip_sizes — если этот параметр опущен или равен NULL, применяется политика анализа размеров; если он равен false, анализ размеров производится, а если true — пропускается.

take_sample_subset([sets_cnt integer, current_set integer])

Получает выборку с каждого сервера в подмножестве. Используйте эту функцию, чтобы получать выборки параллельным образом при большом количестве включённых серверов. Хотя PL/pgSQL не поддерживает параллельное выполнение функции, вы можете запустить эту функцию в нескольких сеансах. Она возвращает тот же тип, что и take_sample(). Если оба параметра опущены, функция действует аналогично take_sample(), то есть перебирает все включённые серверы по одному.

Аргументы:

  • sets_cnt — количество подмножеств, на которое будет разделено множество всех включённых серверов.

  • current_set — номер подмножества, в котором будут собираться выборки. Принимает значение от 0 до sets_cnt - 1. Для выбранного подмножества выборки собираются как обычно, с последовательным переходом от сервера к серверу.

Если обнаружится, что после предыдущей выборки произошёл сброс статистики, pgpro_pwr обработает соответствующие абсолютные значения как разницу; однако точность пострадает в любом случае.

show_samples([server name,] [days integer])

Выдаёт таблицу с информацией об имеющихся на сервере выборках статистики (если параметр server опущен, подразумевается local) за последние days дней (если этот параметр опущен, то за всё время). Эта таблица содержит следующие столбцы:

  • sample — идентификатор выборки.

  • sample_time — время, когда была получена выборка.

  • dbstats_resetNULL или время сброса статистики в представлении pg_stat_database, если она была сброшена после предыдущей выборки.

  • clustats_resetNULL или время сброса статистики в представлении pg_stat_bgwriter, если она была сброшена после предыдущей выборки.

  • archstats_resetNULL или время сброса статистики в представлении pg_stat_archiver, если она была сброшена после предыдущей выборки.

Функции получения выборок также поддерживают заданное политикой хранения желаемое состояние репозитория, удаляя устаревшие выборки и выборочные линии.

G.4.5.2. Получение выборок

Чтобы получить выборки со всех включённых серверов, вызовите функцию take_sample(). Обычно достаточно получать одну-две выборки в час. Для выполнения этой функции по расписанию можно воспользоваться планировщиком cron или подобным. Например, так выглядит расписание cron для получения выборок каждые 30 минут:

*/30 * * * *   psql -c 'SELECT profile.take_sample()' &> /dev/null

Однако результаты такого вызова не проверяются на ошибки. В производственной среде для целей мониторинга имеет смысл проверять строку результата, которая будет содержать OK для всех серверов, с которых выборки были получены успешно, либо текст ошибки, если получить выборку не удалось:

SELECT * FROM take_sample();
  server   |                                   result                                    |   elapsed
-----------+-----------------------------------------------------------------------------+-------------
 ok_node   | OK                                                                          | 00:00:00.48
 fail_node | could not establish connection                                             +| 00:00:00
           | SQL statement "SELECT dblink_connect('server_connection',server_connstr)"  +|
           | PL/pgSQL function take_sample(integer) line 69 at PERFORM                  +|
           | PL/pgSQL function take_sample_subset(integer,integer) line 27 at assignment+|
           | SQL function "take_sample" statement 1                                     +|
           | FATAL:  database "postgresno" does not exist                                |
(2 rows)

G.4.5.3. Политика хранения выборок

Политики хранения можно определить на следующих уровнях:

  1. Глобальный

    Значение параметра pgpro_pwr.max_sample_age в файле postgresql.conf определяет общее значение параметра хранения, действующее в случае, когда не определены никакие другие параметры.

  2. Сервер

    Параметр max_sample_age, указанный при создании сервера или при вызове функции set_server_max_sample_age(сервер), определяет срок хранения на уровне сервера. Значение этого параметра переопределяет значение pgpro_pwr.max_sample_age для конкретного сервера.

  3. Выборочная линия

    Созданная выборочная линия переопределяет все другие заданные сроки хранения для включённых в неё выборок.

G.4.6. Управление анализом размеров отношений

Сбор сведений о размерах всех отношений в базе данных с использованием функций Postgres Pro может занять продолжительное время. Кроме того, эти функции требуют установления блокировки AccessExclusiveLock для анализируемых отношений. Однако во многих случаях может быть достаточно собирать информацию о размерах один раз в сутки. Реализовать это можно, определив в pgpro_pwr политики анализа размеров для серверов, позволяющие пропускать сбор сведений о размерах в процессе получения выборок. Такая политика устанавливает:

  • Окно в течение суток, когда разрешается сбор сведений о размерах отношений.

  • Минимальный промежуток между двумя выборками со сведениями о размерах.

Когда определена политика анализа размеров, функции получения выборок собирают сведения о размерах только в заданном окне и только если после предыдущей выборки с размерами прошло не меньше заданного промежутка. Такую политику позволяют определить следующие функции:

set_server_size_sampling(server name, window_start time with time zone DEFAULT NULL, window_duration interval hour to second DEFAULT NULL, sample_interval interval day to minute DEFAULT NULL, collect_mode text DEFAULT NULL)

Определяет политику сбора сведений о размере для сервера.

Аргументы:

  • server — имя сервера.

  • window_start — время начала периода сбора.

  • window_duration — длительность периода сбора.

  • sample_interval — минимальный промежуток времени между сборами сведений о размере.

  • collect_mode — при значении off, используемом по умолчанию для новых инсталляций, размеры отношений собираются из каталога pg_class, при значении on, размеры отношений собираются с помощью функции pg_relation_size(), при значении schedule, pgpro_pwr собирает размеры отношений в заданном окне. Этот параметр переопределяет значение параметра расширения relsize_collect_mode. При обновлении с предыдущих версий для этого параметра устанавливается значение on или schedule, что не меняет поведения, имевшего место до обновления.

Примечание

Если вы построите отчёт между двумя выборками, хотя бы в одной из которых отсутствуют сведения о размерах отношений, в нём будут разделы с информацией об увеличивающихся в размере объектах, полученной из pg_class.relpages. Однако вы можете расширить интервал отчёта до ближайших выборок, содержащих сведения о размерах, передав функциям построения отчётов параметр with_growth; это позволяет получать более точные данные об увеличении размера.

Размеры отношений необходимо знать, чтобы вычислить объём последовательно сканированных данных в таблицах и непосредственную нагрузку автоочистки при обработке индексов.

Пример:

SELECT set_server_size_sampling('local','23:00+03',interval '2 hour',interval '8 hour', 'schedule');

Функция show_servers_size_sampling выводит политики анализа размеров для всех серверов:

postgres=# SELECT * FROM show_servers_size_sampling();
 server_name | window_start | window_end  | window_duration | sample_interval | limited_collection
-------------+--------------+-------------+-----------------+-----------------+--------------------
 local       | 23:00:00+03  | 01:00:00+03 | 02:00:00        | 08:00:00        | t

G.4.7. Управление промежуточными выборками

Некоторые доступные в Postgres Pro данные, связанные с производительностью, не являются накопительными. Например, наиболее часто используемые данные о состояниях сеансов доступны через представление pg_stat_activity и могут быть получены только с помощью частых выборок. Однако функция take_sample() создаёт большую нагрузку и может занять много времени. Поэтому она не подходит для сбора данных о состоянии сеансов.

В механизме промежуточных выборок реализована новая быстрая функция take_subsample(). Она может использоваться для сбора относительно быстро меняющихся данных. Каждая промежуточная выборка привязана к следующей обычной выборке и удаляется вместе с ней согласно заданной политике хранения.

Механизм промежуточных выборок можно использовать для захвата наиболее интересных состояний сеансов:

  • Длительные запросы

  • Длительные транзакции

  • Старые транзакции, то есть те, снимок в которых находится позади множества других транзакций

  • Транзакции, долгое время находящиеся в состоянии простоя (idle)

G.4.7.1. Функции получения промежуточных выборок

Следующие функции pgpro_pwr относятся к работе с промежуточными выборками:

take_subsample()
take_subsample(server name)

Без параметров эта функция получает промежуточные выборки со всех включённых серверов с включённым механизмом их получения (за подробностями обратитесь к set_server_subsampling). Промежуточные выборки для серверов получаются последовательно, по одному. Функция выдаёт в результате таблицу со следующими столбцами:

  • server — имя сервера.

  • result — результат получения промежуточной выборки. Может быть строкой OK, если промежуточная выборка получена успешно, либо содержать текст ошибки в случае неудачи.

  • elapsed — время, потраченное на получение промежуточной выборки.

Этот табличный формат вывода данных позволяет легко управлять созданием промежуточных выборок с помощью SQL-запроса.

С параметром эта функция получает промежуточную выборку с указанного сервера. Она полезна, когда нужно получать промежуточные выборки с разных серверов с разной частотой или получить явную выборку для конкретного сервера.

Аргументы:

  • server — имя сервера.

Примечание

Попытка получить промежуточную выборку во время получения обычной выборки завершится ошибкой.

take_subsample_subset([sets_cnt integer], [current_set integer])

Получает промежуточную выборку с каждого сервера в подмножестве с включённым механизмом их получения. Хотя даже последовательное получение промежуточных выборок должно выполняться достаточно быстро, их можно получать параллельно, аналогично обычным выборкам. Эта функция возвращает тот же тип, что и take_subsample(). Если оба параметра опущены, функция действует аналогично take_subsample().

Аргументы:

  • sets_cnt — количество подмножеств серверов.

  • current_set — номер подмножества, в котором будут собираться промежуточные выборки. Принимает значение от 0 до sets_cnt - 1. Для выбранного подмножества промежуточные выборки собираются как обычно, с последовательным переходом от сервера к серверу.

G.4.7.2. Конфигурирование механизма получения промежуточных выборок

На поведение промежуточных выборок влияют следующие параметры:

  • pgpro_pwr.subsample_enabled — определяет, должна ли функция take_subsample() фактически создавать промежуточную выборку.

  • pgpro_pwr.min_query_duration — предел, по достижении которого запрос считается длительным.

  • pgpro_pwr.min_xact_duration — предел, по достижении которого транзакция считается длительной.

  • pgpro_pwr.min_xact_age — предел возраста транзакции.

  • pgpro_pwr.min_idle_xact_dur_age — предел простоя транзакции.

Это поведение можно задать на уровне сервера с помощью функции set_server_subsampling.

Последнее наблюдаемое состояние сеанса сохраняется в репозитории, когда происходит одно из следующих событий, связанных с пределами:

  • Во время выполнения запроса разница между now() и query_start превышает предел pgpro_pwr.min_query_duration.

  • Во время выполнения транзакции разница между now() и xact_start превышает предел pgpro_pwr.min_xact_duration.

  • Во время выполнения транзакции age(backend_xmin) превышает предел pgpro_pwr.min_xact_age.

  • Во время выполнения транзакции в состоянии idle in transaction или idle in transaction (aborted) разница между now() и state_change превышает предел pgpro_pwr.min_idle_xact_duration.

За более подробным описанием упомянутых полей обратитесь к Главе 27. Каждая промежуточная выборка может содержать не более pgpro_pwr.max записей для каждого типа пределов.

G.4.7.3. Планирование получения промежуточных выборок

Скорость получения промежуточных выборок позволяет получать их довольно часто. Однако обычно требуется не более 2-4 промежуточных выборок в минуту. Очевидно, что частота промежуточных выборок зависит от самого маленького из значений параметров пределов.

Cron допускает только один вызов в минуту, поэтому нужно предпринять дополнительные действия, чтобы получать промежуточные выборки чаще. Например, можно использовать команду psql \watch:

echo "select take_subsample(); \watch 15" | psql &> /dev/null

Вызов psql можно обернуть в systemd следующим образом:

Description=pgpro_pwr subsampling unit
[Unit]

[Service]
Type=simple
ExecStart=/bin/sh -c 'echo "select take_subsample(); \\watch 15" | /path/to/psql -qo /dev/null'
User=postgres
Group=postgres

[Install]
WantedBy=multi-user.target

G.4.8. Управление выборочными линиями

Выборочной линией называется именованная последовательность выборок, для которых определяется отдельный срок хранения. Выборочная линия также может задавать интервал для функций построения отчётов. Если срок хранения для выборочной линии не определён, относящиеся к ней выборки не будут удаляться. Выборочные линии позволяют сохранить информацию о нагрузке базы данных за определённый интервал времени.

G.4.8.1. Функции управления выборочными линиями

Для управления выборочными линиями предназначены следующие функции pgpro_pwr:

create_baseline([server name,] baseline varchar(25), start_id integer, end_id integer [, days integer])
create_baseline([server name,] baseline varchar(25), time_range tstzrange [, days integer])

Создаёт выборочную линию.

Аргументы:

  • server — имя сервера. Если оно опущено, подразумевается local.

  • baseline — имя выборочной линии, которое должно быть уникальным на сервере.

  • start_id — идентификатор первой выборки в линии.

  • end_id — идентификатор последней выборки в линии.

  • time_range — период времени для выборочной линии. Выборочная линия будет включать все выборки, относящиеся к минимальному интервалу, который покрывает заданный отрезок time_range.

  • days — срок хранения выборочной линии, определяемый целым количеством дней с момента now(). Чтобы срок хранения не ограничивался, опустите этот параметр или задайте значение NULL.

drop_baseline([server name,] baseline varchar(25))

Удаляет выборочную линию. Аргументы этой функции действуют аналогично одноимённым аргументам create_baseline. Удаление выборочной линии не влечёт за собой непосредственное удаление относящихся к ней выборок. На них просто перестают распространяться заданные для этой линии параметры хранения.

keep_baseline([server name,] baseline varchar(25) [, days integer])

Изменяет срок хранения для выборочной линии. Аргументы этой функции действуют аналогично одноимённым аргументам create_baseline. Чтобы изменить срок хранения для всех существующих выборочных линий, опустите параметр baseline или передайте в нём NULL.

show_baselines([server name])

Выводит существующие выборочные линии. Вызовите show_baselines, чтобы получить информацию о выборочных линиях, включающую их имена, интервалы и периоды хранения. Если параметр server опущен, подразумевается сервер local.

G.4.9. Экспорт и импорт данных

Собранные выборки можно экспортировать из одного экземпляра расширения pgpro_pwr и загрузить в другой. Это позволяет перемещать накопленную информацию о серверах или передать её специалистам поддержки для анализа.

G.4.9.1. Экспорт данных

Функция export_data экспортирует данные в обычную таблицу. Выгрузить их затем из базы данных можно любым доступным способом. Например, можно воспользоваться метакомандой psql \copy и получить данные в файле csv:

postgres=# \copy (select * from export_data()) to 'export.csv'

G.4.9.2. Импорт данных

Так как данные могут импортироваться только из локальной таблицы, сначала загрузите ранее экспортированные данные. Для этого вновь воспользуйтесь метакомандой \copy:

postgres=# CREATE TABLE import (section_id bigint, row_data json);
CREATE TABLE
postgres=# \copy import from 'export.csv'
COPY 6437

Теперь вы можете импортировать данные, передав таблицу import функции import_data:

postgres=# SELECT * FROM import_data('import');

По завершении импорта таблицу import можно удалить.

Примечание

Если данные сервера импортируются впервые, локально определённые серверы pgpro_pwr с совпадающими именами вызовут конфликт во время импорта. Чтобы его избежать, можно временно переименовать такие серверы или указать префикс имён серверов для операций импорта. Однако во время последующего импорта данных для ранее импортированных серверов эти данные будут сопоставляться с серверами по системным идентификаторам, поэтому эти серверы можно переименовать как угодно. Также имейте в виду, что pgpro_pwr переводит импортируемые серверы в отключённое состояние, чтобы функция take_sample() не обрабатывала их.

G.4.9.3. Функции экспорта и импорта

Для экспорта и импорта данных предназначены следующие функции:

export_data([server name, [min_sample_id integer,] [max_sample_id integer,]] [, obfuscate_queries boolean] [, hide_connstr boolean])

Экспортирует собранные данные.

Аргументы:

  • server — имя сервера. Если оно опущено, данные экспортируется со всех настроенных серверов.

  • min_sample_id, max_sample_id — идентификаторы выборок, ограничивающих диапазон экспортируемых выборок (включающий указанные границы). Если min_sample_id опущен или равен NULL, экспортируются все выборки до выборки max_sample_id; если же max_sample_id опущен или равен NULL, экспортируются все выборки, начиная с выборки min_sample_id.

  • obfuscate_queries — экспортирует тексты запросов в виде хеша MD5 и исключает из экспорта строки подключения к серверу. Передавайте этот аргумент, только когда нужно скрыть тексты запросов.

  • hide_connstr — исключает из экспорта строки подключения к серверу.

import_data(data regclass [, server_name_prefix text])

Импортирует ранее экспортированные данные. Возвращает число строк, фактически загруженных в таблицы pgpro_pwr.

Аргументы:

  • data — имя таблицы, содержащей данные импорта.

  • server_name_prefix задаёт префикс имён серверов для операции импорта. Его можно использовать, чтобы избежать конфликтов имён.

G.4.10. Функции построения отчётов

Отчёты pgpro_pwr формируются в формате HTML функциями построения. В pgpro_pwr имеются следующие типы отчётов:

  • Обычные отчёты предоставляют статистику по нагрузке для заданного интервала.

  • Разностные отчёты предоставляют статистику по одинаковым объектам в двух интервалах. Соответствующие значения выводятся рядом, что позволяет легко сравнивать профили нагрузки.

Функции построения отчётов позволяют определить интервалы разными способами, принимая идентификаторы выборок, выборочные линии или диапазоны времени. В последнем случае выбирается минимальный интервал, охватывающий указанный диапазон.

G.4.10.1. Обычные отчёты

Для построения обычных отчётов воспользуйтесь следующими функциями:

get_report([server name,] start_id integer, end_id integer [, description text [, with_growth boolean [, db_exclude name[]]]])
get_report([server name,] time_range tstzrange [, description text [, with_growth boolean [, db_exclude name[]]]])
get_report([server name,] baseline varchar(25) [, description text [, with_growth boolean [, db_exclude name[]]]])

Строит обычный отчёт согласно заданным аргументам.

Аргументы:

  • server — имя сервера. Если оно опущено, подразумевается local.

  • start_id — идентификатор выборки, с которой начинается интервал.

  • end_id — идентификатор выборки, которой заканчивается интервал.

  • baseline — имя выборочной линии.

  • time_range — временной диапазон.

  • description — короткий текст, который будет включён в отчёт в качестве его описания.

  • with_growth — флаг, позволяющий расширить интервал до ближайших выборок, в которых имеются данные об увеличении отношений. Значение по умолчанию: false.

  • db_exclude — список исключаемых баз данных. Содержит базы данных, исключаемых из всех таблиц отчёта, содержащих столбец Database. Используйте этот параметр, чтобы скрыть в отчёте выбранные базы данных.

get_report_latest([server name,])
get_report_latest([server name [, db_exclude name[]]])

Строит обычный отчёт для двух последних выборок.

Аргументы:

  • server — имя сервера. Если оно опущено, подразумевается local.

  • db_exclude — список исключаемых баз данных. Содержит базы данных, исключаемых из всех таблиц отчёта, содержащих столбец Database. Используйте этот параметр, чтобы скрыть в отчёте выбранные базы данных.

G.4.10.2. Сравнительные отчёты

Для построения сравнительных отчётов воспользуйтесь следующей функцией:

get_diffreport([server name,] start1_id integer, end1_id integer, start2_id integer, end2_id integer [, description text [, with_growth boolean [, db_exclude name[]]]])
get_diffreport([server name,] time_range1 tstzrange, time_range2 tstzrange [, description text [, with_growth boolean [, db_exclude name[]]]])
get_diffreport([server name,] baseline1 varchar(25), baseline2 varchar(25) [, description text [, with_growth boolean [, db_exclude name[]]]])
get_diffreport([server name,] baseline1 varchar(25), time_range2 tstzrange [, description text [, with_growth boolean[, db_exclude name[]]]])
get_diffreport([server name,] time_range1 tstzrange, baseline2 varchar(25) [, description text [, with_growth boolean[, db_exclude name[]]]])
get_diffreport([server name,] start1_id integer, end1_id integer, baseline2 varchar(25) [, description text [, with_growth boolean[, db_exclude name[]]]])
get_diffreport([server name,] baseline1 varchar(25), start2_id integer, end2_id integer [, description text [, with_growth boolean[, db_exclude name[]]]])

Формирует сравнительный отчёт за два интервала. Различные сочетания аргументов позволяют задать интервалы самыми разными способами.

Аргументы:

  • server — имя сервера. Если оно опущено, подразумевается local.

  • start1_id, end1_id — идентификаторы начальной и конечной выборок для первого интервала.

  • start2_id, end2_id — идентификаторы начальной и конечной выборок для второго интервала.

  • baseline1 — имя выборочной линии для первого интервала.

  • baseline2 — имя выборочной линии для второго интервала.

  • time_range1 — временной диапазон, задающий первый интервал.

  • time_range2 — временной диапазон, задающий второй интервал.

  • description — короткий текст, который будет включён в отчёт в качестве его описания.

  • with_growth — флаг, позволяющий расширить интервал до ближайших выборок, в которых имеются данные об увеличении отношений. Значение по умолчанию: false.

  • db_exclude — список исключаемых баз данных. Содержит базы данных, исключаемых из всех таблиц отчёта, содержащих столбец Database. Используйте этот параметр, чтобы скрыть в отчёте выбранные базы данных.

G.4.10.3. Пример построения отчёта

Построение отчёта для локального сервера (local) за интервал, определяемый выборками:

psql -Aqtc "SELECT profile.get_report(480,482)" -o report_480_482.html

Построение отчёта для другого сервера:

psql -Aqtc "SELECT profile.get_report('omega',12,14)" -o report_omega_12_14.html

Построение отчёта за временной диапазон:

psql -Aqtc "SELECT profile.get_report(tstzrange('2020-05-13 11:51:35+03','2020-05-13 11:52:18+03'))" -o report_range.html

Построение отчёта за временной диапазон, определяемый относительно:

psql -Aqtc "SELECT profile.get_report(tstzrange(now() - interval '1 day',now()))" -o report_last_day.html

G.4.11. Разделы отчёта pgpro_pwr

Каждый отчёт pgpro_pwr включает в себя разделы, описанные ниже. Число первых объектов, выбираемых из отсортированной таблицы при построении отчёта, задаётся параметром pgpro_pwr.max.

Почти любой элемент в отчёте можно выделить одним щелчком мыши. Выбранный элемент будет мгновенно выделен во всех разделах отчёта, что облегчит его поиск. Атрибуты, идентифицирующие элемент, появятся в правом нижнем углу страницы. Например, если выбрать имя базы данных в таблице отчёта «Database statistics» (Статистика базы данных), можно заметить небольшую таблицу с атрибутами базы данных в правом нижнем углу страницы.

При прокрутке отчёта вниз его оглавление будет доступно в правой части страницы. Его можно скрыть одним щелчком мыши по закладке «content».

Также доступен фильтр на основе подстроки, который помогает ограничить содержимое отчёта определёнными объектами. В частности, фильтрация на основе подстроки применяется к текстам запросов.

G.4.11.1. Server statistics (Серверная статистика)

Ниже описаны таблицы, относящиеся к этому разделу отчёта pgpro_pwr.

Таблицы «Database statistics» содержат статистику, собранную за интервал времени, в разрезе баз данных. Эта статистика основана на содержимом представления pg_stat_database. Столбцы такой таблицы отчёта перечислены в Таблице G.8.

Таблица G.8. Database statistics (Статистика баз данных)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данныхdatname
CommitsЧисло зафиксированных транзакцийxact_commit
RollbacksЧисло отменённых транзакцийxact_rollback
DeadlocksЧисло выявленных взаимоблокировокdeadlocks
Checksum FailuresКоличество ошибок контрольных сумм в страницах данных этой базы. Это поле отображается, только если за отчётный интервал в этой базе данных были обнаружены какие-либо ошибки контрольной суммы.checksum_failures
Checksums LastВремя выявления последней ошибки контрольной суммы в страницах данных этой базы. Это поле отображается, только если за отчётный интервал в этой базе данных были обнаружены какие-либо ошибки контрольной суммы.checksum_last_failure
Hit%Процент попаданий в кеш, то есть отношение числа страниц, прочитанных из буферов, к общему числу страниц 
ReadКоличество прочитанных дисковых блоков в этой базе данныхblks_read
HitСколько раз требуемые блоки с диска уже находились в кешеblks_hit
RetКоличество выданных кортежейtup_returned
FetКоличество считанных кортежейtup_fetched
InsКоличество вставленных кортежейtup_inserted
UpdКоличество изменённых кортежейtup_updated
DelКоличество удалённых кортежейtup_deleted
Parallel workers PlannedКоличество параллельных рабочих процессов, которые планируется запустить запросами в этой базе данных
Parallel workers LaunchedКоличество параллельных рабочих процессов, запущенных запросами в этой базе данных
Temp SizeОбщий объём данных, записанный во временные файлы при выполнении запросов в этой базе данныхtemp_bytes
Temp FilesКоличество временных файлов, созданных запросами в этой базе данныхtemp_files
SizeРазмер базы данных в момент получения последней выборки в отчётном интервалеpg_database_size()
GrowthПрирост объёма базы данных за отчётный интервалПриращение pg_database_size() на конец интервала относительно начала

Таблица отчёта «Cluster I/O statistics» (Статистика ввода-вывода кластера) показывает статистику ввода-вывода по типам объектов, типам обслуживающих процессов и контекстам. Эта таблица основана на представлении pg_stat_io Системы накопительной статистики, доступном начиная с Postgres Pro 16. Столбцы этой таблицы перечислены в Таблице G.9. Значения времени в ней выражаются в секундах.

Таблица G.9. Cluster I/O statistics (Статистика ввода-вывода кластера)

СтолбецОписание
ObjectЦелевой объект операции ввода-вывода
BackendТип обслуживающего процесса, выполнившего операцию ввода-вывода
ContextКонтекст операции ввода-вывода
Reads CountКоличество операций чтения
Reads BytesОбъём прочитанных данных
Reads TimeВремя, затраченное операциями чтения
Writes CountКоличество операций записи
Writes BytesОбъём записанных данных
Writes TimeВремя, затраченное операциями записи
Writebacks CountКоличество блоков, запрошенных процессом для записи ядром в постоянное хранилище
Writebacks BytesОбъём данных, запрошенных для записи в постоянное хранилище
Writebacks TimeВремя, затраченное на операции отложенной записи, в том числе на постановку в очередь запросов на запись, и, возможно, на запись «грязных» данных
Extends CountКоличество операций расширения отношений
Extends BytesОбъём пространства, использованного операциями расширения
Extends TimeВремя, затраченное операциями расширения
HitsСколько раз нужный блок был найден в общем буфере
EvictionsСколько раз блок был записан из общего или локального буфера, чтобы его можно было переиспользовать
ReusesСколько раз существующий буфер в кольцевом буфере с ограниченным размером за пределами общих буферов был повторно использован как часть операции ввода-вывода в контекстах bulkread, bulkwrite или vacuum
Fsyncs CountКоличество вызовов fsync. Они отслеживаются только в контексте normal
Fsyncs TimeВремя, затраченное операциями синхронизации с файловой системой

Таблица отчёта «Cluster SLRU statistics» (Статистика SLRU-кеша кластера) показывает статистику доступа к SLRU-кешам (simple least-recently-used, простое вытеснение давно не используемых). Эта таблица основана на представлении pg_stat_slru Системы накопительной статистики. Столбцы этой таблицы перечислены в Таблице G.10. Значения времени в ней выражаются в секундах.

Таблица G.10. Cluster SLRU statistics (Статистика SLRU-кеша кластера)

СтолбецОписаниеПоле/вычисление
NameИмя SLRU-кешаname
ZeroedКоличество блоков, обнулённых при инициализацииblks_zeroed
HitsСколько раз дисковые блоки обнаруживались в SLRU-кеше и чтение с диска не требовалось (здесь учитываются только случаи обнаружения в этом кеше, а не в файловом кеше ОС)blks_hit
ReadsКоличество дисковых блоков, прочитанных для этого SLRU-кешаblks_read
%HitКоличество попаданий дискового блока для этого SLRU-кеша в процентах от Reads + Hitsblks_hit*100/blks_read + blks_hit
WritesКоличество дисковых блоков, записанных для этого SLRU-кешаblks_written
CheckedКоличество блоков, проверенных на предмет наличия в этом SLRU-кешеblks_exists
FlushesКоличество операций сброса «грязных» данных для этого SLRU-кешаflushes
TruncatesКоличество операций усечения для этого SLRU-кешаtruncates

Таблица «Session statistics by database» выводится в отчёте для баз Postgres Pro, начиная с версии 14. Эта таблица основана на представлении pg_stat_database сборщика статистики. Столбцы этой таблицы перечислены в Таблице G.11. Значения времени в ней выражаются в секундах.

Таблица G.11. Session statistics by database (Статистика сеансов по базам данных)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данных 
Timings TotalДлительность сеансов в этой базе за отчётный интервал (обратите внимание, что статистика обновляется только при изменении состояния сеанса, поэтому, если сеансы простаивают в течение длительного времени, время простоя не будет учитываться)session_time
Timings ActiveВремя, затраченное на выполнение операторов SQL в этой базе за отчётный интервал (соответствует состояниям active и fastpath function call в pg_stat_activity)active_time
Timings IdleВремя простоя в транзакциях в этой базе за отчётный интервал (соответствует состояниям idle in transaction и idle in transaction (aborted) в pg_stat_activity)idle_in_transaction_time
Sessions EstablishedОбщее количество сеансов, относящихся к этой базе, за отчётный интервалsessions
Sessions AbandonedКоличество сеансов в этой базе данных, прерванных из-за потери соединения с клиентом, за отчётный интервалsessions_abandoned
Sessions FatalКоличество сеансов в этой базе данных, прерванных из-за критических ошибок, за отчётный интервалsessions_fatal
Sessions KilledКоличество сеансов в этой базе данных, прерванных из-за вмешательства оператора, за отчётный интервалsessions_killed

В базах данных Postgres Pro Enterprise версий, включающих версию pgpro_stats 1.4 и выше, доступна статистика нагрузки процессов очистки. В отчёте выводится таблица «Database vacuum statistics», содержащая общую агрегированную статистику очистки по базам данных из pgpro_stats_vacuum_tables. Столбцы этой таблицы перечислены в Таблице G.12. Значения времени в ней выражаются в секундах.

Таблица G.12. Database vacuum statistics (Статистика очистки баз данных)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данных 
Blocks fetchedОбщее количество блоков БД, полученных операциями очисткиtotal_blks_read + total_blks_hit
Fetched %TotalОбщее количество блоков БД (прочитанных и найденных в общих буферах), полученных операциями очистки, в процентах от общего числа блоков, полученных в кластереBlocks fetched * 100 / Cluster fetched
Blocks readОбщее количество блоков БД, прочитанных операциями очисткиtotal_blks_read
Read %TotalОбщее количество блоков БД, прочитанных операциями очистки, в процентах от общего числа блоков, прочитанных в кластереBlocks read * 100 / Cluster read
VM FrozenОбщее количество блоков, помеченных в карте видимости как полностью замороженныеpages_frozen
VM VisibleОбщее количество блоков, помеченных в карте видимости как полностью видимыеpages_all_visible
Tuples deletedОбщее количество «мёртвых» кортежей, удалённых операциями очистки из таблиц этой БДtuples_deleted
Tuples leftОбщее количество «мёртвых» кортежей, оставленных операциями очистки в таблицах этой БД из-за видимости этих кортежей в транзакцияхdead_tuples
%EffЭффективность очистки, оцениваемая по количеству удалённых кортежей. Это процент кортежей, удалённых из таблиц этой базы данных, от всех «мёртвых» кортежей, подлежащих удалению из этих таблиц.tuples_deleted * 100 / (tuples_deleted + dead_tuples)
WAL sizeОбщий объём WAL (в байтах), сгенерированный операциями очистки, выполненными для таблиц этой БДwal_bytes
Read I/O timeВремя, затраченное на чтение блоков БД операциями очистки, выполненными для таблиц этой БДblk_read_time
Write I/O timeВремя, затраченное на запись блоков БД операциями очистки, выполненными для таблиц этой БДblk_write_time
%TotalВремя, затраченное на чтение/запись в процессе очистки, в процентах от всего времени чтения/записи в кластере
Vacuum time TotalОбщее время, затраченное на очистку таблиц этой БДtotal_time
Vacuum time DelayВремя простоя в точке задержки при выполнении операций очистки таблиц этой БДdelay_time
User CPU timeВремя использования процессора в пользовательском режиме при очистке таблиц этой БДuser_time
System CPU timeВремя использования процессора в режиме ядра при очистке таблиц этой БДsystem_time
InterruptsСколько раз операции очистки, выполнявшиеся для таблиц этой БД, были прерваны из-за каких-либо ошибокinterrupts

Если в отчётном интервале было доступно расширение pgpro_stats, поддерживающее статистики аннулирования, в отчёте выводится таблица «Invalidation messages by database» с общей агрегированной статистикой событий аннулирования по каждой базе данных. Столбцы этой таблицы перечислены в Таблице G.13.

Таблица G.13. Invalidation messages by database (Число событий аннулирования в базе данных)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данных 
Invalidation messages sentОбщее количество событий аннулирования, отправленных обслуживающими процессами в этой базе данных. Статистика предоставляется для соответствующих типов сообщений pgpro_stats_inval_msgsПоля столбца pgpro_stats_totals.inval_msgs
Cache resetsОбщее число сбросов разделяемого кешаpgpro_stats_totals.cache_resets

Если в отчётном интервале было доступно расширение pgpro_stats, в отчёте выводится таблица «Statement statistics by database» с общей агрегированной статистикой из pgpro_stats_statements по каждой базе данных. Столбцы этой таблицы перечислены в Таблице G.14. Значения времени в ней выражаются в секундах.

Таблица G.14. Statement statistics by database (Статистика SQL-операторов в базе данных)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данных 
CallsСчётчик всех выполненных SQL-операторов в базеcalls
Plan TimeВремя, затраченное на планирование операторов в этой базеСумма значений total_plan_time
Exec TimeВремя, затраченное на выполнение всех операторов в этой базеСумма значений total_exec_time
Read TimeВремя, затраченное на чтение блоков в этой базеСумма значений blk_read_time
Write TimeВремя, затраченное на запись блоков в этой базеСумма значений blk_write_time
Trg TimeВремя, затраченное на выполнение триггерных функций в этой базе 
Shared FetchedОбщее количество разделяемых блоков, прочитанных в этой базеСумма значений shared_blks_read + shared_blks_hit
Local FetchedОбщее количество локальных блоков, прочитанных в этой базеСумма значений local_blks_read + local_blks_hit
Shared DirtiedОбщее количество разделяемых блоков, загрязнённых при выполнении операторов в этой базеСумма значений shared_blks_dirtied
Local DirtiedКоличество прочитанных локальных блоков, загрязнённых при выполнении операторов в этой базеСумма значений local_blks_dirtied
Read TempОбщее количество временных блоков, прочитанных всеми операторами в этой базеСумма значений temp_blks_read
Write TempОбщее количество временных блоков, записанных всеми операторами в этой базеСумма значений temp_blks_written
Read LocalОбщее количество локальных блоков, прочитанных в этой базеСумма значений local_blks_read
Write LocalОбщее количество локальных блоков, записанных в этой базеСумма значений local_blks_written
StatementsОбщее число обработанных SQL-операторов 
WAL SizeОбщий объём WAL, сгенерированный в этой базеСумма значений wal_bytes
WAL buffers fullКоличество случаев переполнения буферов WAL

Таблица отчёта «Statement average min/max timings» содержит агрегированную статистику о минимальных/максимальных замерах времени за отчётный интервал, в разрезе баз данных, из представлений расширения pgpro_stats или pg_stat_statements (предпочтение отдаётся представлению pgpro_stats). Этот отчёт учитывает самое быстрое и самое медленное планирование и выполнение каждого оператора в кластере, то есть позволяет увидеть стабильность выполнения и планирования в базе данных. Столбцы такой таблицы отчёта перечислены в Таблице G.15.

Таблица G.15. Statement average min/max timings (Средние значения минимальных/максимальных замеров времени)

СтолбецОписание
DatabaseИмя базы данных
Min average planning timeСреднее значение min_plan_time для всех операторов и всех выборок, включённых в отчёт, в миллисекундах
Max average planning timeСреднее значение max_plan_time для всех операторов и всех выборок, включённых в отчёт, в миллисекундах
Delta% of average planning timesРазность среднего значения max_plan_time и среднего значения min_plan_time в процентах от среднего значения min_plan_time. Чем меньше эта разность, тем стабильнее планирование запросов в базе данных.
Min average execution timeСреднее значение min_exec_time для всех операторов и всех выборок, включённых в отчёт, в миллисекундах
Max average execution timeСреднее значение max_exec_time для всех операторов и всех выборок, включённых в отчёт, в миллисекундах
Delta% of average execution timesРазность среднего значения max_exec_time и среднего значения min_exec_time в процентах от среднего значения min_exec_time. Чем меньше эта разность, тем стабильнее выполнение запросов в базе данных.
StatementsОбщее число операторов, попавших в выборки

Если расширение, собирающее статистику операторов в отчётном интервале, собрало статистику JIT, в отчёте выводится таблица «JIT statistics by database» с общей агрегированной статистикой по использованию JIT в разрезе баз данных. Столбцы этой таблицы перечислены в Таблице G.16. Значения времени в ней выражаются в секундах.

Таблица G.16. JIT statistics by database (Статистика JIT в базах данных)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данных 
CallsСчётчик всех выполненных SQL-операторов в базеcalls
Plan TimeВремя, затраченное на планирование операторов в этой базеСумма значений total_plan_time
Exec TimeВремя, затраченное на выполнение всех операторов в этой базеСумма значений total_exec_time
Generation countОбщее число функций, скомпилированных в JIT-код при выполнении операторовСумма значений jit_functions
Generation timeОбщее время, затраченное на компиляцию JIT-кода при выполнении операторовСумма значений jit_generation_time
Inlining countСколько раз встраивались функцииСумма значений jit_inlining_count
Inlining timeОбщее время, затраченное на встраивание функций при выполнении операторовСумма значений jit_inlining_time
Optimization countОбщее число JIT-оптимизаций для операторовСумма значений jit_optimization_count
Optimization timeОбщее время, затраченное на JIT-оптимизацию при выполнении операторовСумма значений jit_optimization_time
Emission countСколько раз выдавался кодСумма значений jit_emission_count
Emission timeОбщее время, затраченное на выдачу кода при выполнении операторовСумма значений jit_emission_time
Deform countЧисло функций преобразования кортежей, скомпилированных в JIT-код при выполнении данного оператора
Deform timeОбщее время, затраченное операторами на компилирование функций преобразования кортежей в JIT-код

В таблице отчёта «Cluster statistics» содержатся данные из представлений pg_stat_bgwriter и pg_stat_checkpointer. Последнее представление доступно, начиная с Postgres Pro 17. Строки данной таблицы перечислены в Таблице G.17. Значения времени в ней выражаются в секундах.

Таблица G.17. Cluster statistics (Статистика кластера)

СтрокаОписаниеПоле/вычисление
Checkpoints ScheduledКоличество запланированных контрольных точек, которые уже были выполненыcheckpoints_timed
Checkpoints RequestedКоличество запрошенных контрольных точек, которые уже были выполненыcheckpoints_req
Checkpoints DoneКоличество контрольных точек, которые были выполнены
Restartpoints ScheduledКоличество запланированных точек перезапуска из-за тайм-аута или после неудачной попытки выполнить перезапускrestartpoints_timed
Restartpoints RequestedКоличество запрошенных точек перезапуска (при наличии)restartpoints_req
Restartpoints DoneКоличество точек перезапуска, которые были выполнены (при наличии)restartpoints_done
Checkpoint write timeОбщее время, которое было затрачено на часть обработки контрольных точек и точек перезапуска, в которой файлы записываются на дискcheckpoint_write_time
Checkpoint sync timeОбщее время, которое было затрачено на часть обработки контрольных точек и точек перезапуска, в которой файлы синхронизируются с дискомcheckpoint_sync_time
Checkpoint buffers writtenКоличество общих буферов, записанных при выполнении контрольных точек и точек перезапускаbuffers_checkpoint
SLRU buffers written by checkpointКоличество SLRU-буферов, записанных при выполнении контрольных точек и точек перезапуска
Background buffers writtenКоличество буферов, записанных фоновым процессом записиbuffers_clean
Backend buffers writtenКоличество буферов, записанных самим обслуживающим процессом. Не будет показываться в Postgres Pro 17 и выше.buffers_backend
Backend fsync countСколько раз обслуживающему процессу пришлось выполнить fsync самостоятельно (обычно фоновый процесс записи сам обрабатывает эти вызовы, даже когда обслуживающий процесс выполняет запись самостоятельно). Не будет показываться в Postgres Pro 17 и выше.buffers_backend_fsync
Bgwriter interrupts (too many buffers)Сколько раз фоновый процесс записи останавливал сброс грязных страниц на диск из-за того, что записал слишком много буферовmaxwritten_clean
Number of buffers allocatedОбщее количество выделенных буферовbuffers_alloc
WAL generatedОбщий сгенерированный объём WALПриращение значения pg_current_wal_lsn()
Start LSNПоследовательный номер в журнале в начале отчётного интервалаpg_current_wal_lsn() в первой выборке отчёта
End LSNПоследовательный номер в журнале в конце отчётного интервалаpg_current_wal_lsn() в последней выборке отчёта
WAL generated by vacuumОбщий объём WAL, сгенерированный при очисткеОсновано на значении поля wal_bytes представления pgpro_stats_vacuum_databases.
WAL segments archivedОбщее количество заархивированных сегментов WALОсновано на значении pg_stat_archiver.archived_count
WAL segments archive failedОбщее количество ошибок, возникших при архивировании сегментов WALОсновано на значении pg_stat_archiver.failed_count.
Archiver performanceСредняя производительность процесса архивирования в секундуОсновано на значении поля active_time представления pgpro_stats_archiver.
Archive command performanceСредняя производительность команды archive_command в секундуОсновано на значении поля archive_command_time представления pgpro_stats_archiver.

Таблица «WAL statistics» выводится в отчёте для баз Postgres Pro, начиная с версии 14. Эта таблица основана на представлении pg_stat_wal сборщика статистики. Столбцы этой таблицы отчёта перечислены в Таблице G.18. Значения времени в ней выражаются в секундах.

Таблица G.18. WAL statistics (Статистика WAL)

СтрокаОписаниеПоле/вычисление
WAL generatedОбщий объём записей WAL, сгенерированных за отчётный интервалwal_bytes
WAL per secondСреднее количество записей WAL, генерируемых в секунду, за отчётный интервалwal_bytes / report_duration
WAL recordsОбщее число записей WAL, сгенерированных за отчётный интервалwal_records
WAL FPIОбщее число образов полных страниц WAL, сгенерированных за отчётный интервалwal_fpi
WAL buffers fullСколько раз данные WAL записывались на диск из-за переполнения буферов WAL за отчётный интервалwal_buffers_full
WAL writesСколько раз буферы WAL были записаны на диск функцией XLogWrite за отчётный интервалwal_write
WAL writes per secondСколько раз в секунду в среднем буферы WAL записывались на диск функцией XLogWrite за отчётный интервалwal_write / report_duration
WAL syncСколько раз файлы WAL сбрасывались на диск функцией issue_xlog_fsync за отчётный интервал (если fsync включён и wal_sync_method имеет значение fdatasync, fsync или fsync_writethrough, в противном случае — ноль). Более подробную информацию о внутренней функции WAL issue_xlog_fsync можно найти в Разделе 29.5.wal_sync
WAL syncs per secondСколько раз в секунду в среднем файлы WAL сбрасывались на диск функцией issue_xlog_fsync за отчётный интервалwal_sync / report_duration
WAL write timeОбщее время, затраченное на запись буферов WAL на диск функцией XLogWrite, за отчётный интервал (если включён track_wal_io_timing, в противном случае — ноль; за дополнительными сведениями обратитесь к разделу Разделе 19.9). Учитывается и время синхронизации, когда wal_sync_method имеет значение open_datasync или open_sync.wal_write_time
WAL write dutyПроцент WAL write time от продолжительности отчётаwal_write_time * 100 / report_duration
WAL sync timeОбщее время, затраченное на сброс файлов WAL на диск функцией issue_xlog_fsync, за отчётный интервал (если track_wal_io_timing включён, значение fsync — on и wal_sync_method имеет значение fdatasync, fsync или fsync_writethrough, в противном случае — ноль).wal_sync_time
WAL sync dutyПроцент WAL sync time от продолжительности отчётаwal_sync_time * 100 / report_duration

В таблице отчёта «Tablespace statistics» содержится информация о размере и приросте табличных пространств. Столбцы этой таблицы перечислены в Таблице G.19.

Таблица G.19. Tablespace statistics (Статистика табличных пространств)

СтолбецОписаниеПоле/вычисление
TablespaceИмя табличного пространстваpg_tablespace.spcname
PathПуть табличного пространстваpg_tablespace_location()
SizeРазмер табличного пространства в момент получения последней выборки в отчётном интервалеpg_tablespace_size()
GrowthПрирост объёма табличного пространства за отчётный интервалПриращение pg_tablespace_size() на конец интервала относительно начала

Если в отчётном интервале было доступно расширение pgpro_stats, в отчёте выводится таблица «Wait statistics by database» с информацией об общем времени ожидания в разрезе типов ожидания и баз данных. Столбцы этой таблицы перечислены в Таблице G.20.

Таблица G.20. Wait statistics by database (Статистика ожидания в базах данных)

СтолбецОписание
DatabaseИмя базы данных
Wait event typeТип события, которого ожидали серверные процессы. Звёздочка вместо типа соответствует совокупности всех типов ожидания в базе данных.
WaitedВремя, проведённое в ожидании событий типа Wait event type, в секундах
%TotalОтношение времени, проведённого в ожидании событий типа Wait event type, к общему времени ожидания таких событий в кластере

Если в отчётном интервале было доступно расширение pgpro_stats, в отчёте выводится таблица «Top wait events» с информацией о наиболее длительных событиях ожидания в кластере. Столбцы этой таблицы перечислены в Таблице G.21.

Таблица G.21. Top wait events (Преобладающие события ожидания)

СтолбецОписание
DatabaseИмя базы данных
Wait event typeТип события, которого ждали серверные процессы
Wait eventНазвание события ожидания, которого ждали серверные процессы
WaitedОбщее время, проведённое в ожидании событий типа Wait event в базе данных, в секундах
%TotalОтношение времени, проведённого в ожидании события Wait event в базе данных к общему времени ожидания этого события в кластере

G.4.11.2. Load distribution (Распределение нагрузки)

Этот раздел отчёта pgpro_pwr основан на представлении pgpro_stats_totals расширения pgpro_stats, если оно было доступно в течение отчётного интервала. Каждая таблица в данном разделе предоставляет данные за отчётный интервал о распределении нагрузки для определённого типа объектов, для которых собирается агрегированная статистика, например, баз данных, приложений, узлов или пользователей. Каждая таблица содержит по одной строке для каждого из ресурсов (таких, как общее время или общее число записанных разделяемых блоков), где распределение нагрузки показано на графике в виде линейчатой диаграммы с накоплением для объектов с наибольшей нагрузкой по этому ресурсу. Если область диаграммы, соответствующая объекту, слишком узка для включения заголовков, наведите указатель на эту область, чтобы получить подсказку с заголовком, значением и процентом. Таблицы «Load distribution among heavily loaded databases», «Load distribution among heavily loaded applications», «Load distribution among heavily loaded hosts» и «Load distribution among heavily loaded users» показывают распределение нагрузки для соответствующих объектов. Строки этих таблиц описаны в Таблице G.22. Значения времени в этих таблицах выражаются в секундах.

Таблица G.22. Load distribution (Распределение нагрузки)

СтрокаОписаниеВычисление
Total timeОбщее время, затраченное на планирование и выполнение операторовtotal_plan_time + total_exec_time
Executed countЧисло выполненных запросовqueries_executed
I/O timeОбщее время, затраченное операторами на чтение или запись блоков (если включён track_io_timing, или ноль в противном случае)blk_read_time + blk_write_time
Blocks fetchedОбщее число разделяемых блоков, прочитанных с диска и из кеша, для данного оператораshared_blks_hit + shared_blks_read
Shared blocks readОбщее количество разделяемых блоков, прочитанных операторамиshared_blks_read
Shared blocks dirtiedОбщее число разделяемых блоков, «загрязнённых» операторамиshared_blks_dirtied
Shared blocks writtenОбщее число разделяемых блоков, записанных операторамиshared_blks_written
WAL generatedОбщий объём WAL, сгенерированный при выполнении операторовwal_bytes
Temp and Local blocks writtenОбщее число временных и локальных блоков, записанных операторамиtemp_blks_written + local_blks_written
Temp and Local blocks readОбщее количество временных и локальных блоков, прочитанных операторамиtemp_blks_read + local_blks_read
Invalidation messages sentОбщее число событий аннулирования, отправленных обслуживающими процессами в этой базе данных(pgpro_stats_totals.inval_msgs).all
Cache resetsОбщее число сбросов разделяемого кешаpgpro_stats_totals.cache_resets

G.4.11.3. Состояния сеансов, попадающие в промежуточные выборки

В этом разделе отчёта pgpro_pwr содержится информация о состояниях сеансов, попавших в промежуточные выборки за отчётный интервал.

Ниже описаны таблицы, относящиеся к этому разделу отчёта.

Подраздел отчёта «Chart with session state» показывает состояния сеансов, попавшие в промежуточные выборки. Это график линии времени, иллюстрирующий попавшие в выборку состояния сеансов в обслуживающих процессах и транзакциях. Каждое состояние содержит всплывающее окно с атрибутами состояния сеанса. Нажмите на состояние, чтобы увидеть его в таблице состояний сеансов.

В таблице отчёта «Session state statistics by database» (Статистики состояний сеансов по базам данных) содержатся агрегированные данные о состояниях сеансов. Считаются только состояния сеансов, попавшие в промежуточные выборки. Столбцы этой таблицы перечислены в Таблице G.23.

Таблица G.23. Session state statistics by database (Статистики состояний сеансов по базам данных)

СтолбецОписание
DatabaseИмя базы данных
Summary ActiveОбщее время, проведённое в состояниях active, которые попали в промежуточные выборки
Summary Idle in xactОбщее время состояний idle in transaction, попавших в промежуточные выборки
Summary Idle in xact (A)Общее время состояний idle in transaction (aborted), попавших в промежуточные выборки
Maximal ActiveПродолжительность самого длительного состояния active, попавшего в промежуточные выборки
Maximal Idle in xactПродолжительность самого длительного состояния idle in transaction, попавшего в промежуточные выборки
Maximal Idle in xact (A)Продолжительность самого длительного состояния idle in transaction (aborted), попавшего в промежуточные выборки
Maximal xact ageМаксимальный возраст транзакций, попавший в промежуточные выборки

В таблице отчёта «Top 'idle in transaction' session states by duration» показано pgpro_pwr.max самых длительных состояний idle in transaction для каждого сеанса. Эта информация основана на данных последнего наблюдения каждого из них в представлении pg_stat_activity. Столбцы такой таблицы отчёта перечислены в Таблице G.24.

Таблица G.24. Top 'idle in transaction' session states by duration (Самые длительные состояния 'idle in transaction' сеансов)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данныхdatname
UserИмя пользователяusename
AppИмя приложенияapplication_name
PidИдентификатор процессаpid
Xact startВременная метка начала транзакцииxact_start
State changeВременная метка изменения состоянияstate_change
State durationПродолжительность состоянияРазность clock_timestamp() и state_change

В таблице отчёта «Top 'active' session states by duration» показаны pgpro_pwr.max самых длительных состояний active для каждого сеанса. Эта информация основана на данных последнего наблюдения каждого из них в представлении pg_stat_activity. Столбцы такой таблицы отчёта перечислены в Таблице G.25.

Таблица G.25. Top 'active' session states by duration (Самые длительные состояния 'active' сеансов)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данныхdatname
UserИмя пользователяusename
AppИмя приложенияapplication_name
PidИдентификатор процессаpid
Xact startВременная метка начала транзакцииxact_start
State changeВременная метка изменения состоянияstate_change
State durationПродолжительность состоянияРазность clock_timestamp() и state_change

В таблице отчёта «Top states by transaction age» показаны состояния сеансов с самым большим возрастом транзакций. Эта информация основана на данных последнего наблюдения каждого из них в представлении pg_stat_activity. Столбцы такой таблицы отчёта перечислены в Таблице G.26.

Таблица G.26. Top states by transaction age (Состояния с самым большим возрастом транзакций)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данныхdatname
UserИмя пользователяusename
AppИмя приложенияapplication_name
PidИдентификатор процессаpid
Xact startВременная метка начала транзакцииxact_start
Xact durationПродолжительность транзакцииРазность clock_timestamp() и xact_start
AgeВозраст транзакцииage(backend_xmin)
StateСостояние сеанса при максимальном обнаруженном возрасте 
State changeВременная метка изменения состоянияstate_change
State durationПродолжительность состоянияРазность clock_timestamp() и state_change

В таблице отчёта «Top states by transaction duration» показаны самые длительные состояния сеансов. Эта информация основана на данных последнего наблюдения каждого из них в представлении pg_stat_activity. Столбцы такой таблицы отчёта перечислены в Таблице G.26.

Таблица G.27. Top states by transaction duration (Состояния с наибольшей продолжительностью транзакций)

СтолбецОписаниеПоле/вычисление
DatabaseИмя базы данныхdatname
UserИмя пользователяusename
AppИмя приложенияapplication_name
PidИдентификатор процессаpid
Xact startВременная метка начала транзакцииxact_start
Xact durationПродолжительность транзакцииРазность clock_timestamp() и xact_start
AgeВозраст транзакцииage(backend_xmin)
StateСостояние сеанса при максимальном обнаруженном возрасте 
State changeВременная метка изменения состоянияstate_change
State durationПродолжительность состоянияРазность clock_timestamp() и state_change

G.4.11.4. Статистика SQL-запросов

В этом разделе отчёта pgpro_pwr представлена информация о наиболее выдающихся по разным критериям операторах за отчётный интервал. В основном эти данные получаются из представлений расширения pgpro_stats и pg_stat_statements (предпочтение отдаётся представлению pgpro_stats). Каждый оператор можно выделить во всех разделах, связанных с SQL, одним щелчком мыши. При этом прямо под строкой статистики запроса также доступен для предварительного просмотра текст запроса, который можно скрыть повторным щелчком мыши по запросу.

Ниже описаны таблицы, относящиеся к этому разделу отчёта.

Таблица отчёта «Top SQL by elapsed time» показывает запросы с наибольшей длительностью, рассчитанной как сумма полей total_plan_time и total_exec_time в представлении pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.28. Значения времени в ней выражаются в секундах.

Таблица G.28. Top SQL by elapsed time (SQL-запросы с наибольшей длительностью)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
%TotalОтношение времени, затраченного на выполнение плана, к общему времени всех запросов в кластере 
Elapsed TimeОбщее время, затраченное на планирование и выполнение плана запросаtotal_plan_time + total_exec_time
Plan TimeОбщее время, затраченное на планирование запросаtotal_plan_time
Exec TimeОбщее время, затраченное на выполнение плана запросаtotal_exec_time
JIT TimeОбщее время, затраченное на выполнение этого плана оператора с применением JIT, в секундахjit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Read I/O timeОбщее время, потраченное при выполнении запроса на чтение блоковblk_read_time
Write I/O timeОбщее время, потраченное при выполнении запроса на запись блоковblk_write_time
Usr CPU timeПроцессорное время, потраченное в пользовательском режиме, в секундахrusage.user_time
Sys CPU timeПроцессорное время, потраченное в режиме ядра, в секундахrusage.system_time
PlansСколько раз строился данный план запросаplans
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by planning time» показывает запросы с наибольшей длительностью планирования, определяемой по значению поля total_plan_time представления pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.29.

Таблица G.29. Top SQL by planning time (SQL-запросы с наибольшей длительностью планирования)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Plan elapsedОбщее время, затраченное на построение плана данного запроса, в секундахtotal_plan_time
%ElapsedОтношение total_plan_time к сумме total_plan_time и total_exec_time для данного плана 
Mean plan timeСреднее время планирования данного запроса, в миллисекундахmean_plan_time
Min plan timeМинимальное время планирования данного запроса, в миллисекундахmin_plan_time
Max plan timeМаксимальное время планирования данного запроса, в миллисекундахmax_plan_time
StdErr plan timeСтандартное отклонение времени, затраченного на планирование запроса, в миллисекундахstddev_plan_time
PlansСколько раз строился данный план запросаplans
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by execution time» показывает запросы с наибольшей длительностью выполнения, определяемой по значению поля total_time представления pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.30.

Таблица G.30. Top SQL by execution time (SQL-запросы с наибольшей длительностью выполнения)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
ExecОбщее время, потраченное на выполнение плана запроса, в секундахtotal_exec_time
%ElapsedПроцент времени total_exec_time, затраченного на выполнение плана, от времени выполнения данного оператора 
%TotalОтношение времени total_exec_time, затраченного на выполнение плана, к общему времени выполнения всех запросов в кластере 
JIT TimeОбщее время, затраченное на выполнение этого плана оператора с применением JIT, в секундахjit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Read I/O timeОбщее время, затраченное на чтение страниц при выполнении плана, в секундахblk_read_time
Write I/O timeОбщее время, затраченное на запись страниц при выполнении плана, в секундахblk_write_time
Usr CPU timeПроцессорное время, потраченное в пользовательском режиме, в секундахrusage.user_time
Sys CPU timeПроцессорное время, потраченное в режиме ядра, в секундахrusage.system_time
RowsЧисло строк, полученных или обработанных при выполнении планаrows
Mean execution timeСреднее время, потраченное на выполнение плана, в миллисекундахmean_exec_time
Min execution timeМинимальное время, потраченное на выполнение плана, в миллисекундахmin_exec_time
Max execution timeМаксимальное время, потраченное на выполнение плана, в миллисекундахmax_exec_time
StdErr execution timeСтандартное отклонение времени, затраченного на выполнение плана, в миллисекундахstddev_exec_time
ExecutionsСколько раз выполнялся планcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by mean execution time» показывает pgpro_pwr.max запросов с наибольшей средней длительностью выполнения, определяемой по значению поля mean_time или mean_exec_time представления pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.31.

Таблица G.31. Top SQL by mean execution time (SQL-запросы с наибольшей средней длительностью выполнения)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Mean execution timeСреднее время, потраченное на выполнение оператора, в миллисекундахmean_exec_time
Min execution timeМинимальное время, потраченное на выполнение оператора, в миллисекундахmin_exec_time
Max execution timeМаксимальное время, потраченное на выполнение оператора, в миллисекундахmax_exec_time
StdErr execution timeСтандартное отклонение времени, затраченного на выполнение оператора, в миллисекундахstddev_exec_time
ExecВремя, потраченное на выполнение этого оператора, в секундахtotal_exec_time
%ElapsedВремя выполнения этого оператора в процентах от общего времени, затраченного на оператор
%TotalВремя выполнения этого оператора в процентах от общего времени, затраченного на все операторы в кластере
JIT timeОбщее время, затраченное на выполнение этого оператора с применением JIT, в секундахjit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Read I/O timeВремя, затраченное на чтение блоков, в секундахblk_read_time
Write I/O timeВремя, затраченное на запись блоков, в секундахblk_write_time
RowsЧисло строк, полученных или обработанных операторомrows
ExecutionsСчётчик выполнений этого оператораcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by executions» показывает запросы, которые выполнялись чаще других, что определяется по значению поля calls представления pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.32.

Таблица G.32. Top SQL by executions (Наиболее частые SQL-запросы)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
ExecutionsСколько раз выполнялся план запросаcalls
%TotalОтношение числа выполнений этого запроса (calls) к сумме значений calls по всем запросам, выполненным в кластере 
RowsЧисло строк, полученных или обработанных при выполнении планаrows
MeanСреднее время, потраченное на выполнение плана, в миллисекундахmean_exec_time
MinМинимальное время, потраченное на выполнение плана, в миллисекундахmin_exec_time
MaxМаксимальное время, потраченное на выполнение плана, в миллисекундахmax_exec_time
StdErrСтандартное отклонение времени, затраченного на выполнение плана, в миллисекундахstddev_time
ElapsedОбщее время, потраченное на выполнение плана запроса, в секундахtotal_exec_time
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by I/O wait time» показывает запросы с наибольшей длительностью операций чтения/записи, определяемой как сумма полей blk_read_time и blk_write_time представления pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.33. Значения времени в ней выражаются в секундах.

Таблица G.33. Top SQL by I/O wait time (SQL-запросы с наибольшим временем I/O)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
IO(s)Общее время, затраченное на чтение/запись при выполнении плана, то есть время ввода-выводаblk_read_time + blk_write_time
R(s)Общее время, затраченное на чтение при выполнении планаblk_read_time
W(s)Общее время, затраченное на запись при выполнении планаblk_write_time
%TotalОтношение времени ввода-вывода при выполнении этого плана к общему времени ввода-вывода для всех запросов в кластере 
Shr ReadsОбщее число разделяемых блоков, прочитанных при выполнении планаshared_blks_read
Loc ReadsОбщее число локальных блоков, прочитанных при выполнении планаlocal_blks_read
Tmp ReadsОбщее число временных блоков, прочитанных при выполнении планаtemp_blks_read
Shr WritesОбщее число разделяемых блоков, записанных при выполнении планаshared_blks_written
Loc WritesОбщее число локальных блоков, записанных при выполнении планаlocal_blks_written
Tmp WritesОбщее число временных блоков, записанных при выполнении планаtemp_blks_written
Elapsed(s)Общее время, затраченное на выполнение плана запросаtotal_plan_time + total_exec_time
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by shared blocks fetched» показывает запросы с наибольшим количеством полученных (с диска или из кеша) блоков, что помогает выявить запросы, наиболее активно читающие данные. Столбцы этой таблицы перечислены в Таблице G.34.

Таблица G.34. Top SQL by shared blocks fetched (SQL-запросы, получившие максимум разделяемых блоков)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Blks fetchedЧисло блоков, полученных при выполнении этого плана запросаshared_blks_hit + shared_blks_read
%TotalОтношение числа блоков, полученных при выполнении этого плана, к общему числу блоков, полученных при выполнении всех запросов в кластере 
Hits(%)Отношение числа блоков, полученных из буферов, к общему числу полученных блоков 
ElapsedОбщее время, затраченное на выполнение плана запроса, в секундахtotal_plan_time + total_exec_time
RowsЧисло строк, полученных или обработанных при выполнении планаrows
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by shared blocks read» показывает запросы с наибольшим количеством прочитанных разделяемых блоков, что помогает выявить запросы, наиболее активно читающие данные. Столбцы этой таблицы перечислены в Таблице G.35.

Таблица G.35. Top SQL by shared blocks read (SQL-запросы, прочитавшие максимум разделяемых блоков)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
ReadsКоличество прочитанных разделяемых блоков при выполнении этого планаshared_blks_read
%TotalОтношение количества разделяемых блоков, прочитанных для этого плана, к количеству разделяемых блоков, прочитанных всеми выполненными в кластере запросами 
Hits(%)Отношение числа блоков, полученных из буферов, к общему числу блоков, полученных при выполнении этого плана 
ElapsedОбщее время, затраченное на выполнение плана запроса, в секундахtotal_plan_time + total_exec_time
RowsЧисло строк, полученных или обработанных при выполнении планаrows
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by shared blocks dirtied» показывает запросы с наибольшим количеством загрязнённых разделяемых буферов, что помогает выявить запросы, наиболее активно меняющие данные. Столбцы этой таблицы перечислены в Таблице G.36.

Таблица G.36. Top SQL by shared blocks dirtied (SQL-запросы, «загрязнившие» максимум разделяемых блоков)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
DirtiedКоличество разделяемых блоков, загрязнённых при выполнении этого планаshared_blks_dirtied
%TotalОтношение количества загрязнённых разделяемых буферов для этого плана к количеству разделяемых блоков, загрязнённых всеми запросами, выполненными в кластере 
Hits(%)Отношение числа блоков, полученных из буферов, к общему числу блоков, полученных при выполнении этого плана 
WALОбщий объём WAL (в байтах), сгенерированный при выполнении планаwal_bytes
%TotalОтношение объёма WAL, сгенерированного при выполнении плана, ко всему объёму WAL, сгенерированному в кластере 
ElapsedОбщее время, затраченное на выполнение плана запроса, в секундахtotal_plan_time + total_exec_time
RowsЧисло строк, полученных или обработанных при выполнении планаrows
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by shared blocks written» показывает запросы, записавшие наибольшее количество блоков. Столбцы этой таблицы перечислены в Таблице G.37.

Таблица G.37. Top SQL by shared blocks written (SQL-запросы, записавшие максимум разделяемых блоков)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
WrittenКоличество блоков, записанных при выполнении планаshared_blks_written
%TotalОтношение числа блоков, записанных при выполнении этого плана, к общему числу записанных блоков в кластереОтношение shared_blks_written к pg_stat_bgwriter.buffers_checkpoint+ pg_stat_bgwriter.buffers_clean+ pg_stat_bgwriter.buffers_backend
%BackendWОтношение числа блоков, записанных при выполнении этого плана, к общему числу блоков, записанных обслуживающими процессамиОтношение shared_blks_written к pg_stat_bgwriter.buffers_backend
Hits(%)Отношение числа блоков, полученных из буферов, к общему числу блоков, полученных при выполнении этого плана 
ElapsedОбщее время, затраченное на выполнение плана запроса, в секундахtotal_plan_time + total_exec_time
RowsЧисло строк, полученных или обработанных при выполнении планаrows
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by WAL size» показывает запросы, которые породили наибольший объём записей WAL. Столбцы этой таблицы перечислены в Таблице G.38.

Таблица G.38. Top SQL by WAL size (SQL-запросы, породившие наибольший объём WAL)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
WALОбщий объём WAL (в байтах), сгенерированный при выполнении планаwal_bytes
%TotalОтношение объёма WAL, сгенерированного при выполнении плана, ко всему объёму WAL, сгенерированному в кластере 
WAL buffers fullКоличество случаев переполнения буферов WAL 
DirtiedКоличество разделяемых блоков, загрязнённых при выполнении этого планаshared_blks_dirtied
WAL FPIОбщее число образов полных страниц в WAL, сгенерированных при выполнении планаwal_fpi
WAL recordsОбщее число записей WAL, сгенерированных при выполнении планаwal_records
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by temp usage» показывает запросы с наибольшим объёмом ввода-вывода временных блоков, которое считается как сумма полей temp_blks_read, temp_blks_written, local_blks_read и local_blks_written. Столбцы этой таблицы перечислены в Таблице G.39.

Таблица G.39. Top SQL by temp usage (SQL-запросы с максимальным использованием временных блоков)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Local fetchedЧисло полученных локальных блоковlocal_blks_hit + local_blks_read
Hits(%)Отношение числа локальных блоков, полученных из буферов, к общему числу полученных локальных блоков 
Write Local (blk)Количество блоков, записанных при выполнении этого плана и относящихся к временным таблицамlocal_blks_written
Write Local %TotalОтношение значения local_blks_written этого плана к сумме local_blks_written по всем запросам, выполненным в кластере 
Read Local (blk)Количество блоков, прочитанных при выполнении этого плана и относящихся к временным таблицамlocal_blks_read
Read Local %TotalОтношение значения local_blks_read этого плана к сумме local_blks_written по всем запросам, выполненным в кластере 
Write Temp (blk)Количество временных блоков, записанных при выполнении этого планаtemp_blks_written
Write Temp %TotalОтношение значения temp_blks_written этого плана к сумме temp_blks_written по всем запросам, выполненным в кластере 
Read Temp (blk)Количество временных блоков, прочитанных при выполнении этого планаtemp_blks_read
Read Temp %TotalОтношение значения temp_blks_read этого плана к сумме temp_blks_read по всем запросам, выполненным в кластере 
ElapsedОбщее время, затраченное на выполнение плана запроса, в секундахtotal_plan_time + total_exec_time
RowsЧисло строк, полученных или обработанных при выполнении планаrows
ExecutionsСколько раз выполнялся план запросаcalls
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

Таблица отчёта «Top SQL by invalidation messages sent» показывает операторы, для которых было отправлено наибольшее число событий аннулирования. Столбцы этой таблицы перечислены в Таблице G.40.

Таблица G.40. Top SQL by invalidation messages sent (Операторы с наибольшим числом отправленных событий аннулирования)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N).queryid
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Invalidation messages sentОбщее количество событий аннулирования, которые были отправлены обслуживающими процессами, выполняющими этот оператор. Статистика предоставляется для соответствующих типов сообщений pgpro_stats_inval_msgsПоля столбца pgpro_stats_statements.inval_msgs

G.4.11.4.1. rusage statistics (Статистика использования ресурсов)

Этот раздел добавляется в отчёт, только если в отчётном интервале было доступно расширение pgpro_stats или pg_stat_kcache.

Таблица отчёта «Top SQL by system and user time» показывает запросы с наибольшей суммой значений полей user_time и system_time в представлении pg_stat_kcache или pgpro_stats_totals. Столбцы этой таблицы перечислены в Таблице G.41. Значения времени в ней выражаются в секундах.

Таблица G.41. Top SQL by system and user time (SQL-запросы с наибольшей системной и пользовательской нагрузкой CPU)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
User Time PlanВремя процессора в пользовательском режиме, затраченное на планированиеplan_user_time
User Time ExecВремя процессора в пользовательском режиме, затраченное на выполнениеexec_user_time
User Time %TotalОтношение значения plan_user_time + exec_user_time к общему времени использования процессора в пользовательском режиме всеми запросами 
System Time PlanВремя процессора в режиме ядра, затраченное на планированиеplan_system_time
System Time ExecВремя процессора в режиме ядра, затраченное на выполнениеexec_system_time
System Time %TotalОтношение значения plan_system_time + exec_system_time к общему времени использования процессора в режиме ядра всеми запросами 

Таблица отчёта «Top SQL by reads/writes done by filesystem layer» показывает запросы с наибольшей суммой значений reads и writes представления pg_stat_kcache. Столбцы этой таблицы перечислены в Таблице G.42.

Таблица G.42. Top SQL by reads/writes done by filesystem layer (SQL-запросы, выполнившие максимум операций чтения/записи в файловой системе)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Read Bytes PlanКоличество байт, прочитанное при планированииplan_reads
Read Bytes ExecКоличество байт, прочитанное при выполненииexec_reads
Read Bytes %TotalОтношение значения plan_reads + exec_reads к общему количеству байт, прочитанному на уровне файловой системы всеми запросами 
Write Bytes PlanКоличество байт, записанное при планированииplan_writes
Write Bytes ExecКоличество байт, записанное при выполненииexec_writes
Write Bytes %TotalОтношение значения plan_writes + exec_writes к общему количеству байт, прочитанному на уровне файловой системы всеми запросами 

G.4.11.5. SQL query wait statistics (Статистика ожидания по SQL-запросам)

Если в отчётном интервале было доступно расширение pgpro_stats, в этом разделе отчёта будет содержаться таблица, разделённая на секции, в каждой из которой будут показываться запросы с наибольшем временем ожидания в целом или с наибольшим временем ожидания определённого типа события. Разделы этой таблицы, относящиеся к определённым событиям ожидания, располагаются в порядке уменьшения общего времени ожидания событий данного типа. Столбцы этой таблицы перечислены в Таблице G.43.

Таблица G.43. SQL query wait statistics (Статистика ожидания по SQL-запросам)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
WaitedОбщее время, затраченное на ожидание всех типов событий при выполнении этого плана, в секундах 
%TotalОтношение суммарного времени ожидания при выполнении этого плана к общему времени ожидания для всех запросов в кластере 
DetailsДетализация событий ожидания по типам 

Если расширение, собирающее статистику операторов в отчётном интервале, собрало статистику JIT, в отчёте выводится таблица «Top SQL by JIT elapsed time», где показаны основные операторы по сумме значений полей jit_*_time представления pgpro_stats_statements или pg_stat_statements. Столбцы этой таблицы перечислены в Таблице G.44. Значения времени в ней выражаются в секундах.

Таблица G.44. Top SQL by JIT elapsed time (SQL-запросы с наибольшей длительностью JIT)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
Plan IDХеш-код для идентификации нормализованного плана оператораplanid
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
JIT TimeОбщее время, затраченное на выполнение этого плана оператора с применением JITjit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Generation countОбщее число функций, скомпилированных в JIT-код при выполнении данного оператораСумма значений jit_functions
Generation timeОбщее время, затраченное на компиляцию JIT-кода при выполнении оператораСумма значений jit_generation_time
Inlining countСколько раз встраивались функцииСумма значений jit_inlining_count
Inlining timeОбщее время, затраченное на встраивание функций при выполнении оператораСумма значений jit_inlining_time
Optimization countЧисло JIT-оптимизаций для данного оператораСумма значений jit_optimization_count
Optimization timeОбщее время, затраченное на JIT-оптимизацию при выполнении данного оператораСумма значений jit_optimization_time
Emission countСколько раз выдавался кодСумма значений jit_emission_count
Emission timeОбщее время, затраченное на выдачу кода при выполнении оператораСумма значений jit_emission_time
Deform countЧисло функций преобразования кортежей, скомпилированных в JIT-код при выполнении оператора
Deform timeОбщее время, затраченное оператором на компилирование преобразования кортежей в JIT-код
Plan TimeОбщее время, затраченное на планирование запросаtotal_plan_time
Exec TimeОбщее время, затраченное на выполнение плана запросаtotal_exec_time
Read I/O timeОбщее время, потраченное при выполнении запроса на чтение блоковblk_read_time
Write I/O timeОбщее время, потраченное при выполнении запроса на запись блоковblk_write_time
%CvrОхват: продолжительность сбора статистики по операторам в процентах от продолжительности отчётного интервала

G.4.11.6. Top SQL by parallel workers usage (SQL-запросы с максимальным использованием параллельных рабочих процессов)

Раздел отчёта «Top SQL by parallel workers usage» показывает запросы с наибольшим количеством запланированных и запущенных параллельных рабочих процессов, определяемым как сумма полей parallel_workers_to_launch и parallel_workers_launched представления pg_stat_statements. Некоторые статистические данные доступны, начиная с Postgres Pro 18. Столбцы этой таблицы перечислены в Таблице G.45. Значения времени в ней выражаются в секундах.

Таблица G.45. Top SQL by parallel workers usage (SQL-запросы с максимальным использованием параллельных рабочих процессов)

СтолбецОписаниеПоле/вычисление
Query IDШестнадцатеричное представление queryid. Хеш от идентификатора запроса, идентификатора базы данных и идентификатора пользователя приводится в квадратных скобках. Для вложенных операторов (таких как операторы, вызываемые внутри операторов верхнего уровня) здесь будет отображаться метка (N). 
DatabaseИмя базы данных, в которой выполнялся запросВыводится из dbid
UserИмя пользователя, выполняющего запросВыводится из userid
Parallel workers PlannedЧисло параллельных рабочих процессов, которые планируется запустить
Parallel workers LaunchedЧисло запущенных параллельных рабочих процессов
ExecВремя процессора в режиме ядра, затраченное на выполнениеexec_system_time или system_time
Blks fetchedКоличество считанных блоковshared_blks_hit + shared_blks_read
Shr ReadsОбщее количество разделяемых блоков, прочитанных при выполнении плана операторовshared_blks_read
Loc ReadsОбщее количество локальных блоков, прочитанных при выполнении плана операторовlocal_blks_read
Tmp ReadsОбщее количество временных блоков, прочитанных при выполнении плана операторовtemp_blks_read
Read I/O timeВремя, затраченное на чтение блоковblk_read_time
Write I/O timeВремя, затраченное на запись блоковblk_write_time

G.4.11.7. Complete list of SQL texts (Полный текст SQL-запросов)

Раздел отчёта «Complete list of SQL texts» содержит таблицу с полным текстом и планом запроса для всех SQL-операторов, упомянутых в отчёте. Перейти к тексту соответствующего запроса/плана, можно из любой таблицы со статистикой по ссылке Query ID/Plan ID. Столбцы этой таблицы перечислены в Таблице G.46.

Таблица G.46. Complete list of SQL texts (Полный текст SQL-запросов)

СтолбецОписание
IDШестнадцатеричное представление идентификатора запроса или плана
Query/Plan TextТекст или план запроса

G.4.11.8. Schema object statistics (Статистика по объектам схемы)

Таблицы в этом разделе отчёта показывают наиболее активно используемые объекты базы согласно информации Сборщика статистики в Postgres Pro. Таблицы отчётов, содержащие данные по таблицам и индексам, позволяют просматривать параметры хранения. Щелчок мышью по соответствующей строке показывает параметры хранения непосредственно под строкой.

Таблица отчёта «Top tables by estimated sequentially scanned volume» показывает таблицы с наибольшим приблизительным объёмом, просканированным последовательным образом. Исходя из этого, можно понять, что для каких-то таблиц не хватает индексов. В отсутствие данных о размере, собираемых функцией pg_relation_size(), оценка размера берётся из поля pg_class.relpages. Для обозначения меньшей точности оценки она отображается в квадратных скобках. Данная информация основана на представлении pg_stat_all_tables. Столбцы этой таблицы перечислены в Таблице G.47.

Таблица G.47. Top tables by estimated sequentially scanned volume (Таблицы с наибольшим объёмом последовательно сканированных блоков)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
~SeqBytesПриблизительный объём, прочитанный при последовательном сканированииСумма (pg_relation_size() * seq_scan)
SeqScanЧисло операций последовательного сканирования, выполненных в таблицеseq_scan
IxScanЧисло операций сканирования по индексу, выполненных в этой таблицеidx_scan
IxFetКоличество «живых» строк, отобранных при сканированиях по индексуidx_tup_fetch
InsКоличество вставленных строкn_tup_ins
UpdКоличество изменённых строкn_tup_upd
DelКоличество удалённых строкn_tup_del
Upd(HOT)Количество строк, изменённых по схеме HOTn_tup_hot_upd

В таблице отчёта «Top tables by blocks fetched» полученными блоками считаются блоки, как прочитанные с диска (read), так и найденные в общих буферах (hit). В ней показываются таблицы с максимальным суммарным количеством блоков, полученных из кучи, из индексов, из таблицы TOAST (при наличии) и индекса таблицы TOAST (при наличии). Это помогает понять, какие таблицы активнее других используют блоки данных. Эта информация основана на представлении pg_statio_all_tables. Столбцы этой таблицы перечислены в Таблице G.48.

Таблица G.48. Top tables by blocks fetched (Таблицы, для которых получено максимум блоков)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
Heap BlksЧисло блоков, полученных из кучи таблицыheap_blks_read + heap_blks_hit
Heap Blks %TotalОтношение числа блоков, полученных из кучи таблицы, к общему числу блоков, полученных запросами в кластере 
Ix BlksЧисло блоков, полученных из индексов таблицыidx_blks_read + idx_blks_hit
Ix Blks %TotalОтношение числа блоков, полученных из индексов таблицы, к общему числу блоков, полученных запросами в кластере 
TOAST BlksЧисло блоков, полученных из связанной таблицы TOASTtoast_blks_read + toast_blks_hit
TOAST Blks %TotalОтношение числа блоков, полученных из связанной таблицы TOAST, к общему числу блоков, полученных запросами в кластере 
TOAST-Ix BlksЧисло блоков, полученных из индекса связанной таблицы TOASTtidx_blks_read + tidx_blks_hit
TOAST-Ix Blks %TotalОтношение числа блоков, полученных из индекса связанной таблицы TOAST, к общему числу блоков, полученных запросами в кластере 

В таблице отчёта «Top tables by blocks read» показаны таблицы с максимальным суммарным количество блоков прочитанных из кучи, из индексов, из таблицы TOAST (при наличии) и индекса таблицы TOAST (при наличии). Это помогает понять, какие таблицы активнее других читают блоки данных с диска. Эта информация основана на представлении pg_statio_all_tables. Столбцы этой таблицы перечислены в Таблице G.49.

Таблица G.49. Top tables by blocks read (Таблицы, для которых прочитано максимум блоков)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
Heap BlksЧисло блоков, прочитанных из кучи таблицыheap_blks_read
Heap Blks %TotalОтношение числа блоков, прочитанных из кучи таблицы, к общему числу блоков, прочитанных запросами в кластере 
Ix BlksЧисло блоков, прочитанных из индексов таблицыidx_blks_read
Ix Blks %TotalОтношение числа блоков, прочитанных из индексов таблицы, к общему числу блоков, прочитанных запросами в кластере 
TOAST BlksЧисло блоков, прочитанных из таблицы TOAST, относящейся к даннойtoast_blks_read
TOAST Blks %TotalОтношение числа блоков, прочитанных из связанной таблицы TOAST, к общему числу блоков, прочитанных запросами в кластере 
TOAST-Ix BlksЧисло блоков, прочитанных из индекса таблицы TOAST, относящейся к даннойtidx_blks_read
TOAST-Ix Blks %TotalОтношение числа блоков, прочитанных из индекса связанной таблицы TOAST, к общему числу блоков, прочитанных запросами в кластере 
Hit(%)Отношение числа блоков таблицы, индекса, TOAST-таблицы и индекса TOAST-таблицы, полученных из буферов для данной таблицы, к общему числу блоков, полученных для этой таблицы либо из файловой системы, либо из буферов 

В таблице отчёта «Top DML tables» показаны таблицы с наибольшим числом строк, затронутых операциями DML, то есть с наибольшей суммой значений n_tup_ins, n_tup_upd и n_tup_del (включая таблицы TOAST). Эта информация основана на представлении pg_stat_all_tables. Столбцы этой таблицы перечислены в Таблице G.50.

Таблица G.50. Top DML tables (Таблицы с наибольшим объёмом DML-изменений)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
InsКоличество вставленных строкn_tup_ins
UpdКоличество изменённых строк, включая изменения по схеме HOTn_tup_upd
DelКоличество удалённых строкn_tup_del
Upd(HOT)Количество строк, изменённых по схеме HOTn_tup_hot_upd
SeqScanЧисло операций последовательного сканирования, выполненных в таблицеseq_scan
SeqFetКоличество «живых» строк, прочитанных при последовательных чтенияхseq_tup_read
IxScanКоличество сканирований по индексу, запущенных по этой таблицеidx_scan
IxFetКоличество «живых» строк, отобранных при сканированиях по индексуidx_tup_fetch

В таблице отчёта «Top tables by updated/deleted tuples» показаны таблицы с наибольшим количеством кортежей, затронутых операциями UPDATE/DELETE, то есть с наибольшей суммой значений n_tup_upd и n_tup_del (включая таблицы TOAST). Эта информация основана на представлении pg_stat_all_tables. Столбцы этой таблицы перечислены в Таблице G.51.

Таблица G.51. Top tables by updated/deleted tuples (Таблицы с наибольшим количеством изменённых/удалённых кортежей)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
UpdКоличество изменённых строк, включая изменения по схеме HOTn_tup_upd
Upd(HOT)Количество строк, изменённых по схеме HOTn_tup_hot_upd
DelКоличество удалённых строкn_tup_del
Vacuum countСколько раз очистка этой таблицы была выполнена вручную (VACUUM FULL не учитывается)vacuum_count
Autovacuum countСколько раз очистка этой таблицы была выполнена фоновым процессом автоочисткиautovacuum_count
Analyze countСколько раз сбор статистики для этой таблицы был выполнен вручнуюanalyze_count
AutoAnalyze countСколько раз сбор статистики для этой таблицы был выполнен фоновым процессом автоочисткиautoanalyze_count

Таблица отчёта «Top tables by removed all-visible marks» показывает таблицы с наибольшим количеством меток полной видимости, удалённых обслуживающими процессами из карты видимости. Этот раздел отчёта отображается только при наличии соответствующей статистики. В Таблице G.52 перечислены столбцы этой таблицы отчёта.

Таблица G.52. Top tables by removed all-visible marks (Таблицы с наибольшим количеством удалённых меток полной видимости)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
All-Visible marks clearedОбщее число меток полной видимости, удалённых из карты видимости отношенияrev_all_visible_pages
All-Visible marks setОбщее число меток полной видимости, установленных в карте видимости отношенияpages_all_visible
All-Visible marks %SetОтношение числа установленных меток полной видимости к общему числу установленных и удалённых меток полной видимостиpages_all_visible * 100% / (rev_all_visible_pages + pages_all_visible)
Vacuum countСколько раз очистка этой таблицы была выполнена вручную (VACUUM FULL не учитывается)vacuum_count
Autovacuum countСколько раз очистка этой таблицы была выполнена фоновым процессом автоочисткиautovacuum_count

Таблица отчёта «Top tables by removed all-frozen marks» показывает таблицы с наибольшим количеством меток полной заморозки, удалённых обслуживающими процессами из карты видимости. Этот раздел отчёта отображается только при наличии соответствующей статистики. В Таблице G.53 перечислены столбцы этой таблицы отчёта.

Таблица G.53. Top tables by removed all-visible marks (Таблицы с наибольшим количеством удалённых меток полной заморозки)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
All-Frozen marks clearedОбщее число меток полной заморозки, удалённых из карты видимости отношенияrev_all_frozen_pages
All-Frozen marks setОбщее число меток полной заморозки, установленных в карте видимости отношенияpages_frozen
All-Frozen marks %SetОтношение числа установленных меток полной заморозки к общему числу установленных и удалённых меток полной заморозкиpages_frozen * 100% / (rev_all_frozen_pages + pages_frozen)
Vacuum countСколько раз очистка этой таблицы была выполнена вручную (VACUUM FULL не учитывается)vacuum_count
Autovacuum countСколько раз очистка этой таблицы была выполнена фоновым процессом автоочисткиautovacuum_count

Таблица отчёта «Top tables by new-page updated tuples» (Таблицы с наибольшим количеством изменённых кортежей, попавших на новую страницу) показывает таблицы с наибольшим количеством изменённых строк, новая версия которых переходит на новую страницу кучи, оставляя исходную версию с полем t_ctid, которое указывает на другую страницу кучи. Учитываются только изменения не по схеме HOT. Столбцы этой таблицы перечислены в Таблице G.54.

Таблица G.54. Top tables by new-page updated tuples (Таблицы с наибольшим количеством изменённых кортежей, попавших на новую страницу)

СтолбецОписание
DBИмя базы данных, к которой относится таблица
TablespaceИмя табличного пространства, в котором находится таблица
SchemaИмя схемы, содержащей таблицу
TableИмя таблицы
NP UpdКоличество изменённых строк, попавших на новую страницу кучи
%UpdКоличество изменённых строк, попавших на новую страницу, в процентах от количества всех изменённых строк
UpdКоличество изменённых строк, включая изменения по схеме HOT
Upd(HOT)Количество строк, изменённых по схеме HOT (т. е. без отдельного изменения индекса)

Таблица отчёта «Top growing tables» показывает таблицы, которые увеличились в объёме больше других. Эта информация основана на представлении pg_stat_all_tables. В отсутствие данных о размере, собираемых функцией pg_relation_size(), оценка размера берётся из поля pg_class.relpages. Для обозначения меньшей точности оценки она отображается в квадратных скобках. Столбцы этой таблицы перечислены в Таблице G.55.

Таблица G.55. Top growing tables (Наиболее быстро растущие таблицы)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится таблица 
TablespaceИмя табличного пространства, в котором находится таблица 
SchemaИмя схемы, содержащей таблицу 
TableИмя таблицы 
SizeРазмер таблицы в момент получения последней выборки в отчётном интервалеpg_table_size() - pg_relation_size(toast)
GrowthУвеличение размера таблицы 
InsКоличество вставленных строкn_tup_ins
UpdКоличество изменённых строк, включая изменения по схеме HOTn_tup_upd
DelКоличество удалённых строкn_tup_del
Upd(HOT)Количество строк, изменённых по схеме HOTn_tup_hot_upd

В таблице отчёта «Top indexes by blocks fetched» полученными блоками считаются блоки как прочитанные с диска (read), так и найденные в общих буферах (hit). Эта информация основана на представлении pg_statio_all_indexes. Столбцы этой таблицы перечислены в Таблице G.56.

Таблица G.56. Top indexes by blocks fetched (Индексы, из которых получено максимум блоков)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится индекс 
TablespaceИмя табличного пространства, в котором находится индекс 
SchemaИмя схемы, содержащей нижележащую таблицу 
TableИмя таблицы, для которой создан индекс 
IndexИмя индекса 
ScansКоличество произведённых сканирований по этому индексуidx_scan
BlksЧисло блоков, полученных из индексаidx_blks_read + idx_blks_hit
%TotalОтношение числа блоков, полученных из индекса, к общему числу блоков, полученных запросами в кластере 

Таблица отчёта «Top indexes by blocks read» также основана на представлениях pg_statio_all_indexes и pg_stat_all_indexes. Столбцы этой таблицы перечислены в Таблице G.57.

Таблица G.57. Top indexes by blocks fetched (Индексы, из которых прочитано максимум блоков)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится индекс 
TablespaceИмя табличного пространства, в котором находится индекс 
SchemaИмя схемы, содержащей нижележащую таблицу 
TableИмя таблицы, для которой создан индекс 
IndexИмя индекса 
ScansКоличество произведённых сканирований по этому индексуidx_scan
Blk ReadsКоличество дисковых блоков, прочитанных из этого индексаidx_blks_read
%TotalОтношение числа дисковых блоков, прочитанных из этого индекса, к общему числу блоков, прочитанных с диска запросами в кластере 
Hits(%)Отношение числа блоков индекса, полученных из буферов, к общему числу блоков, полученных для этого индекса 

Таблица отчёта «Top growing indexes» показывает индексы, которые увеличились в объёме больше других. Эта информация основана на представлениях pg_stat_all_tables и pg_stat_all_indexes. В отсутствие данных о размере, собираемых функцией pg_relation_size(), оценка размера берётся из поля pg_class.relpages. Для обозначения меньшей точности оценки она отображается в квадратных скобках. Столбцы этой таблицы перечислены в Таблице G.58.

Таблица G.58. Top growing indexes (Наиболее быстро растущие индексы)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится индекс 
TablespaceИмя табличного пространства, в котором находится индекс 
SchemaИмя схемы, содержащей нижележащую таблицу 
TableИмя таблицы, для которой создан индекс 
IndexИмя индекса 
Index SizeРазмер индекса в момент получения последней выборки в отчётном интервалеpg_relation_size()
Index GrowthПрирост объёма индекса за отчётный интервал 
Table InsКоличество строк, вставленных в нижележащую таблицуn_tup_ins
Table UpdКоличество строк, изменённых в нижележащей таблицеn_tup_upd - n_tup_hot_upd
Table DelКоличество строк, удалённых из нижележащей таблицыn_tup_del

Таблица отчёта «Unused indexes» показывает индексы, в нижележащих таблицах которых за отчётный интервал произведён наибольший объём изменений (требующих поддержания индекса), но при этом сами эти индексы не использовались. Индексы ограничений при этом не учитываются. Эта информация основана на представлении pg_stat_all_tables. Столбцы этой таблицы перечислены в Таблице G.59.

Таблица G.59. Unused indexes (Неиспользуемые индексы)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, к которой относится индекс 
TablespaceИмя табличного пространства, в котором находится индекс 
SchemaИмя схемы, содержащей нижележащую таблицу 
TableИмя таблицы, для которой создан индекс 
IndexИмя индекса 
Index SizeРазмер индекса в момент получения последней выборки в отчётном интервалеpg_relation_size()
Index GrowthПрирост объёма индекса за отчётный интервал 
Table InsКоличество строк, вставленных в нижележащую таблицуn_tup_ins
Table UpdКоличество строк, изменённых в нижележащей таблицеn_tup_upd - n_tup_hot_upd
Table DelКоличество строк, удалённых из нижележащей таблицыn_tup_del

G.4.11.9. User function statistics (Статистика пользовательских функций)

Таблицы в этом разделе отчёта показывают функции, выделяющиеся по разным показателям, получаемым из представления pg_stat_user_functions. Значения времени в этих таблицах выражаются в секундах.

Таблица отчёта «Top functions by total time» показывает функции с наибольшей суммарной длительностью, таблица «Top functions by executions» — функции, выполняемые чаще других, а таблица «Top trigger functions by total time» — триггерные функции с наибольшей суммарной длительностью. Столбцы этих таблиц перечислены в Таблице G.60.

Таблица G.60. User function statistics (Статистика пользовательских функций)

СтолбецОписаниеПоле/вычисление
DBИмя базы данных, содержащей функцию 
SchemaИмя схемы, содержащей функцию 
FunctionИмя функции 
ExecutionsСколько раз вызывалась функцияcalls
Total TimeОбщее время, затраченное на выполнение этой функции и всех других функций, вызванных еюtotal_time
Self TimeОбщее время, затраченное на выполнение собственно функции, без учёта других функций, которые были ею вызваныself_time
Mean TimeСреднее время выполнения функцииtotal_time/calls
Mean self TimeСреднее время выполнения собственно функцииself_time/calls

G.4.11.11. Cluster settings during the report interval (Параметры кластера в отчётном интервале)

Этот раздел отчёта содержит таблицу, в которой показываются значения GUC-параметров Postgres Pro, данные функций version(), pg_postmaster_start_time(), pg_conf_load_time() и поле system_identifier функции pg_control_system(), полученные в отчётном интервале. Данные в этой таблице собраны в две группы — Defined settings (Заданные параметры) и Default settings (Параметры по умолчанию). Столбцы этой таблицы перечислены в Таблице G.75.

Таблица G.75. Cluster settings during the report interval (Параметры кластера в отчётном интервале)

СтолбецОписание
SettingИмя параметра
reset_valПоле reset_val представления pg_settings. Значения, изменявшиеся в отчётном интервале, выделяются полужирным шрифтом.
UnitЕдиница измерения параметра
SourceФайл конфигурации, в котором определён параметр, и номер строки в нём через двоеточие
NotesВремя выборки, в которой было получено данное значение в первый раз

G.4.11.12. Extension versions during the report interval (Версии расширения в отчётном интервале)

Этот раздел отчёта содержит таблицу со списком установленных версий расширения, найденных в базах данных за отчётный интервал. Столбцы First seen и Last seen не отображаются, если версии расширения не изменялись за отчётный интервал. Столбцы этой таблицы перечислены в Таблице G.76.

Таблица G.76. Extension versions during the report interval (Версии расширения в отчётном интервале)

СтолбецОписание
NameНазвание расширения
DBИмя базы данных
First seenВремя выборки, в которой эта версия расширения появилась в первый раз
Last seenВремя выборки, в которой эта версия расширения появилась в последний раз
VersionНазвание версии расширения

G.4.12. Диагностические средства pgpro_pwr

В pgpro_pwr имеются средства для самодиагностики.

G.4.12.1. Сбор детальной статистики о времени выполнения процедур получения выборок

Расширение pgpro_pwr собирает подробную информацию о длительности действий, связанных с получением выборок, когда включён параметр pgpro_pwr.track_sample_timings. Данную информацию вы можете просмотреть в представлении v_sample_timings. Столбцы этого представления перечислены в Таблице G.77.

Таблица G.77. Представление v_sample_timings

СтолбецОписание
server_nameИмя сервера
sample_idИдентификатор выборки
sample_timeВремя получения выборки
sampling_eventЭтап получения выборки. Описания всех этапов приведены в Таблице G.78.
time_spentДлительность данного события

Таблица G.78. Описание событий sampling_event

СобытиеОписание
totalПолучение выборки (все этапы)
connectУстановление подключения к серверу (с использованием dblink)
get server environmentПолучение от сервера GUC-параметров, списка доступных расширений и т. п.
collect database statsПолучение из представления pg_stat_database статистики по базам данных
calculate database statsВычисление изменения статистики по базам данных относительно предыдущей выборки
collect tablespace statsПолучение из представления pg_tablespace статистики по табличным пространствам
collect statement statsСбор статистики по SQL-операторам с использованием расширений pgpro_stats и pg_stat_kcache
collect wait sampling statsСбор статистики по SQL-операторам с использованием расширения pg_wait_sampling
query pg_stat_bgwriterСбор статистики уровня кластера с использованием представления pg_stat_bgwriter
query pg_stat_walСбор статистики WAL на уровне кластера с использованием представления pg_stat_wal
query pg_stat_ioСбор статистики ввода-вывода на уровне кластера с использованием представления pg_stat_io, доступного, начиная с Postgres Pro 16
query pg_stat_slruСбор статистики SLRU-кеша кластера с использованием представления pg_stat_slru
query pg_stat_archiverСбор статистики уровня кластера с использованием представления pg_stat_archiver
collect object statsСбор статистики по объектам базы. Включает события из Таблицы G.79. Включает следующие события:
  • db:имя_бд get extensions version — составление списка версий расширений для базы данных имя_бд

  • db:имя_бд collect tables stats — сбор статистики по таблицам базы имя_бд

  • db:имя_бд collect indexes stats — сбор статистики по индексам базы имя_бд

  • db:имя_бд collect functions stats — сбор статистики по функциям базы имя_бд

  • analyzing collected data — анализ секций с собранной статистикой

processing subsamplesСбор статистики серверных процессов с использованием представления pg_stat_activity
disconnectЗакрытие подключения к серверу (с использованием dblink)
maintain repositoryВыполнение процедур обслуживания
calculate tablespace statsВычисление изменения статистики по табличным пространствам
calculate object statsВычисление изменения статистики по объектам базы. Включает события из Таблицы G.80, а также:
  • merge new extensions version — обработка данных по версиям расширений

  • merge new relation storage parameters — обработка данных по параметрам хранения отношений

calculate cluster statsВычисление изменения статистики на уровне кластера
calculate IO statsВычисление изменения статистики ввода-вывода на уровне кластера
calculate SLRU statsВычисление изменения статистики SLRU-кеша кластера
calculate WAL statsВычисление изменения статистики WAL на уровне кластера
calculate archiver statsВычисление изменения статистики архиватора
delete obsolete samplesУдаление устаревших выборочных линий и выборок

Таблица G.79. Events of Collecting Statistics on Database Objects (События, связанные со сбором статистики по объектам БД)

СобытиеОписание
db:имя_бд collect tables statsСбор статистики по таблицам базы имя_бд
db:имя_бд collect indexes statsСбор статистики по индексам базы имя_бд
db:имя_бд collect functions statsСбор статистики по функциям базы имя_бд

Таблица G.80. Events of Calculating Differences of Statistics on Database Objects (События, связанные с вычислением изменения статистики по объектам БД)

СобытиеОписание
calculate tables statsВычисление изменения статистики по таблицам всех баз данных
calculate indexes statsВычисление изменения статистики по индексам всех баз данных
calculate functions statsВычисление изменения статистики по функциям всех баз данных

G.4.13. Важные замечания

Используя расширение pgpro_pwr, имейте в виду следующее:

  • Postgres Pro собирает статистику о выполнении запроса после того, как он будет выполнен. Если выполнение одного запроса по времени охватывает несколько выборок, связанная с ним статистика попадёт только в ту выборку, ко времени которой он завершится. Кроме того, получить статистику по запросам, выполняемым в текущий момент, нет возможности. Также учтите, что процедуры обслуживания, например очистки и контрольных точек, обновляют статистику только при завершении.

  • В случае сброса статистики Postgres Pro информация в следующей выборке может оказаться неточной.

  • Установленные для отношений исключительные блокировки препятствуют вычислению размера этих отношений. Если функция take_sample() не сможет дождаться снятия такой блокировки в течение короткого периода времени (за 3 секунды), её выполнение прервётся и выборка не будет получена.

G.4. pgpro_pwr — workload reports

The pgpro_pwr module is designed to discover most resource-intensive activities in your database. (PWR, pronounced like "power", is an abbreviation of Postgres Pro Workload Reporting.) This extension is based on Postgres Pro's Statistics Collector views and the pgpro_stats or pg_stat_statements extension.

Note

Although pgpro_pwr can work with the pg_stat_statements extension, it is recommended that you use the pgpro_stats extension since it provides statement plans, wait events sampling and load distribution statistics for databases, roles, client hosts and applications.

Below, use of pgpro_stats is assumed unless otherwise noted.

If you cannot use pgpro_stats for an observed database, but the pg_stat_kcache extension is available, pgpro_pwr can process pg_stat_kcache data, which also provides information about CPU resource usage of statements and filesystem load (rusage).

pgpro_pwr can obtain summary wait statistics from the pg_wait_sampling extension. When pg_wait_sampling is in use, pgpro_pwr will reset the wait sampling profile on every sample.

pgpro_pwr is based on cumulative statistics sampling. Each sample contains statistic increments for most active objects and queries since the time when the previous sample was taken, or more concisely, since the previous sample. This data is later used to generate reports.

pgpro_pwr provides functions to collect samples. Regular sampling allows building a report on the database workload in the past.

pgpro_pwr allows you to take explicit samples during batch processing, load testing, etc.

Any time a sample is taken, pgpro_stats_statements_reset() (see pgpro_stats for the function description) is called to ensure that statement statistics will not be lost when the statements count exceed pgpro_stats.max (see Section G.5.7.1). The report will also contain a section informing you of whether the count of captured statements in any sample reaches 90% of pgpro_stats.max.

pgpro_pwr installed on one Postgres Pro server can also collect statistics from other servers. This feature is useful for gathering workload statistics from hot standbys on the primary server. To benefit from it, make sure that all server names and connection strings are specified and that the pgpro_pwr server can connect to all databases on all servers.

G.4.1. pgpro_pwr Architecture

The extension consists of the following parts:

  • Historical repository is a storage for sampling data. The repository is a set of extension tables.

    Note

    Among the rest, pgpro_pwr tables store query texts, which can contain sensitive information. So, for security reasons, restrict access to the repository as appropriate.

  • Sample management engine comprises functions used to take samples and maintain the repository by removing obsolete sample data.

  • Report engine comprises functions for generating reports based on data from the historical repository.

  • Administrative functions allow you to create and manage servers and baselines.

G.4.2. Prerequisites

The prerequisites assume that pgpro_pwr, which is usually installed in a target cluster, i.e., the cluster that you will mainly track the workload for, the extension can also collect performance data from other clusters.

G.4.2.1. For the pgpro_pwr Database

The pgpro_pwr extension depends on PL/pgSQL and the dblink extension.

G.4.2.2. For the Target Server

The target server must allow connections to all databases from the server where pgpro_pwr is running. To connect to the target server, provide a connection string where a particular database on this server is specified. This database is of high importance for pgpro_pwr since the functionality of the pgpro_stats or pg_stat_statements extensions will be provided through this database. Note, however, that pgpro_pwr will also connect to all the other databases on this server.

Optionally, for completeness of gathered statistics:

  • If statement statistics are needed in reports, pgpro_stats must be installed and configured in the aforementioned database. The following settings may affect the completeness and accuracy of gathered statistics:

    • pgpro_stats.max

      Low setting of this parameter may cause some statement statistics to be wiped out before the sample is taken. A report will warn you if the value of pgpro_stats.max seems undersized.

    • pgpro_stats.track

      Avoid changing the default value of 'top' (note that the value of 'all' will affect the accuracy of %Total fields for statements-related sections of a report).

  • Set the parameters of the Postgres Pro's Statistics Collector as follows:

            track_activities = on
            track_counts = on
            track_io_timing = on
            track_wal_io_timing = on   # Since PostgreSQL 14
            track_functions = all/pl
          

G.4.3. Installation and Setup

pgpro_pwr is provided with Postgres Pro Enterprise as a separate pre-built package pgpro-pwr-ent-15 (for the detailed installation instructions, see Chapter 17).

Note

pgpro_pwr creates a bunch of database objects, so installation in a dedicated schema is recommended.

Although the use of pgpro_pwr with superuser privileges does not have any issues, superuser privileges are not necessary. So you can choose one of the following setup procedures depending on your configuration and security requirements or customize them to meet your needs:

G.4.3.1. Simple Setup

Use this setup procedure when pgpro_pwr is to be installed on the target cluster to only track its workload as superuser.

Create a schema for the pgpro_pwr installation and create the extension:

CREATE SCHEMA profile;
CREATE EXTENSION pgpro_pwr SCHEMA profile;

G.4.3.2. Complex Setup

Use this setup procedure when you intend to use pgpro_pwr for tracking workload on one or more servers and need to follow the principle of least privilege.

G.4.3.2.1. In the Target Server Database

Create a user for pgpro_pwr on the target server:

CREATE USER pwr_collector PASSWORD 'collector_pwd';

Make sure this user has permissions to connect to any database in the target cluster (by default, it is true) and that pg_hba.conf permits such a connection from the pgpro_pwr database host. Also, grant pwr_collector with membership in the pg_read_all_stats role and the EXECUTE privilege on the following functions:

GRANT pg_read_all_stats TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgpro_stats_statements_reset TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgpro_stats_totals_reset(text,bigint) TO pwr_collector;

Also ensure the SELECT privilege on the pgpro_stats_archiver view:

GRANT SELECT ON pgpro_stats_archiver TO pwr_collector;
G.4.3.2.2. In the pgpro_pwr Database

Create an unprivileged user:

CREATE USER pwr_user;

This user will be the owner of the extension schema and will collect samples.

Create a schema for the pgpro_pwr installation:

CREATE SCHEMA profile AUTHORIZATION pwr_user;

Grant the USAGE privilege on the schema where the dblink extension resides:

GRANT USAGE ON SCHEMA public TO pwr_user;

Create the extension using pwr_user account:

\c - pwr_user
CREATE EXTENSION pgpro_pwr SCHEMA profile;

Define the connection parameters of the target server for pgpro_pwr. For example:

SELECT profile.create_server('target_server_name','host=192.168.1.100 dbname=postgres port=5432');

The connection string provided will be used in the dblink_connect() call while executing the take_sample() function.

Note

Connection strings are stored in a pgpro_pwr table in clear-text form. Make sure no other database users can access tables of the pgpro_pwr extension.

G.4.3.3. Setting Up pgpro_pwr Roles

Up to three roles can be distinguished when pgpro_pwr is in operation:

  • The pgpro_pwr owner role is the owner of the pgpro_pwr extension.

  • The collecting role is used by pgpro_pwr to connect to databases and collect statistics.

  • The reporting role is used to generate reports.

If all the actions with pgpro_pwr are performed by the superuser role postgres, you can skip most of the setup explained below.

G.4.3.3.1. The pgpro_pwr Owner

This role can be used to perform all actions related to pgpro_pwr. This role will have access to server connection strings, which may contain passwords. You should use this role to call the take_sample() function. The dblink extension is needed for this user.

Consider an example assuming each extension in its own schema:

\c postgres postgres
CREATE SCHEMA dblink;
CREATE EXTENSION dblink SCHEMA dblink;
CREATE USER pwr_usr with password 'pwr_pwd';
GRANT USAGE ON SCHEMA dblink TO pwr_usr;
CREATE SCHEMA profile AUTHORIZATION pwr_usr;
\c postgres pwr_usr
CREATE EXTENSION pgpro_pwr SCHEMA profile;

G.4.3.3.2. The Collecting Role

This role should be used by pgpro_pwr to connect to databases and collect statistics. Unprivileged users cannot open connections using dblink without a password, so you need to provide the password in the connection string for each server. This role should have access to all supported statistics extensions. It should also be able to perform a reset of statistics extensions.

Consider an example. If you use pgpro_stats to collect statistics, set up the collecting role as follows:

\c postgres postgres
CREATE SCHEMA pgps;
CREATE EXTENSION pgpro_stats SCHEMA pgps;
CREATE USER pwr_collector with password 'collector_pwd';
GRANT pg_read_all_stats TO pwr_collector;
GRANT USAGE ON SCHEMA pgps TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgps.pgpro_stats_statements_reset TO pwr_collector;

If you use pg_stat_statements to collect statistics, set up the collecting role as follows:

\c postgres postgres
CREATE SCHEMA pgss;
CREATE SCHEMA pgsk;
CREATE SCHEMA pgws;
CREATE EXTENSION pg_stat_statements SCHEMA pgss;
CREATE EXTENSION pg_stat_kcache SCHEMA pgsk;
CREATE EXTENSION pg_wait_sampling SCHEMA pgws;
CREATE USER pwr_collector with password 'collector_pwd';
GRANT pg_read_all_stats TO pwr_collector;
GRANT USAGE ON SCHEMA pgss TO pwr_collector;
GRANT USAGE ON SCHEMA pgsk TO pwr_collector;
GRANT USAGE ON SCHEMA pgws TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgss.pg_stat_statements_reset TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgsk.pg_stat_kcache_reset TO pwr_collector;
GRANT EXECUTE ON FUNCTION pgws.pg_wait_sampling_reset_profile TO pwr_collector;

Now you should set up a connection string pointing to the database with statistics extensions installed:

 \c postgres pwr_usr
 SELECT profile.set_server_connstr('local','dbname=postgres port=5432 host=localhost user=pwr_collector password=collector_pwd');

Password authentication must be configured in the pg_hba.conf file for the pwr_collector user.

Obviously, the collecting role should be properly configured on all servers observed by pgpro_pwr.

Now you should be able to call take_sample() using the pwr_usr role:

\c postgres pwr_usr
SELECT * FROM take_sample();

And now it's time to configure the scheduler (in our example, the crontab command of the postgres user):

*/30 * * * *   psql -U pwr_usr -d postgres -c 'SELECT profile.take_sample()' > /dev/null 2>&1

Note that you can use the Postgres Pro password file to store passwords.

G.4.3.3.3. The Reporting Role

Any user can build a pgpro_pwr report. The minimal privileges needed to generate pgpro_pwr reports are granted to the public role. However a full report, with query texts, is only available to the member of the pg_read_all_stats role. Anyway, the reporting role cannot access server connection strings, so it cannot get the passwords of servers.

G.4.3.4. Setting Extension Parameters

In postgresql.conf, you can define the following pgpro_pwr parameters:

pgpro_pwr.max (integer)

Number of top objects (statements, relations, etc.) to be reported in each sorted report table. This parameter affects the size of a sample: the more objects you want to appear in your report, the more objects we need to keep in a sample. The maximum value is 100. Any larger value is lowered to 100.

The default value is 20.

pgpro_pwr.max_sample_age (integer)

Retention time of the sample, in days. Samples aged pgpro_pwr.max_sample_age days and older are automatically deleted on the next take_sample() call.

The default value is 7 days.

pgpro_pwr.max_query_length (integer)

Maximum query length allowed in reports. All queries in a report will be truncated to pgpro_pwr.max_query_length characters.

The default value is 20 000 characters.

pgpro_pwr.track_sample_timings (boolean)

Enables collecting detailed timing statistics of pgpro_pwr's own sampling procedures. Set this parameter to diagnose why sampling functions run slowly. Collected timing statistics will be available in the v_sample_timings view.

The default value is off.

pgpro_pwr.statements_reset (boolean)

Controls the pgpro_stats/pg_stat_statements statistics reset during taking a sample. Allows you not to reset the statistics during taking a sample due to new techniques employed. When disabled, pgpro_pwr will track statement evictions using the value of the calls field. However this method does not completly prevent statistics loss. pg_stat_statements v1.11 and pgpro_stats v1.8 contain time tracking abilities that can reduce the possible data loss. When this setting is disabled, you can temporarily enable it in a session if you want to sometimes perform a reset of pgpro_stats/pg_stat_statements.

The default value is on.

pgpro_pwr.relsize_collect_mode (text)

Defines the mode of collecting relation sizes. Possible values:

  • off — collection of relation sizes is based on pg_class. Although the relation sizes collected this way are rough, their collection consumes almost no resources.

  • on — accurate relation sizes are collected for each sample using the pg_relation_size() function, which requires a lock on the table and is pretty resource intensive.

  • schedule — accurate relation sizes are collected in the size-collection window, defined for each server.

The default value is off.

G.4.4. Managing Servers

Once installed, pgpro_pwr creates one enabled local server for the current cluster. If a server is enabled, pgpro_pwr includes it in sampling when no server is explicitly specified (see take_sample() for details). A server that is not enabled is referred to as disabled.

The default connection string for a local node contains only dbname and port parameters. The values of these parameters are taken from the connection used to create the extension. You can change the server connection string using the set_server_connstr() function when needed.

G.4.4.1. Server Management Functions

Use the following pgpro_pwr functions for server management:

create_server(server name, connstr text, enabled boolean DEFAULT TRUE, max_sample_age integer DEFAULT NULL description text DEFAULT NULL)

Creates a server definition.

Arguments:

  • server — server name. Must be unique.

  • connstr — connection string. Must contain all the necessary settings to connect from pgpro_pwr server to the target server database.

  • enabled — set to include the server in sampling by the take_sample() function without arguments.

  • max_sample_age — retention time of the sample. Overrides the global pgpro_pwr.max_sample_age setting for this server.

  • description — server description text, to be included in reports.

Here is an example of how to create a server definition:

SELECT profile.create_server('omega','host=192.168.1.100 dbname=postgres port=5432');

drop_server(server name)

Drops a server and all its samples.

set_server_description(server name description text)

Sets a new server description.

set_server_subsampling(server name, subsample_enabled boolean, min_query_duration interval, min_xact_duration interval, min_xact_age integer, min_idle_xact_dur interval hour to second)

Defines subsample settings for a server.

Arguments:

  • server — server name.

  • subsample_enabled — defines whether subsampling is enabled for the server, that is, whether take_subsample() function should actually take a subsample.

  • min_query_duration — the query duration threshold.

  • min_xact_duration — the transaction duration threshold.

  • min_xact_age — the transaction age threshold.

  • min_idle_xact_dur_age — the idle transaction threshold.

enable_server(server name)

Includes a server in sampling by the take_sample() function without arguments.

disable_server(server name)

Excludes a server from sampling by the take_sample() function without arguments.

rename_server(server name, new_name name)

Renames a server.

set_server_max_sample_age(server name, max_sample_age integer)

Sets the retention period for a server (in days). To reset the server retention, set the value of max_sample_age to NULL.

set_server_db_exclude(server name, exclude_db name[])

Excludes a list of databases on a server from sampling. Use when pgpro_pwr is unable to connect to some databases in a cluster (for example, in Amazon RDS instances).

set_server_connstr(server name, server_connstr text)

Sets the connection string for a server.

set_server_setting(server name, setting text, value jsonb)

Fine-tunes settings of the server statistics collection. collect* settings control which statistics should be collected, and value for these settings accepts bollean values, with the default equal to true. Available settings:

  • collect_pg_stat_statement — collect statement statistics using pg_stat_statements and pg_stat_kcache extensions.

  • collect_pg_wait_sampling — collect wait event statistics using the pg_wait_sampling extension.

  • collect_objects — collect all the schema object statistics, that is, tables, indexes, and functions, from pg_stat_* views.

  • collect_relations — collect statistics on tables and indexes from pg_stat_* views.

  • collect_functions — collect statistics on user functions from the pg_stat_user_functions view.

  • collect_vacuum_stats — collect the extended vacuum statistics.

show_server_settings(server name)

Returns the statistics collection settings for the specified server.

show_servers()

Displays the list of configured servers.

G.4.5. Managing Samples

A sample contains the database workload statistics since the previous sample

G.4.5.1. Sampling Functions

The following pgpro_pwr functions relate to sampling:

take_sample()
take_sample(server name [, skip_sizes boolean])

Takes samples.

If the parameter is omitted, the function takes a sample on each enabled server. Servers are accessed for sampling sequentially, one by one. The function returns a table with the following columns:

  • server — server name.

  • result — result of taking the sample. Can be OK if the sample was taken successfully or contain the error trace text in case of exception.

  • elapsed — time elapsed while the sample was taken.

If called with the parameter, the function takes a sample on the specified server even if this server is disabled. Use when you need different sampling frequencies on specific servers. Returns 0 on success.

Arguments:

  • server — server name.

  • skip_sizes — if omitted or set to null, the size-collection policy applies; if false, relation sizes are collected; if true, the collection of relation sizes is skipped.

take_sample_subset([sets_cnt integer, current_set integer])

Takes a sample on each server in a subset of servers. Use to take samples on servers in parallel if you have many enabled servers. Although PL/pgSQL does not support parallel execution, you can call this function in parallel sessions. This function returns the same type as take_sample(). If both parameters are omitted, the function behaves like the take_sample() function, i.e., it takes a sample on all enabled servers one by one.

Arguments:

  • sets_cnt — number of subsets to divide all enabled servers into.

  • current_set — number of the subset to collect samples for. Takes values from 0 through sets_cnt - 1. For the specified subset, samples are collected as usual, server by server.

If a reset of statistics since the previous sample was detected, pgpro_pwr treats corresponding absolute values as differentials; however, the accuracy will be affected anyway.

show_samples([server name,] [days integer])

Returns a table with information on server samples (local server is assumed if server is omitted) for the last days days (all existing samples are assumed if omitted). This table has the following columns:

  • sample — sample identifier.

  • sample_time — time when this sample was taken.

  • dbstats_resetNULL or the statistics reset timestamp of the pg_stat_database view if the statistics were reset since the previous sample.

  • clustats_resetNULL or the statistics reset timestamp of the pg_stat_bgwriter view if the statistics were reset since the previous sample.

  • archstats_resetNULL or the statistics reset timestamp of the pg_stat_archiver view if the statistics were reset since the previous sample.

Sampling functions also maintain the server repository by deleting obsolete samples and baselines according to the retention policy.

G.4.5.2. Taking Samples

To take samples for all enabled servers, call the take_sample() function. Usually, one or two samples per hour is sufficient. You can use a cron-like tool to schedule sampling. Here is an example for a 30-minute sampling period:

*/30 * * * *   psql -c 'SELECT profile.take_sample()' &> /dev/null

However, the results of such a call are not checked for errors. In a production environment, function results can be used for monitoring. This function returns OK for all servers with successfully taken samples and shows error text for failed servers:

SELECT * FROM take_sample();
  server   |                                   result                                    |   elapsed
-----------+-----------------------------------------------------------------------------+-------------
 ok_node   | OK                                                                          | 00:00:00.48
 fail_node | could not establish connection                                             +| 00:00:00
           | SQL statement "SELECT dblink_connect('server_connection',server_connstr)"  +|
           | PL/pgSQL function take_sample(integer) line 69 at PERFORM                  +|
           | PL/pgSQL function take_sample_subset(integer,integer) line 27 at assignment+|
           | SQL function "take_sample" statement 1                                     +|
           | FATAL:  database "postgresno" does not exist                                |
(2 rows)

G.4.5.3. Sample Retention Policy

You can define sample retention at the following levels:

  1. Global

    The value of the pgpro_pwr.max_sample_age parameter in the postgresql.conf file defines a common retention setting, which is effective if none of other related settings are defined.

  2. Server

    Specifying the max_sample_age parameter while creating a server or calling the set_server_max_sample_age(server,max_sample_age) function for an existing server defines the retention for the server. A server retention setting overrides pgpro_pwr.max_sample_age for a specific server.

  3. Baseline

    A baseline created overrides all the other retention periods for included samples.

G.4.6. Managing the Collection of Relation Sizes

It may take considerable time to collect sizes of all relations in a database by Postgres Pro relation-size functions. Besides, those functions require AccessExclusiveLock on a relation. However, it may be sufficient for you to collect relation sizes on a daily basis. pgpro_pwr allows you to skip collecting relation sizes by defining the size-collection policy for servers. The policy defines:

  • A daily window when the collection of relation sizes is permitted.

  • A minimum gap between two samples with relation sizes collected.

When the size-collection policy is defined, sampling functions collect relation sizes only when the sample is taken in the defined window and the previous sample with sizes is older than the gap. The following function defines this policy:

set_server_size_sampling(server name, window_start time with time zone DEFAULT NULL, window_duration interval hour to second DEFAULT NULL, sample_interval interval day to minute DEFAULT NULL, collect_mode text DEFAULT NULL)

Defines the size-collection policy for a server.

Arguments:

  • server — server name.

  • window_start — start time of the size-collection window.

  • window_duration — duration of the size-collection window.

  • sample_interval — minimum time gap between two samples with relation sizes collected.

  • collect_mode — when set to off, which is the default for new installations, relation sizes are collected from pg_class, when set to on, relation sizes are collected using the pg_relation_size() function, when set to schedule, pgpro_pwr collects the relation size in the size-collection window. This parameter overrides the relsize_collect_mode extension parameter. Upgrading from a previous version sets the value of this parameter to on or schedule, so the previous behavior does not change.

Note

When you build a report between samples either of which lacks relation-size data, relation-growth sections will be based on pg_class.relpages data. However, you can expand the report interval bounds to the nearest samples with relation sizes collected using the with_growth parameter of report generation functions; this makes the growth data more accurate.

Relation sizes are needed to calculate sequentially scanned volume for tables and explicit vacuum load for indexes.

Example:

SELECT set_server_size_sampling('local','23:00+03',interval '2 hour',interval '8 hour', 'schedule');

The show_servers_size_sampling function shows size collection policies for all servers:

postgres=# SELECT * FROM show_servers_size_sampling();
 server_name | window_start | window_end  | window_duration | sample_interval | limited_collection
-------------+--------------+-------------+-----------------+-----------------+--------------------
 local       | 23:00:00+03  | 01:00:00+03 | 02:00:00        | 08:00:00        | t

G.4.7. Managing Subsamples

Some performance-related data available in Postgres Pro is not cumulative. For example, the most often used data about session states is available through the pg_stat_activity view and can only be obtained with frequent samples. However, the take_sample() function is heavy and can take considerable amount of time. So it is not suitable for collecting session state data.

The subsample feature provides a new fast take_subsample() function. It can be used to collect relatively fast changing data. Every subsample is bound to the next regular sample and is deleted by the retention policy together with it.

The subsample feature can be used to capture the most interesting session states:

  • Long running queries

  • Long transactions

  • Aged transactions, that is, those that hold a snapshot behind a lot of other transactions

  • Transactions being in an idle state for a long time

G.4.7.1. Subsampling Functions

The following pgpro_pwr functions relate to subsampling:

take_subsample()
take_subsample(server name)

If the parameter is omitted, the function takes a subsample on each enabled server with subsampling enabled (see set_server_subsampling for details). Server subsamples are taken sequentially, one by one. The function returns a table with the following columns:

  • server — server name.

  • result — result of taking the subsample. Can be OK if the subsample was taken successfully or contain the error text in case of exception.

  • elapsed — time elapsed while the subsample was taken.

This tabular return format makes it easy to control subsample creation using an SQL query.

If called with the parameter, the function takes a subsample for the specified server. Use when you need different subsampling frequencies on servers or if you want to take an explicit subsample on a specific server.

Arguments:

  • server — server name.

Note

Trying to take a subsample during taking a sample fails.

take_subsample_subset([sets_cnt integer], [current_set integer])

Takes subsamples for a subset of enabled servers with subsampling enabled. Although subsamples should be fast enough for serial processing, subsamples can be taken in parallel, like regular samples. This function returns the same type as take_subsample(). If both parameters are omitted, the function behaves like the take_subsample() function.

Arguments:

  • sets_cnt — number of server subsets.

  • current_set — the subset to process. Takes values from 0 through sets_cnt - 1. For the specified subset, subsamples are collected as usual, server by server.

G.4.7.2. Configuring the Subsample Feature

The following settings affect the subsample behaviour:

  • pgpro_pwr.subsample_enabled — defines whether the take_subsample() function should actually take a subsample.

  • pgpro_pwr.min_query_duration — the long running query threshold.

  • pgpro_pwr.min_xact_duration — the long transaction threshold.

  • pgpro_pwr.min_xact_age — the transaction age threshold.

  • pgpro_pwr.min_idle_xact_dur_age — the idle transaction threshold.

The subsample behavior can be defined at the server level using the set_server_subsampling function.

The last observed session state is saved in the repository when either of the following threshold-related events happens:

  • During query execution, the difference between now() and the query_start exceeds the pgpro_pwr.min_query_duration threshold.

  • During a transaction, the difference between now() and the xact_start exceeds the pgpro_pwr.min_xact_duration threshold.

  • During a transaction, the age(backend_xmin) exceeds the pgpro_pwr.min_xact_age threshold.

  • During a transaction in a state idle in transaction or idle in transaction (aborted), the difference between now() and the state_change exceeds the pgpro_pwr.min_idle_xact_duration threshold.

See Chapter 27 for details of the mentioned fields. Every subsample can hold at most pgpro_pwr.max entries for every threshold type.

G.4.7.3. Scheduling Subsamples

Subsamples are fast enough to take them quite often. However usually you do not need more than 2-4 subsamples per minute. Obviously the subsample frequency depends on the shortest used duration of a threshold setting.

Cron only allows one call per minute, so some effort is needed to schedule more frequent subsamples. For example, the \watch psql command can be used:

echo "select take_subsample(); \watch 15" | psql &> /dev/null

The psql call can be wrapped in the systemd service like this:

Description=pgpro_pwr subsampling unit
[Unit]

[Service]
Type=simple
ExecStart=/bin/sh -c 'echo "select take_subsample(); \\watch 15" | /path/to/psql -qo /dev/null'
User=postgres
Group=postgres

[Install]
WantedBy=multi-user.target

G.4.8. Managing Baselines

A baseline is a named sequence of samples that has its own retention setting. A baseline can be used as a sample interval in report generation functions. An undefined baseline retention means infinite retention. Use baselines to save information about the database workload for a certain time interval.

G.4.8.1. Baseline Management Functions

Use the following pgpro_pwr functions for baseline management:

create_baseline([server name,] baseline varchar(25), start_id integer, end_id integer [, days integer])
create_baseline([server name,] baseline varchar(25), time_range tstzrange [, days integer])

Creates a baseline.

Arguments:

  • server — server name. local sever is assumed if omitted.

  • baseline — baseline name. Must be unique for a server.

  • start_id — identifier of the first sample in the baseline.

  • end_id — identifier of the last sample in the baseline.

  • time_range — time interval for the baseline. The baseline will include all samples for the minimal interval that covers time_range.

  • days — baseline retention time, defined in integer days since now(). Omit or set to null for infinite retention.

drop_baseline([server name,] baseline varchar(25))

Drops a baseline. For the meaning and usage details of function arguments, see create_baseline. Dropping a baseline does not mean dropping all its samples immediately. The baseline retention just no longer applies to them.

keep_baseline([server name,] baseline varchar(25) [, days integer])

Changes the retention of a baseline. For the meaning and usage details of function arguments, see create_baseline. Omit the baseline parameter or pass null to it to change the retention of all existing baselines.

show_baselines([server name])

Displays existing baselines. Call show_baselines to get information about the baselines, such as names, sampling intervals and retention periods. local sever is assumed if the server parameter is omitted.

G.4.9. Data Export and Import

Collected samples can be exported from one instance of the pgpro_pwr extension and then loaded into another one. This feature helps you to move server data from one instance to another or to send collected data to your support team.

G.4.9.1. Data Export

The export_data function exports data to a regular table. You can use any method available to export this table from your database. For example, you can use the \copy meta-command of psql to obtain a single csv file:

postgres=# \copy (select * from export_data()) to 'export.csv'

G.4.9.2. Data Import

Since data can only be imported from a local table, first, load the data you exported. Using the \copy meta-command again:

postgres=# CREATE TABLE import (section_id bigint, row_data json);
CREATE TABLE
postgres=# \copy import from 'export.csv'
COPY 6437

Now you can import the data by providing the import table to the import_data function:

postgres=# SELECT * FROM import_data('import');

After successful import, you can drop the import table.

Note

If server data is imported for the first time, your local pgpro_pwr servers with matching names will cause a conflict during import. To avoid this, you can temporarily rename such servers or you can specify the server name prefix for import operations. However, during import of new data for already imported servers, they are matched by system identifiers, so feel free to rename imported severs. Also keep in mind that pgpro_pwr sets servers being imported to the disabled state for take_sample() to bypass them.

G.4.9.3. Export and Import Functions

Use these functions to export or import data:

export_data([server name, [min_sample_id integer,] [max_sample_id integer,]] [, obfuscate_queries boolean] [, hide_connstr boolean])

Exports collected data.

Arguments:

  • server — server name. All configured servers are assumed if omitted.

  • min_sample_id, max_sample_id — sample identifiers to bound the export (inclusive). If min_sample_id is omitted or set to null, all samples until max_sample_id sample are exported; if max_sample_id is omitted or set to null, all samples since min_sample_id sample are exported.

  • obfuscate_queries — exports query texts as MD5 hash and excludes server connection strings from export. Pass this argument only when you want to hide query texts.

  • hide_connstr — excludes server connection strings from export.

import_data(data regclass [, server_name_prefix text])

Imports previously exported data. Returns the number of actually loaded rows in pgpro_pwr tables.

Arguments:

  • data is the name of the table containing import data.

  • server_name_prefix specifies the server name prefix for the import operation. It can be used to avoid name conflicts.

G.4.10. Report Generation Functions

pgpro_pwr reports are generated in HTML format by reporting functions. The following types of reports are available:

  • Regular reports provide statistics on the workload for an interval.

  • Differential reports provide statistics on the same objects for two intervals. Corresponding values are located next to each other, which makes it easy to compare the workloads.

Reporting functions take sample identifiers, baselines or time ranges to determine the intervals. For time ranges, these are the minimal intervals that cover the ranges.

G.4.10.1. Regular Reports

Use these functions to generate regular reports:

get_report([server name,] start_id integer, end_id integer [, description text [, with_growth boolean [, db_exclude name[]]]])
get_report([server name,] time_range tstzrange [, description text [, with_growth boolean [, db_exclude name[]]]])
get_report([server name,] baseline varchar(25) [, description text [, with_growth boolean [, db_exclude name[]]]])

Generates a regular report defined by the arguments.

Arguments:

  • server — server name. local sever is assumed if omitted.

  • start_id — identifier of the interval starting sample.

  • end_id — identifier of the interval ending sample.

  • baseline — baseline name.

  • time_range — time range.

  • description — short text to be included in the report as its description.

  • with_growth — flag requesting interval expansion to the nearest bounds with data on relation growth available. The default value is false.

  • db_exclude — the database exclusion list. Lists databases to be excluded from all report tables having the Database column. Use to hide some databases in the report.

get_report_latest([server name,])
get_report_latest([server name [, db_exclude name[]]])

Generates a regular report for two latest samples.

Arguments:

  • server — server name. local sever is assumed if omitted.

  • db_exclude — the database exclusion list. Lists databases to be excluded from all report tables having the Database column. Use to hide some databases in the report.

G.4.10.2. Differential Reports

Use this function to generate differential reports:

get_diffreport([server name,] start1_id integer, end1_id integer, start2_id integer, end2_id integer [, description text [, with_growth boolean [, db_exclude name[]]]])
get_diffreport([server name,] time_range1 tstzrange, time_range2 tstzrange [, description text [, with_growth boolean [, db_exclude name[]]]])
get_diffreport([server name,] baseline1 varchar(25), baseline2 varchar(25) [, description text [, with_growth boolean [, db_exclude name[]]]])
get_diffreport([server name,] baseline1 varchar(25), time_range2 tstzrange [, description text [, with_growth boolean[, db_exclude name[]]]])
get_diffreport([server name,] time_range1 tstzrange, baseline2 varchar(25) [, description text [, with_growth boolean[, db_exclude name[]]]])
get_diffreport([server name,] start1_id integer, end1_id integer, baseline2 varchar(25) [, description text [, with_growth boolean[, db_exclude name[]]]])
get_diffreport([server name,] baseline1 varchar(25), start2_id integer, end2_id integer [, description text [, with_growth boolean[, db_exclude name[]]]])

Generates a differential report for two intervals. The combinations of arguments provide possible ways to specify the two intervals.

Arguments:

  • server — server name. local sever is assumed if omitted.

  • start1_id, end1_id — identifiers of the starting and ending samples for the first interval.

  • start2_id, end2_id — identifiers of the starting and ending samples for the second interval.

  • baseline1 — baseline name for the first interval.

  • baseline2 — baseline name for the second interval.

  • time_range1 — time range for the first interval.

  • time_range2 — time range for the second interval.

  • description — short text to be included in the report as its description.

  • with_growth — flag requesting interval expansion to the nearest bounds with data on relation growth available. The default value is false.

  • db_exclude — the database exclusion list. Lists databases to be excluded from all report tables having the Database column. Use to hide some databases in the report.

G.4.10.3. Report Generation Example

Generate a report for the local server and interval defined by samples:

psql -Aqtc "SELECT profile.get_report(480,482)" -o report_480_482.html

For any other server, provide its name:

psql -Aqtc "SELECT profile.get_report('omega',12,14)" -o report_omega_12_14.html

Generate a report using time ranges:

psql -Aqtc "SELECT profile.get_report(tstzrange('2020-05-13 11:51:35+03','2020-05-13 11:52:18+03'))" -o report_range.html

Generate a relative time-range report:

psql -Aqtc "SELECT profile.get_report(tstzrange(now() - interval '1 day',now()))" -o report_last_day.html

G.4.11. pgpro_pwr Report Sections

Each pgpro_pwr report is divided into sections, described below. The number of top objects reported in each sorted report table is specified by the pgpro_pwr.max parameter.

Almost every item in the report can be accentuated by a single mouse click. The accentuated item will be instantly highlighted in all report sections, making it easy to find. The attributes identifying the item will appear in the bottom-right corner of the page. For example, if you click on a database name in the Database statistics report table, you can notice a small table with the database attributes in the bottom-right corner of the page.

When you scroll down the report, its table of contents will be available on the right side of the page. It can be hidden with a single mouse click on the content tag.

A substring-based filter is also available that helps limit the report contents to particular objects based on a substring. Specifically, substring-based filtering is applied to query texts.

G.4.11.1. Server statistics

Tables in this section of a pgpro_pwr report are described below.

The report table Database statistics provides per-database statistics for the report interval. The statistics are based on the pg_stat_database view. Table G.8 lists columns of this report table.

Table G.8. Database statistics

ColumnDescriptionField/Calculation
Database Database name datname
Commits Number of committed transactions xact_commit
Rollbacks Number of rolled back transactions xact_rollback
Deadlocks Number of deadlocks detected deadlocks
Checksum Failures Number of data page checksum failures detected in this database. This field is only shown if any checksum failures were detected in this database during the report interval. checksum_failures
Checksums Last Time at which the last data page checksum failure was detected in this database. This field is only shown if any checksum failures were detected in this database during the report interval. checksum_last_failure
Hit% Buffer cache hit ratio, i.e., percentage of pages fetched from buffers in all pages fetched  
Read Number of disk blocks read in this database blks_read
Hit Number of times disk blocks were found already in the buffer cache blks_hit
Ret Number of returned tuples tup_returned
Fet Number of fetched tuples tup_fetched
Ins Number of inserted tuples tup_inserted
Upd Number of updated tuples tup_updated
Del Number of deleted tuples tup_deleted
Parallel workers Planned Number of parallel workers planned to be launched by queries on this database
Parallel workers Launched Number of parallel workers launched by queries on this database
Temp Size Total amount of data written to temporary files by queries in this database temp_bytes
Temp Files Number of temporary files created by queries in this database temp_files
Size Database size at the time of the last sample in the report interval pg_database_size()
GrowthDatabase growth during the report intervalpg_database_size() increment between interval bounds

The report table Cluster I/O statistics provides I/O statistics by object types, backend types and contexts. This table is based on the pg_stat_io view of the Cumulative Statistics System, available since Postgres Pro 16. Table G.9 lists columns of this report table. Times are provided in seconds.

Table G.9. Cluster I/O statistics

ColumnDescription
Object Target object of an I/O operation
Backend Type of the backend that performed an I/O operation
Context The context of an I/O operation
Reads Count Number of read operations
Reads Bytes Amount of data read
Reads Time Time spent in read operations
Writes Count Number of write operations
Writes Bytes Amount of data written
Writes Time Time spent in write operations
Writebacks Count Number of blocks which the process requested the kernel write out to permanent storage
Writebacks Bytes Amount of data requested for write out to permanent storage
Writebacks Time Time spent in writeback operations, including the time spent queueing write-out requests and, potentially, the time spent to write out the dirty data
Extends Count Number of relation extend operations
Extends Bytes Amount of space used by extend operations
Extends Time Time spent in extend operations
Hits The number of times a desired block was found in a shared buffer
Evictions Number of times a block has been written out from a shared or local buffer in order to make it available for another use
Reuses The number of times an existing buffer in a size-limited ring buffer outside of shared buffers was reused as part of an I/O operation in the bulkread, bulkwrite, or vacuum contexts
Fsyncs Count Number of fsync calls. These are only tracked in context normal.
Fsyncs Time Time spent in fsync operations

The report table Cluster SLRU statistics provides access statistics on SLRU (simple least-recently-used) caches. This table is based on the pg_stat_slru view of the Cumulative Statistics System. Table G.10 lists columns of this report table. Times are provided in seconds.

Table G.10. Cluster SLRU statistics

ColumnDescriptionField/Calculation
Name Name of the SLRU name
Zeroed Number of blocks zeroed during initializations blks_zeroed
Hits Number of times disk blocks were found already in the SLRU, so that a read was not necessary (this only includes hits in the SLRU, not the operating system's file system cache) blks_hit
Reads Number of disk blocks read for this SLRU blks_read
%Hit Number of disk block hits for this SLRU as the percentage of Reads + Hitsblks_hit*100/blks_read + blks_hit
Writes Number of disk blocks written for this SLRU blks_written
Checked Number of blocks checked for existence for this SLRU blks_exists
Flushes Number of flushes of dirty data for this SLRU flushes
Truncates Number of truncates for this SLRU truncates

Table Session statistics by database is available in the report for Postgres Pro databases starting with version 14. This table is based on the pg_stat_database view of the Statistics Collector. Table G.11 lists columns of this report table. Times are provided in seconds.

Table G.11. Session statistics by database

ColumnDescriptionField/Calculation
Database Database name  
Timings Total Time spent by database sessions in this database during the report interval (note that statistics are only updated when the state of a session changes, so if sessions have been idle for a long time, this idle time won't be included) session_time
Timings Active Time spent executing SQL statements in this database during the report interval (this corresponds to the states active and fastpath function call in pg_stat_activity) active_time
Timings Idle Time spent idling while in a transaction in this database during the report interval (this corresponds to the states idle in transaction and idle in transaction (aborted) in pg_stat_activity) idle_in_transaction_time
Sessions Established Total number of sessions established to this database during the report interval sessions
Sessions Abandoned Number of database sessions to this database that were terminated because connection to the client was lost during the report interval sessions_abandoned
Sessions Fatal Number of database sessions to this database that were terminated by fatal errors during the report interval sessions_fatal
Sessions Killed Number of database sessions to this database that were terminated by operator intervention during the report interval sessions_killed

In Postgres Pro Enterprise databases of versions that include pgpro_stats version starting with 1.4, workload statistics of vacuum processes are available. The Database vacuum statistics report table provides per-database aggregated total vacuum statistics based on the pgpro_stats_vacuum_tables view. Table G.12 lists columns of this report table. Times are provided in seconds.

Table G.12. Database vacuum statistics

ColumnDescriptionField/Calculation
Database Database name  
Blocks fetched Total number of database blocks fetched by vacuum operations total_blks_read + total_blks_hit
Fetched %Total Total number of database blocks fetched (read+hit) by vacuum operations as the percentage of all blocks fetched in the cluster Blocks fetched * 100 / Cluster fetched
Blocks read Total number of database blocks read by vacuum operations total_blks_read
Read %Total Total number of database blocks read by vacuum operations as the percentage of all blocks read in the cluster Blocks read * 100 / Cluster read
VM Frozen Total number of blocks marked all-frozen in the visibility map pages_frozen
VM Visible Total number of blocks marked all-visible in the visibility map pages_all_visible
Tuples deleted Total number of dead tuples vacuum operations deleted from tables of this database tuples_deleted
Tuples left Total number of dead tuples vacuum operations left in tables of this database due to their visibility in transactions dead_tuples
%Eff Vacuum efficiency in terms of deleted tuples. This is the percentage of tuples deleted from tables of this database in all dead tuples to be deleted from tables of this database. tuples_deleted * 100 / (tuples_deleted + dead_tuples)
WAL size Total amount of WAL bytes generated by vacuum operations performed on tables of this database wal_bytes
Read I/O time Time spent reading database blocks by vacuum operations performed on tables of this database blk_read_time
Write I/O time Time spent writing database blocks by vacuum operations performed on tables of this database blk_write_time
%Total Vacuum I/O time spent as the percentage of whole cluster I/O time
Vacuum time Total Total time of vacuuming tables of this database total_time
Vacuum time Delay Time spent sleeping in a vacuum delay point by vacuum operations performed on tables of this database delay_time
User CPU time User CPU time of vacuuming tables of this database user_time
System CPU time System CPU time of vacuuming tables of this database system_time
Interrupts Number of times vacuum operations performed on tables of this database were interrupted on any errors interrupts

If the pgpro_stats extension supporting invalidation statistics was available during the report interval, the "Invalidation messages by database" report table provides per-database aggregated total invalidation message statistics. Table G.13 lists columns of this report table.

Table G.13. Invalidation messages by database

ColumnDescriptionField/Calculation
Database Database name  
Invalidation messages sent Total number of invalidation messages sent by backends in this database. Statistics are provided for corresponding message types of pgpro_stats_inval_msgsFields of pgpro_stats_totals.inval_msgs
Cache resets Total number of shared cache resets pgpro_stats_totals.cache_resets

If the pgpro_stats extension was available during the report interval, the Statement statistics by database report table provides per-database aggregated total statistics for the pgpro_stats_statements view data. Table G.14 lists columns of this report table. Times are provided in seconds.

Table G.14. Statement statistics by database

ColumnDescriptionField/Calculation
Database Database name  
Calls Number of times all statements in the database were executed calls
Plan Time Time spent planning all statements in the database Sum of total_plan_time
Exec Time Time spent executing all statements in the database Sum of total_exec_time
Read Time Time spent reading blocks by all statements in the database Sum of blk_read_time
Write Time Time spent writing blocks by all statements in the database Sum of blk_write_time
Trg Time Time spent executing trigger functions by all statements in the database  
Shared Fetched Total number of shared blocks fetched by all statements in the database Sum of (shared_blks_read + shared_blks_hit)
Local Fetched Total number of local blocks fetched by all statements in the database Sum of (local_blks_read + local_blks_hit)
Shared Dirtied Total number of shared blocks dirtied by all statements in the database Sum of shared_blks_dirtied
Local Dirtied Total number of local blocks dirtied by all statements in the database Sum of local_blks_dirtied
Read Temp Total number of temporary blocks read by all statements in the database Sum of temp_blks_read
Write Temp Total number of temporary blocks written by all statements in the database Sum of temp_blks_written
Read Local Total number of local blocks read by all statements in the database Sum of local_blks_read
Write Local Total number of local blocks written by all statements in the database Sum of local_blks_written
Statements Total number of captured statements  
WAL Size Total amount of WAL generated by all statements in the database Sum of wal_bytes
WAL buffers full Number of times the WAL buffers became full

The Statement average min/max timings report table contains per-database aggregated min/max timing statistics from the one of pgpro_stats or pg_stat_statements extensions that was available during the report interval, with the precedence of pgpro_stats. This report is sensitive to the fastest and slowest planning and execution of every statement in a cluster. That is, you can see execution and planning stability in your database. Table G.15 lists columns of this report table.

Table G.15. Statement average min/max timings

ColumnDescription
Database Database name
Min average planning time The average value of min_plan_time for all statements and all samples included in the report, in milliseconds
Max average planning time The average value of max_plan_time for all statements and all samples included in the report, in milliseconds
Delta% of average planning times Difference between the mean max_plan_time and mean min_plan_time as the percentage of the mean min_plan_time. The less this difference, the more stable query planning in your database is.
Min average execution time The average value of min_exec_time for all statements and all samples included in the report, in milliseconds
Max average execution time The average value of max_exec_time for all statements and all samples included in the report, in milliseconds
Delta% of average execution times Difference between the mean max_exec_time and mean min_exec_time as the percentage of the mean min_exec_time. The less this difference, the more stable query execution in your database is.
Statements Total count of captured statements

If the JIT-related statistics was avaliable in the statement statistics extension during the report interval, the JIT statistics by database report table provides per-database aggregated total statistics of JIT executions. Table G.16 lists columns of this report table. Times are provided in seconds.

Table G.16. JIT statistics by database

ColumnDescriptionField/Calculation
Database Database name  
Calls Number of times all statements in the database were executed calls
Plan Time Time spent planning all statements in the database Sum of total_plan_time
Exec Time Time spent executing all statements in the database Sum of total_exec_time
Generation count Total number of functions JIT-compiled by the statements Sum of jit_functions
Generation time Total time spent by the statements on generating JIT code Sum of jit_generation_time
Inlining count Number of times functions have been inlined Sum of jit_inlining_count
Inlining time Total time spent by statements on inlining functions Sum of jit_inlining_time
Optimization count Number of times statements have been optimized Sum of jit_optimization_count
Optimization time Total time spent by statements on optimizing Sum of jit_optimization_time
Emission count Number of times code has been emitted Sum of jit_emission_count
Emission time Total time spent by statements on emitting code Sum of jit_emission_time
Deform count Number of tuple deform functions JIT-compiled by the statement of the database
Deform time Total time spent by the statements of the database on JIT-compiling the tuple deform functions

The report table Cluster statistics provides data from the pg_stat_bgwriter and pg_stat_checkpointer views. The latter is available starting with Postgres Pro 17. Table G.17 lists rows of this report table. Times are provided in seconds.

Table G.17. Cluster statistics

RowDescriptionField/Calculation
Checkpoints Scheduled Number of scheduled checkpoints that have been performed checkpoints_timed
Checkpoints Requested Number of requested checkpoints that have been performed checkpoints_req
Checkpoints Done Number of checkpoints that have been performed
Restartpoints Scheduled Number of restartpoints scheduled due to timeout or after a failed attempt to perform a restartpoint restartpoints_timed
Restartpoints Requested Number of requested restartpoints if any restartpoints_req
Restartpoints Done Number of restartpoints that have been performed if any restartpoints_done
Checkpoint write time Total amount of time that has been spent in the portion of checkpoint and restartpoint processing where files are written to disk checkpoint_write_time
Checkpoint sync time Total amount of time that has been spent in the portion of checkpoint and restartpoint processing where files are synchronized to disk checkpoint_sync_time
Checkpoint buffers written Number of shared buffers written during checkpoints and restartpoints buffers_checkpoint
SLRU buffers written by checkpoint Number of SLRU buffers written during checkpoints and restartpoints
Background buffers written Number of buffers written by the background writer buffers_clean
Backend buffers written Number of buffers written directly by a backend. Will not be shown since Postgres Pro 17. buffers_backend
Backend fsync count Number of times a backend had to execute its own fsync call (normally the background writer handles those even when the backend does its own write). Will not be shown since Postgres Pro 17. buffers_backend_fsync
Bgwriter interrupts (too many buffers) Number of times the background writer stopped a cleaning scan because it had written too many buffers maxwritten_clean
Number of buffers allocated Total number of buffers allocated buffers_alloc
WAL generated Total amount of WAL generated pg_current_wal_lsn() value increment
Start LSN Log sequence number at the start of a report interval pg_current_wal_lsn() at the first sample of a report
End LSN Log sequence number at the end of a report interval pg_current_wal_lsn() at the last sample of a report
WAL generated by vacuum Total amount of WAL generated by vacuum Based on the wal_bytes field of the pgpro_stats_vacuum_databases view.
WAL segments archived Total number of archived WAL segments Based on pg_stat_archiver.archived_count
WAL segments archive failed Total number of WAL segment archiver failures Based on pg_stat_archiver.failed_count.
Archiver performance Average archiver process performance per second Based on the active_time field of the pgpro_stats_archiver view.
Archive command performance Average archive_command performance per second Based on the archive_command_time field of the pgpro_stats_archiver view.

Table WAL statistics is available in the report for Postgres Pro databases starting with version 14. This table is based on the pg_stat_wal view of the Statistics Collector. Table G.18 lists columns of this report table. Times are provided in seconds.

Table G.18. WAL statistics

RowDescriptionField/Calculation
WAL generated Total amount of WAL generated during the report interval wal_bytes
WAL per second Average amount of WAL generated per second during the report interval wal_bytes / report_duration
WAL records Total number of WAL records generated during the report interval wal_records
WAL FPI Total number of WAL full page images generated during the report interval wal_fpi
WAL buffers full Number of times WAL data was written to disk because WAL buffers became full during the report interval wal_buffers_full
WAL writes Number of times WAL buffers were written out to disk via XLogWrite request during the report interval wal_write
WAL writes per second Average number of times WAL buffers were written out to disk via XLogWrite request per second during the report interval wal_write / report_duration
WAL sync Number of times WAL files were synced to disk via issue_xlog_fsync request during the report interval (if fsync is on and wal_sync_method is either fdatasync, fsync or fsync_writethrough, otherwise zero). See Section 29.5 for more information about the internal WAL function issue_xlog_fsync. wal_sync
WAL syncs per second Average number of times WAL files were synced to disk via issue_xlog_fsync request per second during the report interval wal_sync / report_duration
WAL write time Total amount of time spent writing WAL buffers to disk via XLogWrite request during the report interval (if track_wal_io_timing is enabled, otherwise zero; for more details, see Section 19.9). This includes the sync time when wal_sync_method is either open_datasync or open_sync. wal_write_time
WAL write dutyWAL write time as the percentage of the report interval duration wal_write_time * 100 / report_duration
WAL sync time Total amount of time spent syncing WAL files to disk via issue_xlog_fsync request during the report interval (if track_wal_io_timing is enabled, fsync is on, and wal_sync_method is either fdatasync, fsync or fsync_writethrough, otherwise zero). wal_sync_time
WAL sync dutyWAL sync time as the percentage of the report interval duration wal_sync_time * 100 / report_duration

The report table Tablespace statistics provides information on the sizes and growth of tablespaces. Table G.19 lists columns of this report table.

Table G.19. Tablespace statistics

ColumnDescriptionField/Calculation
Tablespace Tablespace name pg_tablespace.spcname
Path Tablespace path pg_tablespace_location()
Size Tablespace size at the time of the last sample in the report interval pg_tablespace_size()
Growth Tablespace growth during the report interval pg_tablespace_size() increment between interval bounds

If the pgpro_stats extension was available during the report interval, the report table Wait statistics by database shows the total wait time by wait event type and database. Table G.20 lists columns of this report table.

Table G.20. Wait statistics by database

ColumnDescription
Database Database name
Wait event type Type of event for which the backends were waiting. Asterisk means aggregation of all wait event types in the database.
Waited Time spent waiting in events of Wait event type, in seconds
%Total Percentage of wait time spent in the database events of Wait event type in all wait time for the cluster

If the pgpro_stats extension was available during the report interval, the report table Top wait events shows top wait events in the cluster by wait time. Table G.21 lists columns of this report table.

Table G.21. Top wait events

ColumnDescription
Database Database name
Wait event type The type of event for which the backends were waiting
Wait event Wait event name for which the backends were waiting
Waited Total wait time spent in Wait event of the database, in seconds
%Total Percentage of wait time spent in Wait event of the database in all wait time in the cluster

G.4.11.2. Load distribution

This section of a pgpro_pwr report is based on the pgpro_stats_totals view of the pgpro_stats extension if it was available during the report interval. Each table in this section provides data for the report interval on load distribution for a certain kind of objects for which aggregated statistics are collected, such as databases, applications, hosts, or users. Each table contains one row for each resource (for example, total time or shared blocks written), where load distribution is shown in graphics, as a stacked bar chart for top objects by load of this resource. If the bar chart area that corresponds to an object is too narrow to include captions, point that area to get a hint with the caption, value and percentage. The report tables Load distribution among heavily loaded databases, Load distribution among heavily loaded applications, Load distribution among heavily loaded hosts and Load distribution among heavily loaded users show load distribution for respective objects. Table G.22 lists rows of these report tables. Times are provided in seconds.

Table G.22. Load distribution

RowDescriptionCalculation
Total time Total time spent in the planning and execution of statements total_plan_time + total_exec_time
Executed count Number of queries executed queries_executed
I/O time Total time the statements spent reading or writing blocks (if track_io_timing is enabled, otherwise zero) blk_read_time + blk_write_time
Blocks fetched Total number of shared block cache hits and shared blocks read by the statements shared_blks_hit + shared_blks_read
Shared blocks read Total number of shared blocks read by the statements shared_blks_read
Shared blocks dirtied Total number of shared blocks dirtied by the statements shared_blks_dirtied
Shared blocks written Total number of shared blocks written by the statements shared_blks_written
WAL generated Total amount of WAL generated by the statements wal_bytes
Temp and Local blocks written Total number of temporary and local blocks written by the statements temp_blks_written + local_blks_written
Temp and Local blocks read Total number of temp and local blocks read by the statements temp_blks_read + local_blks_read
Invalidation messages sent Total number of all invalidation messages sent by backends in this database (pgpro_stats_totals.inval_msgs).all
Cache resets Total number of shared cache resets pgpro_stats_totals.cache_resets

G.4.11.3. Session states observed by subsamples

This section of a pgpro_pwr report provides information about session states captured by subsamples during the report interval.

Tables of this report section are described below.

The report subsection Chart with session state visualizes session states captured by subsamples. It is the timeline chart showing captured session states in backends and transactions. Every state contains a popup with session state attributes. Click on a state to see this state in the table of session states.

The report table Session state statistics by database shows the aggregated data on session states. Only session states captured in subsamples are counted. Table G.23 lists columns of this report table.

Table G.23. Session state statistics by database

ColumnDescription
Database Database name
Summary Active Overall time of active states captured in subsamples
Summary Idle in xact Overall time of idle in transaction states captured in subsamples
Summary Idle in xact (A) Overall time of idle in transaction (aborted) states captured in subsamples
Maximal Active Time of the longest active state captured in subsamples
Maximal Idle in xact Time of the longest idle in transaction state captured in subsamples
Maximal Idle in xact (A) Time of the longest idle in transaction (aborted) state captured in subsamples
Maximal xact age Maximal transaction age detected in subsamples

The report table Top 'idle in transaction' session states by duration shows top pgpro_pwr.max longest idle in transaction states that were last observed in the pg_stat_activity view for each session. Table G.24 lists columns of this report table.

Table G.24. Top 'idle in transaction' session states by duration

ColumnDescriptionField/Calculation
Database Database name datname
User User name usename
App Application name application_name
Pid Process ID pid
Xact start Transaction start timestamp xact_start
State change State change timestamp state_change
State duration State duration clock_timestamp() - state_change

The report table Top 'active' session states by duration shows top pgpro_pwr.max longest active states that were last observed in the pg_stat_activity view for each session. Table G.25 lists columns of this report table.

Table G.25. Top 'active' session states by duration

ColumnDescriptionField/Calculation
Database Database name datname
User User name usename
App Application name application_name
Pid Process ID pid
Xact start Transaction start timestamp xact_start
State change State change timestamp state_change
State duration State duration clock_timestamp() - state_change

The report table Top states by transaction age shows top session states by transaction age that were last observed in the pg_stat_activity view for each session. Table G.26 lists columns of this report table.

Table G.26. Top states by transaction age

ColumnDescriptionField/Calculation
Database Database name datname
User User name usename
App Application name application_name
Pid Process ID pid
Xact start Transaction start timestamp xact_start
Xact duration Transaction duration clock_timestamp() - xact_start
Age Transaction age age(backend_xmin)
State Session state at the maximum age detected  
State change State change timestamp state_change
State duration State duration clock_timestamp() - state_change

The report table Top states by transaction duration shows top longest session states that were last observed in the pg_stat_activity view for each session. Table G.27 lists columns of this report table.

Table G.27. Top states by transaction duration

ColumnDescriptionField/Calculation
Database Database name datname
User User name usename
App Application name application_name
Pid Process ID pid
Xact start Transaction start timestamp xact_start
Xact duration Transaction duration clock_timestamp() - xact_start
Age Transaction age age(backend_xmin)
State Session state at the maximum age detected  
State change State change timestamp state_change
State duration State duration clock_timestamp() - state_change

G.4.11.4. SQL query statistics

This section of a pgpro_pwr report provides data for the report interval on top statements by several important statistics. The data is mainly captured from views of the one of pgpro_stats and pg_stat_statements extensions that was available during the report interval, with the precedence of pgpro_stats. Each statement can be highlighted in all SQL-related sections with a single mouse click on it. This click will also show a query text preview just under the query statistics row. The query text preview can be hidden with a second click on a query.

Tables of this report section are described below.

The report table Top SQL by elapsed time shows top statements by the sum of total_plan_time and total_exec_time fields of the pgpro_stats_statements or pg_stat_statements view. Table G.28 lists columns of this report table. Times are provided in seconds.

Table G.28. Top SQL by elapsed time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
%Total Percentage of elapsed time of this statement plan in the total elapsed time of all statements in the cluster  
Elapsed Time Total time spent in planning and execution of the statement plan total_plan_time + total_exec_time
Plan Time Total time spent in planning of the statement total_plan_time
Exec Time Total time spent in execution of the statement plan total_exec_time
JIT Time Total time spent by JIT executing this statement plan, in seconds jit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Read I/O time Total time the statement spent reading blocks blk_read_time
Write I/O time Total time the statement spent writing blocks blk_write_time
Usr CPU time Time spent on CPU in the user space, in seconds rusage.user_time
Sys CPU time Time spent on CPU in the system space, in seconds rusage.system_time
Plans Number of times the statement was planned plans
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by planning time shows top statements by the value of the total_plan_time field of the pgpro_stats_statements or pg_stat_statements view. Table G.29 lists columns of this report table.

Table G.29. Top SQL by planning time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Plan elapsed Total time spent in planning of the statement, in seconds total_plan_time
%Elapsed Percentage of total_plan_time in the sum of total_plan_time and total_exec_time of this statement plan  
Mean plan time Mean time spent planning the statement, in milliseconds mean_plan_time
Min plan time Minimum time spent planning the statement, in milliseconds min_plan_time
Max plan time Maximum time spent planning the statement, in milliseconds max_plan_time
StdErr plan time Population standard deviation of time spent planning the statement, in milliseconds stddev_plan_time
Plans Number of times the statement was planned plans
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by execution time shows top statements by the value of the total_time field of the pgpro_stats_statements or pg_stat_statements view. Table G.30 lists columns of this report table.

Table G.30. Top SQL by execution time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Exec Total time spent executing the statement plan, in seconds total_exec_time
%Elapsed Percentage of total_exec_time of this statement plan in this statement elapsed time  
%Total Percentage of total_exec_time of this statement plan in the total elapsed time of all statements in the cluster  
JIT Time Total time spent by JIT executing this statement plan, in seconds jit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Read I/O time Total time spent in reading pages while executing the statement plan, in seconds blk_read_time
Write I/O time Total time spent in writing pages while executing the statement plan, in seconds blk_write_time
Usr CPU time Time spent on CPU in the user space, in seconds rusage.user_time
Sys CPU time Time spent on CPU in the system space, in seconds rusage.system_time
Rows Number of rows retrieved or affected by execution of the statement plan rows
Mean execution time Mean time spent executing the statement plan, in milliseconds mean_exec_time
Min execution time Minimum time spent executing the statement plan, in milliseconds min_exec_time
Max execution time Maximum time spent executing the statement plan, in milliseconds max_exec_time
StdErr execution time Population standard deviation of time spent executing the statement plan, in milliseconds stddev_exec_time
Executions Number of executions of this statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by mean execution time shows top pgpro_pwr.max statements by the value of the mean_time or mean_exec_time field of the pgpro_stats_statements or pg_stat_statements view. Table G.31 lists columns of this report table.

Table G.31. Top SQL by mean execution time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Mean execution time Mean time spent executing the statement, in milliseconds mean_exec_time
Min execution time Minimum time spent executing the statement, in milliseconds min_exec_time
Max execution time Maximum time spent executing the statement, in milliseconds max_exec_time
StdErr execution time Population standard deviation of time spent executing the statement, in milliseconds stddev_exec_time
Exec Time spent executing this statement, in seconds total_exec_time
%Elapsed Execution time of this statement as the percentage of the statement elapsed time
%Total Execution time of this statement as the percentage of the total elapsed time of all statements in the cluster
JIT time Total time spent by JIT executing this statement, in seconds jit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Read I/O time Time spent reading blocks, in seconds blk_read_time
Write I/O time Time spent writing blocks, in seconds blk_write_time
Rows Number of rows retrieved or affected by the statement rows
Executions Number of times this statement was executed calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by executions shows top statements by the value of the calls field of the pgpro_stats_statements or pg_stat_statements view. Table G.32 lists columns of this report table.

Table G.32. Top SQL by executions

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Executions Number of executions of the statement plan calls
%Total Percentage of calls of this statement plan in the total calls of all statements in the cluster  
Rows Number of rows retrieved or affected by execution of the statement plan rows
Mean Mean time spent executing the statement plan, in milliseconds mean_exec_time
Min Minimum time spent executing the statement plan, in milliseconds min_exec_time
Max Maximum time spent executing the statement plan, in milliseconds max_exec_time
StdErr Population standard deviation of time spent executing the statement plan, in milliseconds stddev_time
Elapsed Total time spent executing the statement plan, in seconds total_exec_time
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by I/O wait time shows top statements by read and write time, i.e., sum of values of blk_read_time and blk_write_time fields of the pgpro_stats_statements or pg_stat_statements view. Table G.33 lists columns of this report table. Times are provided in seconds.

Table G.33. Top SQL by I/O wait time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
IO(s) Total time spent in reading and writing while executing this statement plan, i.e., I/O time blk_read_time + blk_write_time
R(s) Total time spent in reading while executing this statement plan blk_read_time
W(s) Total time spent in writing while executing this statement plan blk_write_time
%Total Percentage of I/O time of this statement plan in the total I/O time of all statements in the cluster  
Shr Reads Total number of shared blocks read while executing the statement plan shared_blks_read
Loc Reads Total number of local blocks read while executing the statement plan local_blks_read
Tmp Reads Total number of temp blocks read while executing the statement plan temp_blks_read
Shr Writes Total number of shared blocks written while executing the statement plan shared_blks_written
Loc Writes Total number of local blocks written while executing the statement plan local_blks_written
Tmp Writes Total number of temp blocks written while executing the statement plan temp_blks_written
Elapsed(s) Total time spent in execution of the statement plan total_plan_time + total_exec_time
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by shared blocks fetched shows top statements by the number of read and hit blocks, which helps to detect the most data-intensive statements. Table G.34 lists columns of this report table.

Table G.34. Top SQL by shared blocks fetched

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Blks fetched Number of blocks retrieved while executing the statement plan shared_blks_hit + shared_blks_read
%Total Percentage of blocks fetched while executing the statement plan in all blocks fetched for all statements in the cluster  
Hits(%) Percentage of blocks got from buffers in all blocks got  
Elapsed Total time spent in execution of the statement plan, in seconds total_plan_time + total_exec_time
Rows Number of rows retrieved or affected by execution of the statement plan rows
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by shared blocks read shows top statements by the number of shared reads, which helps to detect the most read-intensive statements. Table G.35 lists columns of this report table.

Table G.35. Top SQL by shared blocks read

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Reads Number of shared blocks read while executing this statement plan shared_blks_read
%Total Percentage of shared reads for this statement plan in all shared reads of all statements in the cluster  
Hits(%) Percentage of blocks got from buffers in all blocks got while executing this statement plan  
Elapsed Total time spent in execution of the statement plan, in seconds total_plan_time + total_exec_time
Rows Number of rows retrieved or affected by execution of the statement plan rows
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by shared blocks dirtied shows top statements by the number of shared dirtied buffers, which helps to detect statements that do most data changes in the cluster. Table G.36 lists columns of this report table.

Table G.36. Top SQL by shared blocks dirtied

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Dirtied Number of shared buffers dirtied while executing this statement plan shared_blks_dirtied
%Total Percentage of dirtied shared buffers for this statement plan in all dirtied shared buffers of all statements in the cluster  
Hits(%) Percentage of blocks got from buffers in all blocks got while executing this statement plan  
WAL Total amount of WAL bytes generated by the statement plan wal_bytes
%Total Percentage of WAL bytes generated by the statement plan in total WAL generated in the cluster  
Elapsed Total time spent in execution of the statement plan, in seconds total_plan_time + total_exec_time
Rows Number of rows retrieved or affected by execution of the statement plan rows
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by shared blocks written shows top statements by the number of blocks written. Table G.37 lists columns of this report table.

Table G.37. Top SQL by shared blocks written

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Written Number of blocks written while executing this statement plan shared_blks_written
%Total Percentage of blocks written by this statement plan in all written blocks in the cluster Percentage of shared_blks_written in (pg_stat_bgwriter.buffers_checkpoint+ pg_stat_bgwriter.buffers_clean+ pg_stat_bgwriter.buffers_backend)
%BackendW Percentage of blocks written by this statement plan in all blocks in the cluster written by backends Percentage of shared_blks_written in pg_stat_bgwriter.buffers_backend
Hits(%) Percentage of blocks got from buffers in all blocks got while executing this statement plan  
Elapsed Total time spent in execution of the statement plan, in seconds total_plan_time + total_exec_time
Rows Number of rows retrieved or affected by execution of the statement plan rows
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by WAL size shows top statements by the amount of WAL generated. Table G.38 lists columns of this report table.

Table G.38. Top SQL by WAL size

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
WAL Total amount of WAL bytes generated by the statement plan wal_bytes
%Total Percentage of WAL bytes generated by the statement plan in total WAL generated in the cluster  
WAL buffers full Number of times the WAL buffers became full  
Dirtied Number of shared buffers dirtied while executing this statement plan shared_blks_dirtied
WAL FPI Total number of WAL full page images generated by the statement plan wal_fpi
WAL records Total number of WAL records generated by the statement plan wal_records
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by temp usage shows top statements by temporary I/O, which is calculated as the sum of temp_blks_read, temp_blks_written, local_blks_read and local_blks_written fields. Table G.39 lists columns of this report table.

Table G.39. Top SQL by temp usage

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Local fetched Number of local blocks retrieved local_blks_hit + local_blks_read
Hits(%) Percentage of local blocks got from buffers in all local blocks got  
Write Local (blk) Number of blocks written by this statement plan that are used in temporary tables local_blks_written
Write Local %Total Percentage of local_blks_written of this statement plan in the total of local_blks_written for all statements in the cluster  
Read Local (blk) Number of blocks read by this statement plan that are used in temporary tables local_blks_read
Read Local %Total Percentage of local_blks_read of this statement plan in the total of local_blks_read for all statements in the cluster  
Write Temp (blk) Number of temporary blocks written by this statement plan temp_blks_written
Write Temp %Total Percentage of temp_blks_written of this statement plan in the total of temp_blks_written for all statements in the cluster  
Read Temp (blk) Number of temporary blocks read by this statement plan temp_blks_read
Read Temp %Total Percentage of temp_blks_read of this statement plan in the total of temp_blks_read for all statements in the cluster  
Elapsed Total time spent in execution of the statement plan, in seconds total_plan_time + total_exec_time
Rows Number of rows retrieved or affected by execution of the statement plan rows
Executions Number of executions of the statement plan calls
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

The report table Top SQL by invalidation messages sent shows top statements by the number of invalidation messages sent. Table G.40 lists columns of this report table.

Table G.40. Top SQL by invalidation messages sent

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements). queryid
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Invalidation messages sent Total number of invalidation messages sent by backends executing this statement. Statistics are provided for corresponding message types of pgpro_stats_inval_msgsfields of pgpro_stats_statements.inval_msgs

G.4.11.4.1. rusage statistics

This section is included in the report only if the pgpro_stats or pg_stat_kcache extension was available during the report interval.

The report table Top SQL by system and user time shows top statements by the sum of user_time and system_time fields of pg_stat_kcache or of the pgpro_stats_totals view. Table G.41 lists columns of this report table. Times are provided in seconds.

Table G.41. Top SQL by system and user time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
User Time Plan User CPU time elapsed during planning plan_user_time
User Time Exec User CPU time elapsed during execution exec_user_time
User Time %Total Percentage of plan_user_time + exec_user_time in the total user CPU time for all statements  
System Time Plan System CPU time elapsed during planning plan_system_time
System Time Exec System CPU time elapsed during execution exec_system_time
System Time %Total Percentage of plan_system_time + exec_system_time in the total system CPU time for all statements  

The report table Top SQL by reads/writes done by filesystem layer shows top statements by the sum of reads and writes fields of pg_stat_kcache. Table G.42 lists columns of this report table.

Table G.42. Top SQL by reads/writes done by filesystem layer

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Read Bytes Plan Bytes read during planning plan_reads
Read Bytes Exec Bytes read during execution exec_reads
Read Bytes %Total Percentage of plan_reads + exec_reads in the total number of bytes read by the filesystem layer for all statements  
Write Bytes Plan Bytes written during planning plan_writes
Write Bytes Exec Bytes written during execution exec_writes
Write Bytes %Total Percentage of plan_writes + exec_writes in the total number of bytes written by the filesystem layer for all statements  

G.4.11.5. SQL query wait statistics

If the pgpro_stats extension was available during the report interval, this section of the report will contain a table that is split into sections, each showing top statements by overall wait time or by wait time for a certain wait event type. Table sections related to specific wait events follow in the descending order of the total wait time in wait events of this type. Table G.43 lists columns of this report table.

Table G.43. SQL query wait statistics

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Waited Total wait time for all wait events of this statement plan, in seconds  
%Total Percentage of the total wait time of this statement plan in all the wait time in the cluster  
Details Waits of this statement plan by wait types  

If the JIT-related statistics was avaliable in the statement statistics extension during the report interval, the report table Top SQL by JIT elapsed time shows top statements by the sum of jit_*_time fields of the pgpro_stats_statements or pg_stat_statements view. Table G.44 lists columns of this report table. Times are provided in seconds.

Table G.44. Top SQL by JIT elapsed time

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Plan ID Hash code to identify the normalized statement's plan planid
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
JIT Time Total time spent by JIT executing this statement plan jit_generation_time + jit_inlining_time + jit_optimization_time + jit_emission_time
Generation count Total number of functions JIT-compiled by this statement Sum of jit_functions
Generation time Total time spent by this statement on generating JIT code Sum of jit_generation_time
Inlining count Number of times functions have been inlined Sum of jit_inlining_count
Inlining time Total time spent by this statement on inlining functions Sum of jit_inlining_time
Optimization count Number of times this statement has been optimized Sum of jit_optimization_count
Optimization time Total time spent by this statement on optimizing Sum of jit_optimization_time
Emission count Number of times code has been emitted Sum of jit_emission_count
Emission time Total time spent by this statement on emitting code Sum of jit_emission_time
Deform count Number of tuple deform functions JIT-compiled by the statement
Deform time Total time spent by the statement on JIT-compiling the tuple deform
Plan Time Total time spent in planning of the statement total_plan_time
Exec Time Total time spent in execution of the statement plan total_exec_time
Read I/O time Total time the statement spent reading blocks blk_read_time
Write I/O time Total time the statement spent writing blocks blk_write_time
%Cvr Coverage: duration of statement statistics collection as the percentage of the report duration

G.4.11.6. Top SQL by parallel workers usage

The Top SQL by parallel workers usage section of the report shows top statements by planned and launched parallel workers, that is, by the sum of parallel_workers_to_launch and parallel_workers_launched fields of the pg_stat_statements view. Some of these statistics are only available starting with Postgres Pro 18. Table G.45 lists columns of this report table. Times are provided in seconds.

Table G.45. Top SQL by parallel workers usage

ColumnDescriptionField/Calculation
Query ID Hex representation of queryid. The hash of the query ID, database ID and user ID is in square brackets. The (N) mark will appear here for nested statements (such as statements invoked within top-level statements).  
Database Database name for the statement Derived from dbid
User Name of the user executing the statement Derived from userid
Parallel workers Planned Number of parallel workers planned to be launched
Parallel workers Launched Number of parallel workers actually launched
Exec System CPU time elapsed during execution exec_system_time or system_time
Blks fetched Number of fetched blocks shared_blks_hit + shared_blks_read
Shr Reads Total number of shared blocks read by the statement plan shared_blks_read
Loc Reads Total number of local blocks read by the statement plan local_blks_read
Tmp Reads Total number of temporary blocks read by the statement plan temp_blks_read
Read I/O time Time spent reading blocks blk_read_time
Write I/O time Time spent writing blocks blk_write_time

G.4.11.7. Complete list of SQL texts

The Complete list of SQL texts section of the report contains a table that provides query and plan texts for all statements mentioned in the report. Use an appropriate Query ID/Plan ID link in any statistics table to see the corresponding query/plan text. Table G.46 lists columns of this report table.

Table G.46. Complete list of SQL texts

ColumnDescription
ID Hex representation of the query or plan identifier
Query/Plan Text Text of the query or statement plan

G.4.11.8. Schema object statistics

Tables in this section of the report show top database objects by statistics from the Postgres Pro's Statistics Collector views. Report tables that contain data for tables and indexes provide a preview of storage parameters. You can click on a row to see storage parameters of the object right under the row.

The report table Top tables by estimated sequentially scanned volume shows top tables by estimated volume read by sequential scans. This can help you find database tables that possibly lack some index. When there are no relation sizes collected with pg_relation_size(), relation-size estimates are based on the pg_class.relpages field. Since such values are less accurate, they are shown in square brackets. The data is based on the pg_stat_all_tables view. Table G.47 lists columns of this report table.

Table G.47. Top tables by estimated sequentially scanned volume

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
~SeqBytes Estimated volume read by sequential scans Sum of (pg_relation_size() * seq_scan)
SeqScan Number of sequential scans performed on the table seq_scan
IxScan Number of index scans initiated on the table idx_scan
IxFet Number of live rows fetched by index scans idx_tup_fetch
Ins Number of rows inserted n_tup_ins
Upd Number of rows updated n_tup_upd
Del Number of rows deleted n_tup_del
Upd(HOT) Number of rows HOT updated n_tup_hot_upd

In the report table Top tables by blocks fetched, blocks fetched include blocks being processed from disk (read) and from shared buffers (hit). This report table shows top database tables by the sum of blocks fetched for the table's heap, indexes, TOAST table (if any) and TOAST table index (if any). This can help you focus on tables with excessive processing of blocks. The data is based on the pg_statio_all_tables view. Table G.48 lists columns of this report table.

Table G.48. Top tables by blocks fetched

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
Heap Blks Number of blocks fetched for the table's heap heap_blks_read + heap_blks_hit
Heap Blks %Total Percentage of blocks fetched for the table's heap in all blocks fetched in the cluster  
Ix Blks Number of blocks fetched for table's indexes idx_blks_read + idx_blks_hit
Ix Blks %Total Percentage of blocks fetched for table's indexes in all blocks fetched in the cluster  
TOAST Blks Number of blocks fetched for the table's TOAST table toast_blks_read + toast_blks_hit
TOAST Blks %Total Percentage of blocks fetched for the table's TOAST table in all blocks fetched in the cluster  
TOAST-Ix Blks Number of blocks fetched for the table's TOAST index tidx_blks_read + tidx_blks_hit
TOAST-Ix Blks %Total Percentage of blocks fetched for the table's TOAST index in all blocks fetched in the cluster  

The report table Top tables by blocks read shows top database tables by the number of blocks read for the table's heap, indexes, TOAST table (if any) and TOAST table index (if any). This can help you focus on tables with excessive block readings. The data is based on the pg_statio_all_tables view. Table G.49 lists columns of this report table.

Table G.49. Top tables by blocks read

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
Heap Blks Number of blocks read for the table's heap heap_blks_read
Heap Blks %Total Percentage of blocks read from the table's heap in all blocks read in the cluster  
Ix Blks Number of blocks read from table's indexes idx_blks_read
Ix Blks %Total Percentage of blocks read from table's indexes in all blocks read in the cluster  
TOAST Blks Number of blocks read from the table's TOAST table toast_blks_read
TOAST Blks %Total Percentage of blocks read from the table's TOAST table in all blocks read in the cluster  
TOAST-Ix Blks Number of blocks read from the table's TOAST index tidx_blks_read
TOAST-Ix Blks %Total Percentage of blocks read from the table's TOAST index in all blocks read in the cluster  
Hit(%) Percentage of table, index, TOAST and TOAST index blocks got from buffers for this table in all blocks got for this table from either file system or buffers  

The report table Top DML tables shows top tables by the number of DML-affected rows, i.e., by the sum of n_tup_ins, n_tup_upd and n_tup_del (including TOAST tables). The data is based on the pg_stat_all_tables view. Table G.50 lists columns of this report table.

Table G.50. Top DML tables

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
Ins Number of rows inserted n_tup_ins
Upd Number of rows updated, including HOT n_tup_upd
Del Number of rows deleted n_tup_del
Upd(HOT) Number of rows HOT updated n_tup_hot_upd
SeqScan Number of sequential scans performed on the table seq_scan
SeqFet Number of live rows fetched by sequential scans seq_tup_read
IxScan Number of index scans initiated on this table idx_scan
IxFet Number of live rows fetched by index scans idx_tup_fetch

The report table Top tables by updated/deleted tuples shows top tables by tuples modified by UPDATE/DELETE operations, i.e., by the sum of n_tup_upd and n_tup_del (including TOAST tables). The data is based on the pg_stat_all_tables view. Table G.51 lists columns of this report table.

Table G.51. Top tables by updated/deleted tuples

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
Upd Number of rows updated, including HOT n_tup_upd
Upd(HOT) Number of rows HOT updated n_tup_hot_upd
Del Number of rows deleted n_tup_del
Vacuum count Number of times this table has been manually vacuumed (not counting VACUUM FULL) vacuum_count
Autovacuum count Number of times this table has been vacuumed by the autovacuum daemon autovacuum_count
Analyze count Number of times this table was manually analyzed analyze_count
AutoAnalyze count Number of times this table was analyzed by the autovacuum daemon autoanalyze_count

The report table Top tables by removed all-visible marks shows top tables by the number of times that the all-visible mark was removed from the visibility map by any backend. This report section is only shown when corresponding statistics are available. Table G.52 lists columns of this report table.

Table G.52. Top tables by removed all-visible marks

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
All-Visible marks cleared Number of times that the all-visible mark was removed from the relation visibility map rev_all_visible_pages
All-Visible marks set Number of times that the all-visible mark was set in the relation visibility map pages_all_visible
All-Visible marks %Set Percentage of the number of times that the all-visible mark was set in the number of times that it was set or removed pages_all_visible * 100% / (rev_all_visible_pages + pages_all_visible)
Vacuum count Number of times this table has been manually vacuumed (not counting VACUUM FULL) vacuum_count
Autovacuum count Number of times this table has been vacuumed by the autovacuum daemon autovacuum_count

The report table Top tables by removed all-frozen marks shows top tables by the number of times that the all-frozen mark was removed from the visibility map by any backend. This report section is only shown when corresponding statistics are available. Table G.53 lists columns of this report table.

Table G.53. Top tables by removed all-frozen marks

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
All-Frozen marks cleared Number of times that the all-frozen mark was removed from the relation visibility map rev_all_frozen_pages
All-Frozen marks set Number of times that the all-frozen mark was set in the relation visibility map pages_frozen
All-Frozen marks %Set Percentage of the number of times that the all-frozen mark was set in the number of times that it was set or removed pages_frozen * 100% / (rev_all_frozen_pages + pages_frozen)
Vacuum count Number of times this table has been manually vacuumed (not counting VACUUM FULL) vacuum_count
Autovacuum count Number of times this table has been vacuumed by the autovacuum daemon autovacuum_count

The report table Top tables by new-page updated tuples shows top tables by the number of rows updated where the successor version goes onto a new heap page, leaving behind an original version with a t_ctid field that points to a different heap page. These are always non-HOT updates. Table G.54 lists columns of this report table.

Table G.54. Top tables by new-page updated tuples

ColumnDescription
DB Database name for the table
Tablespace Name of the tablespace where the table is located
Schema Schema name for the table
Table Table name
NP Upd Number of rows updated to a new heap page
%Upd Number of new-page updated rows as the percentage of all rows updated
Upd Number of rows updated, including HOT
Upd(HOT) Number of rows HOT updated (i.e., with no separate index update required)

The report table Top growing tables shows top tables by growth. The data is based on the pg_stat_all_tables view. When there are no relation sizes collected with pg_relation_size(), relation-size estimates are based on the pg_class.relpages field. Since such values are less accurate, they are shown in square brackets. Table G.55 lists columns of this report table.

Table G.55. Top growing tables

ColumnDescriptionField/Calculation
DB Database name for the table  
Tablespace Name of the tablespace where the table is located  
Schema Schema name for the table  
Table Table name  
Size Table size at the time of the last sample in the report interval pg_table_size() - pg_relation_size(toast)
Growth Table growth  
Ins Number of rows inserted n_tup_ins
Upd Number of rows updated, including HOT n_tup_upd
Del Number of rows deleted n_tup_del
Upd(HOT) Number of rows HOT updated n_tup_hot_upd

In the report table Top indexes by blocks fetched, blocks fetched include index blocks processed from disk (read) and from shared buffers (hit). The data is based on the pg_statio_all_indexes view. Table G.56 lists columns of this report table.

Table G.56. Top indexes by blocks fetched

ColumnDescriptionField/Calculation
DB Database name for the index  
Tablespace Name of the tablespace where the index is located  
Schema Schema name for the underlying table  
Table Underlying table name  
Index Index name  
Scans Number of index scans initiated on this index idx_scan
Blks Number of blocks fetched for this index idx_blks_read + idx_blks_hit
%Total Percentage of blocks fetched for this index in all blocks fetched in the cluster  

The report table Top indexes by blocks read is also based on the pg_statio_all_indexes and pg_stat_all_indexes views. Table G.57 lists columns of this report table.

Table G.57. Top indexes by blocks read

ColumnDescriptionField/Calculation
DB Database name for the index  
Tablespace Name of the tablespace where the index is located  
Schema Schema name for the underlying table  
Table Underlying table name  
Index Index name  
Scans Number of index scans initiated on this index idx_scan
Blk Reads Number of disk blocks read from this index idx_blks_read
%Total Percentage of disk blocks read from this index in all disk blocks read in the cluster  
Hits(%) Percentage of index blocks got from buffers in all index blocks got for this index  

The report table Top growing indexes shows top indexes by growth. The table uses data from the pg_stat_all_tables and pg_stat_all_indexes views. When there are no relation sizes collected with pg_relation_size(), relation-size estimates are based on the pg_class.relpages field. Since such values are less accurate, they are shown in square brackets. Table G.58 lists columns of this report table.

Table G.58. Top growing indexes

ColumnDescriptionField/Calculation
DB Database name for the index  
Tablespace Name of the tablespace where the index is located  
Schema Schema name for the underlying table  
Table Underlying table name  
Index Index name  
Index Size Index size at the time of the last sample in the report interval pg_relation_size()
Index Growth Index growth during the report interval  
Table Ins Number of rows inserted into the underlying table n_tup_ins
Table Upd Number of rows updated in the underlying table, without HOT n_tup_upd - n_tup_hot_upd
Table Del Number of rows deleted from the underlying table n_tup_del

The report table Unused indexes shows top non-scanned indexes (during the report interval) by DML operations on underlying tables that caused index support. Constraint indexes are not counted. The table uses data from the pg_stat_all_tables view. Table G.59 lists columns of this report table.

Table G.59. Unused indexes

ColumnDescriptionField/Calculation
DB Database name for the index  
Tablespace Name of the tablespace where the index is located  
Schema Schema name for the underlying table  
Table Underlying table name  
Index Index name  
Index Size Index size at the time of the last sample in the report interval pg_relation_size()
Index Growth Index growth during the report interval  
Table Ins Number of rows inserted into the underlying table n_tup_ins
Table Upd Number of rows updated in the underlying table, without HOT n_tup_upd - n_tup_hot_upd
Table Del Number of rows deleted from the underlying table n_tup_del

G.4.11.9. User function statistics

Tables in this section of the report show top functions in the cluster by statistics from the pg_stat_user_functions view. Times in the tables are provided in seconds.

The report table Top functions by total time shows top functions by the total time elapsed. The report table Top functions by executions shows top functions by the number of executions. The report table Top trigger functions by total time shows top trigger functions by the total time elapsed. Table G.60 lists columns of these report tables.

Table G.60. User function statistics

ColumnDescriptionField/Calculation
DB Database name for the function  
Schema Schema name for the function  
Function Function name  
Executions Number of times this function has been called calls
Total Time Total time spent in this function and all other functions called by it total_time
Self Time Total time spent in this function itself, not including other functions called by it self_time
Mean Time Mean time of a single function execution total_time/calls
Mean self Time Mean self time of a single function execution self_time/calls

G.4.11.11. Cluster settings during the report interval

This section of the report contains a table with Postgres Pro GUC parameters, values of functions version(), pg_postmaster_start_time(), pg_conf_load_time() and the system_identifier field of the pg_control_system() function during the report interval. The data in the table is grouped under Defined settings and Default settings. Table G.75 lists columns of this report table.

Table G.75. Cluster settings during the report interval

ColumnDescription
Setting Name of the parameter
reset_valreset_val field of the pg_settings view. Settings changed during the report interval are shown in bold font.
Unit Unit of the setting
Source Configuration file where this setting is defined, semicolon, line number
Notes Timestamp of the sample where this value was first observed

G.4.11.12. Extension versions during the report interval

This section of the report contains a table that lists installed extension versions found in databases during the report interval. First seen and Last seen columns are not shown if the extension versions have not changed during the report interval. Table G.76 lists columns of this report table.

Table G.76. Extension versions during the report interval

ColumnDescription
Name Extension name
DB Database name
First seen Timestamp of the sample where this extension version appeared first
Last seen Timestamp of the sample where this extension version appeared last
Version Version name of the extension

G.4.12. pgpro_pwr Diagnostic Tools

pgpro_pwr provides self-diagnostic tools.

G.4.12.1. Collecting Detailed Timing Statistics for Sampling Procedures

pgpro_pwr collects detailed timing statistics of taking samples when the pgpro_pwr.track_sample_timings parameter is on. You can get the results from the v_sample_timings view. Table G.77 lists columns of this view.

Table G.77. v_sample_timings View

ColumnDescription
server_name Name of the server
sample_id Sample identifier
sample_time Time when the sample was taken
sampling_event Sampling stage. See Table G.78 for descriptions of sampling stages.
time_spent Time spent in the event

Table G.78. sampling_event Description

EventDescription
total Taking the sample (all stages)
connect Making dblink connection to the server
get server environment Getting server GUC parameters, available extensions, etc.
collect database stats Querying the pg_stat_database view for statistics on databases
calculate database stats Calculating differential statistics on databases since the previous sample
collect tablespace stats Querying the pg_tablespace view for statistics on tablespaces
collect statement stats Collecting statistics on statements using the pgpro_stats and pg_stat_kcache extensions
collect wait sampling stats Collecting statistics on statements using the pg_wait_sampling extension
query pg_stat_bgwriter Collecting cluster statistics using the pg_stat_bgwriter view
query pg_stat_wal Collecting cluster WAL statistics using the pg_stat_wal view
query pg_stat_io Collecting cluster I/O statistics using the pg_stat_io view, available starting with Postgres Pro 16
query pg_stat_slru Collecting cluster SLRU statistics using the pg_stat_slru view
query pg_stat_archiver Collecting cluster statistics using the pg_stat_archiver view
collect object stats Collecting statistics on database objects. Includes events from Table G.79. Includes the following events:
  • db:dbname get extensions version — Collecting the list of extension versions for the dbname database

  • db:dbname collect tables stats — Collecting statistics on tables for the dbname database

  • db:dbname collect indexes stats — Collecting statistics on indexes for the dbname database

  • db:dbname collect functions stats — Collecting statistics on functions for the dbname database

  • analyzing collected data — Analyzing partitions of collected data

processing subsamples Collecting server process statistics using the pg_stat_activity view
disconnect Closing dblink connection to the server
maintain repository Executing support routines
calculate tablespace stats Calculating differential statistics on tablespaces
calculate object stats Calculating differential statistics on database objects. Includes events from Table G.80 and more:
  • merge new extensions version — Processing the data on extension versions

  • merge new relation storage parameters — Processing the data on relation storage parameters

calculate cluster stats Calculating cluster differential statistics
calculate IO stats Calculating cluster I/O differential statistics
calculate SLRU stats Calculating cluster SLRU differential statistics
calculate WAL stats Calculating cluster WAL differential statistics
calculate archiver stats Calculating archiver differential statistics
delete obsolete samples Deleting obsolete baselines and samples

Table G.79. Events of Collecting Statistics on Database Objects

EventDescription
db:dbname collect tables stats Collecting statistics on tables for the dbname database
db:dbname collect indexes stats Collecting statistics on indexes for the dbname database
db:dbname collect functions stats Collecting statistics on functions for the dbname database

Table G.80. Events of Calculating Differences of Statistics on Database Objects

EventDescription
calculate tables stats Calculating differential statistics on tables of all databases
calculate indexes stats Calculating differential statistics on indexes of all databases
calculate functions stats Calculating differential statistics on functions of all databases

G.4.13. Important Notes

When using the pgpro_pwr extension, be aware of the following:

  • Postgres Pro collects execution statistics after the execution is complete. If a single execution of a statement lasts for several samples, it will only affect statistics of the last sample (in which the execution completed). Besides, statistics on statements that are still running are unavailable. Maintenance processes, such as vacuum and checkpointer, will update the statistics only on completion.

  • Resetting any Postgres Pro statistics may affect the accuracy of the next sample.

  • Exclusive locks on relations conflict with calculation of the relation size. If the take_sample() function is unable to acquire a lock for a short period of time (3 seconds), it will fail and no sample will be generated.

FAQ