F.29. pg_overexplain — выгрузка дополнительной информации через команду EXPLAIN #
Модуль pg_overexplain позволяет расширить возможности команды EXPLAIN путём добавления новых параметров, чтобы получить дополнительную информацию в выводе. Модуль в первую очередь предназначен не для общего пользования, а для отладки и усовершенствования планировщика. Поскольку этот модуль отображает внутреннюю информацию о структурах данных планировщика, чтобы разобраться в выводе, может потребоваться обращение к исходному коду. Кроме того, вывод, скорее всего, будет изменяться при любом изменении структур данных.
Чтобы использовать модуль, просто загрузите его в процесс сервера. Это можно сделать в отдельном сеансе:
LOAD 'pg_overexplain';
Также можно загрузить его в некоторые или все сеансы, включив pg_overexplain в переменную session_preload_libraries или shared_preload_libraries в файле postgresql.conf.
F.29.1. EXPLAIN (DEBUG) #
Параметр DEBUG выводит различную информацию из дерева плана, которая обычно не отображается, так как не требуется для обычного пользователя. Для каждого узла плана выводятся поля, описанные ниже. За подробностями об этих полях обратитесь к разделу Plan в nodes/plannodes.h.
Disabled Nodes. Чтобы определить, отключён ли узел, в обычном режиме командаEXPLAINпроверяет, что количество отключённых узлов превышает общее количество нижележащих узлов. Этот параметр выводит необработанное значение счётчика.Parallel Safe. Показывает, безопасно ли для узла дерева плана оказаться ниже узлаGatherилиGather Mergeвне зависимости от того, находится ли этот узел ниже на самом деле.Plan Node ID. Внутренний идентификационный номер, который должен быть уникальным для каждого узла в дереве плана. Используется для координирования параллельных запросов.extParamиallParam. Информация о том, какие числовые параметры влияют на этот узел плана или его дочерние узлы. В текстовом режиме эти поля отображаются, только если возвращаются непустые наборы.
Для каждого запроса параметр DEBUG будет выводить поля, описанные ниже. За подробностями обратитесь к разделу PlannedStmt в nodes/plannodes.h.
Command Type. Например,selectилиupdate.Flags. Разделённый запятыми список имён членов структуры из разделаPlannedStmt, которые принимают логические значения, с заданным значениемtrue. Включает следующие члены структуры:hasReturning,hasModifyingCTE,canSetTag,transientPlan,dependsOnRoleиparallelModeNeeded.Subplans Needing Rewind. Целочисленные идентификаторы вложенных планов, для которых может потребоваться синхронизация со стороны исполнителя.Relation OIDs. OID отношений, от которых зависит этот план.Executor Parameter Types. OID типов для каждого параметра исполнителя (например, когда выбран вложенный цикл и параметр используется, чтобы передать значение для внутреннего сканирования индекса). Не включает параметры, которые передаются пользователем в подготовленном операторе.Parse Location. Положение в строке запроса, передаваемой планировщику, где можно найти текст этого запроса. В некоторых контекстах может иметь значениеUnknown. В остальных случаях может принимать значениеNNN to endдля некоторых целых чиселNNNилиNNN for MMM bytesдля некоторых целых чиселNNNиMMM.
F.29.2. EXPLAIN (RANGE_TABLE) #
Параметр RANGE_TABLE выводит информацию из дерева плана, относящуюся к списку отношений запроса. Записи в этом списке примерно соответствуют элементам, находящимся в предложении FROM, но с рядом исключений. Например, подзапросы, признанные необязательными, могут быть полностью удалены из списка отношений, в то время как расширение наследования добавляет в список записи для дочерних таблиц, не указанных в запросе напрямую.
На элементы списка отношений в рамках плана запроса ссылаются с помощью индекса списка отношений (range table index, RTI). Узлам плана, которые ссылаются на один или несколько RTI, будут назначены соответствующие метки с помощью одного из следующих полей: Scan RTI, Nominal RTI, Exclude Relation RTI и Append RTIs.
Кроме того, запрос в целом может также содержать списки индексов, которые могут требоваться для различных целей. Эти списки будут выводиться один раз для каждого запроса с соответствующими метками Unprunable RTIs или Result RTIs. В текстовом режиме эти поля отображаются только в том случае, если они являются непустыми множествами.
Наконец, что самое важное, параметр RANGE_TABLE будет выводить дамп целого списка отношений запроса. Каждый элемент списка отношений помечен соответствующим индексом, похожим на элемент списка отношений (например, relation, subquery или join), за которым следует содержимое различных полей элемента, обычно не выводимое командой EXPLAIN. Некоторые из этих полей возвращаются только для определённых элементов списка отношений. Например, Eref выводится для всех типов элементов, а CTE Name — только для элементов типа cte.
За подробностями об элементах списка отношений обратитесь к определению RangeTblEntry в nodes/parsenodes.h.
F.29.3. Автор #
Роберт Хаас <rhaas@postgresql.org>
F.29. pg_overexplain — allow EXPLAIN to dump even more details #
The pg_overexplain module extends EXPLAIN with new options that provide additional output. It is mostly intended to assist with debugging of and development of the planner, rather than for general use. Since this module displays internal details of planner data structures, it may be necessary to refer to the source code to make sense of the output. Furthermore, the output is likely to change whenever (and as often as) those data structures change.
To use it, simply load it into the server. You can load it into an individual session:
LOAD 'pg_overexplain';
You can also preload it into some or all sessions by including pg_overexplain in session_preload_libraries or shared_preload_libraries in postgresql.conf.
F.29.1. EXPLAIN (DEBUG) #
The DEBUG option displays miscellaneous information from the plan tree that is not normally shown because it is not expected to be of general interest. For each individual plan node, it will display the following fields. See Plan in nodes/plannodes.h for additional documentation of these fields.
Disabled Nodes. NormalEXPLAINdetermines whether a node is disabled by checking whether the node's count of disabled nodes is larger than the sum of the counts for the underlying nodes. This option shows the raw counter value.Parallel Safe. Indicates whether it would be safe for a plan tree node to appear beneath aGatherorGather Mergenode, regardless of whether it is actually below such a node.Plan Node ID. An internal ID number that should be unique for every node in the plan tree. It is used to coordinate parallel query activity.extParamandallParam. Information about which numbered parameters affect this plan node or its children. In text mode, these fields are only displayed if they are non-empty sets.
Once per query, the DEBUG option will display the following fields. See PlannedStmt in nodes/plannodes.h for additional detail.
Command Type. For example,selectorupdate.Flags. A comma-separated list of Boolean structure member names from thePlannedStmtthat are set totrue. It covers the following structure members:hasReturning,hasModifyingCTE,canSetTag,transientPlan,dependsOnRole,parallelModeNeeded.Subplans Needing Rewind. Integer IDs of subplans that may need to be rewound by the executor.Relation OIDs. OIDs of relations upon which this plan depends.Executor Parameter Types. Type OID for each executor parameter (e.g. when a nested loop is chosen and a parameter is used to pass a value down to an inner index scan). Does not include parameters supplied to a prepared statement by the user.Parse Location. Location within the query string supplied to the planner where this query's text can be found. May beUnknownin some contexts. Otherwise, may beNNN to endfor some integerNNNorNNN for MMM bytesfor some integersNNNandMMM.
F.29.2. EXPLAIN (RANGE_TABLE) #
The RANGE_TABLE option displays information from the plan tree specifically concerning the query's range table. Range table entries correspond roughly to items appearing in the query's FROM clause, but with numerous exceptions. For example, subqueries that are proved unnecessary may be deleted from the range table entirely, while inheritance expansion adds range table entries for child tables that are not named directly in the query.
Range table entries are generally referenced within the query plan by a range table index, or RTI. Plan nodes that reference one or more RTIs will be labelled accordingly, using one of the following fields: Scan RTI, Nominal RTI, Exclude Relation RTI, Append RTIs.
In addition, the query as a whole may maintain lists of range table indexes that are needed for various purposes. These lists will be displayed once per query, labelled as appropriate as Unprunable RTIs or Result RTIs. In text mode, these fields are only displayed if they are non-empty sets.
Finally, but most importantly, the RANGE_TABLE option will display a dump of the query's entire range table. Each range table entry is labelled with the appropriate range table index, the kind of range table entry (e.g. relation, subquery, or join), followed by the contents of various range table entry fields that are not normally part of EXPLAIN output. Some of these fields are only displayed for certain kinds of range table entries. For example, Eref is displayed for all types of range table entries, but CTE Name is displayed only for range table entries of type cte.
For more information about range table entries, see the definition of RangeTblEntry in nodes/parsenodes.h.
F.29.3. Author #
Robert Haas <rhaas@postgresql.org>