PostgreSQL Source Code  git master
explain.c File Reference
#include "postgres.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/createas.h"
#include "commands/defrem.h"
#include "commands/prepare.h"
#include "executor/nodeHash.h"
#include "foreign/fdwapi.h"
#include "jit/jit.h"
#include "nodes/extensible.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteHandler.h"
#include "storage/bufmgr.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/guc_tables.h"
#include "utils/json.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/tuplesort.h"
#include "utils/typcache.h"
#include "utils/xml.h"
Include dependency graph for explain.c:

Go to the source code of this file.

Macros

#define X_OPENING   0
 
#define X_CLOSING   1
 
#define X_CLOSE_IMMEDIATE   2
 
#define X_NOWHITESPACE   4
 

Functions

static void ExplainOneQuery (Query *query, int cursorOptions, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
 
static void ExplainPrintJIT (ExplainState *es, int jit_flags, JitInstrumentation *ji)
 
static void report_triggers (ResultRelInfo *rInfo, bool show_relname, ExplainState *es)
 
static double elapsed_time (instr_time *starttime)
 
static bool ExplainPreScanNode (PlanState *planstate, Bitmapset **rels_used)
 
static void ExplainNode (PlanState *planstate, List *ancestors, const char *relationship, const char *plan_name, ExplainState *es)
 
static void show_plan_tlist (PlanState *planstate, List *ancestors, ExplainState *es)
 
static void show_expression (Node *node, const char *qlabel, PlanState *planstate, List *ancestors, bool useprefix, ExplainState *es)
 
static void show_qual (List *qual, const char *qlabel, PlanState *planstate, List *ancestors, bool useprefix, ExplainState *es)
 
static void show_scan_qual (List *qual, const char *qlabel, PlanState *planstate, List *ancestors, ExplainState *es)
 
static void show_upper_qual (List *qual, const char *qlabel, PlanState *planstate, List *ancestors, ExplainState *es)
 
static void show_sort_keys (SortState *sortstate, List *ancestors, ExplainState *es)
 
static void show_incremental_sort_keys (IncrementalSortState *incrsortstate, List *ancestors, ExplainState *es)
 
static void show_merge_append_keys (MergeAppendState *mstate, List *ancestors, ExplainState *es)
 
static void show_agg_keys (AggState *astate, List *ancestors, ExplainState *es)
 
static void show_grouping_sets (PlanState *planstate, Agg *agg, List *ancestors, ExplainState *es)
 
static void show_grouping_set_keys (PlanState *planstate, Agg *aggnode, Sort *sortnode, List *context, bool useprefix, List *ancestors, ExplainState *es)
 
static void show_group_keys (GroupState *gstate, List *ancestors, ExplainState *es)
 
static void show_sort_group_keys (PlanState *planstate, const char *qlabel, int nkeys, int nPresortedKeys, AttrNumber *keycols, Oid *sortOperators, Oid *collations, bool *nullsFirst, List *ancestors, ExplainState *es)
 
static void show_sortorder_options (StringInfo buf, Node *sortexpr, Oid sortOperator, Oid collation, bool nullsFirst)
 
static void show_tablesample (TableSampleClause *tsc, PlanState *planstate, List *ancestors, ExplainState *es)
 
static void show_sort_info (SortState *sortstate, ExplainState *es)
 
static void show_incremental_sort_info (IncrementalSortState *incrsortstate, ExplainState *es)
 
static void show_hash_info (HashState *hashstate, ExplainState *es)
 
static void show_memoize_info (MemoizeState *mstate, List *ancestors, ExplainState *es)
 
static void show_hashagg_info (AggState *aggstate, ExplainState *es)
 
static void show_tidbitmap_info (BitmapHeapScanState *planstate, ExplainState *es)
 
static void show_instrumentation_count (const char *qlabel, int which, PlanState *planstate, ExplainState *es)
 
static void show_foreignscan_info (ForeignScanState *fsstate, ExplainState *es)
 
static void show_eval_params (Bitmapset *bms_params, ExplainState *es)
 
static const char * explain_get_index_name (Oid indexId)
 
static void show_buffer_usage (ExplainState *es, const BufferUsage *usage, bool planning)
 
static void show_wal_usage (ExplainState *es, const WalUsage *usage)
 
static void ExplainIndexScanDetails (Oid indexid, ScanDirection indexorderdir, ExplainState *es)
 
static void ExplainScanTarget (Scan *plan, ExplainState *es)
 
static void ExplainModifyTarget (ModifyTable *plan, ExplainState *es)
 
static void ExplainTargetRel (Plan *plan, Index rti, ExplainState *es)
 
static void show_modifytable_info (ModifyTableState *mtstate, List *ancestors, ExplainState *es)
 
static void ExplainMemberNodes (PlanState **planstates, int nplans, List *ancestors, ExplainState *es)
 
static void ExplainMissingMembers (int nplans, int nchildren, ExplainState *es)
 
static void ExplainSubPlans (List *plans, List *ancestors, const char *relationship, ExplainState *es)
 
static void ExplainCustomChildren (CustomScanState *css, List *ancestors, ExplainState *es)
 
static ExplainWorkersStateExplainCreateWorkersState (int num_workers)
 
static void ExplainOpenWorker (int n, ExplainState *es)
 
static void ExplainCloseWorker (int n, ExplainState *es)
 
static void ExplainFlushWorkersState (ExplainState *es)
 
static void ExplainProperty (const char *qlabel, const char *unit, const char *value, bool numeric, ExplainState *es)
 
static void ExplainOpenSetAsideGroup (const char *objtype, const char *labelname, bool labeled, int depth, ExplainState *es)
 
static void ExplainSaveGroup (ExplainState *es, int depth, int *state_save)
 
static void ExplainRestoreGroup (ExplainState *es, int depth, int *state_save)
 
static void ExplainDummyGroup (const char *objtype, const char *labelname, ExplainState *es)
 
static void ExplainXMLTag (const char *tagname, int flags, ExplainState *es)
 
static void ExplainIndentText (ExplainState *es)
 
static void ExplainJSONLineEnding (ExplainState *es)
 
static void ExplainYAMLLineStarting (ExplainState *es)
 
static void escape_yaml (StringInfo buf, const char *str)
 
void ExplainQuery (ParseState *pstate, ExplainStmt *stmt, ParamListInfo params, DestReceiver *dest)
 
ExplainStateNewExplainState (void)
 
TupleDesc ExplainResultDesc (ExplainStmt *stmt)
 
void ExplainOneUtility (Node *utilityStmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
 
void ExplainOnePlan (PlannedStmt *plannedstmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, const instr_time *planduration, const BufferUsage *bufusage)
 
static void ExplainPrintSettings (ExplainState *es)
 
void ExplainPrintPlan (ExplainState *es, QueryDesc *queryDesc)
 
void ExplainPrintTriggers (ExplainState *es, QueryDesc *queryDesc)
 
void ExplainPrintJITSummary (ExplainState *es, QueryDesc *queryDesc)
 
void ExplainQueryText (ExplainState *es, QueryDesc *queryDesc)
 
void ExplainQueryParameters (ExplainState *es, ParamListInfo params, int maxlen)
 
static void show_incremental_sort_group_info (IncrementalSortGroupInfo *groupInfo, const char *groupLabel, bool indent, ExplainState *es)
 
void ExplainPropertyList (const char *qlabel, List *data, ExplainState *es)
 
void ExplainPropertyListNested (const char *qlabel, List *data, ExplainState *es)
 
void ExplainPropertyText (const char *qlabel, const char *value, ExplainState *es)
 
void ExplainPropertyInteger (const char *qlabel, const char *unit, int64 value, ExplainState *es)
 
void ExplainPropertyUInteger (const char *qlabel, const char *unit, uint64 value, ExplainState *es)
 
void ExplainPropertyFloat (const char *qlabel, const char *unit, double value, int ndigits, ExplainState *es)
 
void ExplainPropertyBool (const char *qlabel, bool value, ExplainState *es)
 
void ExplainOpenGroup (const char *objtype, const char *labelname, bool labeled, ExplainState *es)
 
void ExplainCloseGroup (const char *objtype, const char *labelname, bool labeled, ExplainState *es)
 
void ExplainBeginOutput (ExplainState *es)
 
void ExplainEndOutput (ExplainState *es)
 
void ExplainSeparatePlans (ExplainState *es)
 

Variables

ExplainOneQuery_hook_type ExplainOneQuery_hook = NULL
 
explain_get_index_name_hook_type explain_get_index_name_hook = NULL
 

Macro Definition Documentation

◆ X_CLOSE_IMMEDIATE

#define X_CLOSE_IMMEDIATE   2

Definition at line 54 of file explain.c.

◆ X_CLOSING

#define X_CLOSING   1

Definition at line 53 of file explain.c.

◆ X_NOWHITESPACE

#define X_NOWHITESPACE   4

Definition at line 55 of file explain.c.

◆ X_OPENING

#define X_OPENING   0

Definition at line 52 of file explain.c.

Function Documentation

◆ elapsed_time()

static double elapsed_time ( instr_time starttime)
static

Definition at line 1073 of file explain.c.

1074 {
1075  instr_time endtime;
1076 
1077  INSTR_TIME_SET_CURRENT(endtime);
1078  INSTR_TIME_SUBTRACT(endtime, *starttime);
1079  return INSTR_TIME_GET_DOUBLE(endtime);
1080 }
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:89
#define INSTR_TIME_GET_DOUBLE(t)
Definition: instr_time.h:132
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:103
struct timespec instr_time
Definition: instr_time.h:83

References INSTR_TIME_GET_DOUBLE, INSTR_TIME_SET_CURRENT, and INSTR_TIME_SUBTRACT.

Referenced by ExplainOnePlan(), and IsCheckpointOnSchedule().

◆ escape_yaml()

static void escape_yaml ( StringInfo  buf,
const char *  str 
)
static

Definition at line 5040 of file explain.c.

5041 {
5042  escape_json(buf, str);
5043 }
void escape_json(StringInfo buf, const char *str)
Definition: json.c:1271
static char * buf
Definition: pg_test_fsync.c:67

References buf, escape_json(), and generate_unaccent_rules::str.

Referenced by ExplainDummyGroup(), ExplainProperty(), ExplainPropertyList(), and ExplainPropertyListNested().

◆ explain_get_index_name()

static const char * explain_get_index_name ( Oid  indexId)
static

Definition at line 3507 of file explain.c.

3508 {
3509  const char *result;
3510 
3512  result = (*explain_get_index_name_hook) (indexId);
3513  else
3514  result = NULL;
3515  if (result == NULL)
3516  {
3517  /* default behavior: look it up in the catalogs */
3518  result = get_rel_name(indexId);
3519  if (result == NULL)
3520  elog(ERROR, "cache lookup failed for index %u", indexId);
3521  }
3522  return result;
3523 }
#define ERROR
Definition: elog.h:35
explain_get_index_name_hook_type explain_get_index_name_hook
Definition: explain.c:48
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910

References elog(), ERROR, explain_get_index_name_hook, and get_rel_name().

Referenced by ExplainIndexScanDetails(), and ExplainNode().

◆ ExplainBeginOutput()

void ExplainBeginOutput ( ExplainState es)

Definition at line 4864 of file explain.c.

4865 {
4866  switch (es->format)
4867  {
4868  case EXPLAIN_FORMAT_TEXT:
4869  /* nothing to do */
4870  break;
4871 
4872  case EXPLAIN_FORMAT_XML:
4874  "<explain xmlns=\"http://www.postgresql.org/2009/explain\">\n");
4875  es->indent++;
4876  break;
4877 
4878  case EXPLAIN_FORMAT_JSON:
4879  /* top-level structure is an array of plans */
4880  appendStringInfoChar(es->str, '[');
4881  es->grouping_stack = lcons_int(0, es->grouping_stack);
4882  es->indent++;
4883  break;
4884 
4885  case EXPLAIN_FORMAT_YAML:
4886  es->grouping_stack = lcons_int(0, es->grouping_stack);
4887  break;
4888  }
4889 }
@ EXPLAIN_FORMAT_XML
Definition: explain.h:23
@ EXPLAIN_FORMAT_YAML
Definition: explain.h:25
@ EXPLAIN_FORMAT_TEXT
Definition: explain.h:22
@ EXPLAIN_FORMAT_JSON
Definition: explain.h:24
List * lcons_int(int datum, List *list)
Definition: list.c:512
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
List * grouping_stack
Definition: explain.h:52
StringInfo str
Definition: explain.h:39
ExplainFormat format
Definition: explain.h:49
int indent
Definition: explain.h:51

References appendStringInfoChar(), appendStringInfoString(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, lcons_int(), and ExplainState::str.

Referenced by explain_ExecutorEnd(), and ExplainQuery().

◆ ExplainCloseGroup()

void ExplainCloseGroup ( const char *  objtype,
const char *  labelname,
bool  labeled,
ExplainState es 
)

Definition at line 4671 of file explain.c.

4673 {
4674  switch (es->format)
4675  {
4676  case EXPLAIN_FORMAT_TEXT:
4677  /* nothing to do */
4678  break;
4679 
4680  case EXPLAIN_FORMAT_XML:
4681  es->indent--;
4682  ExplainXMLTag(objtype, X_CLOSING, es);
4683  break;
4684 
4685  case EXPLAIN_FORMAT_JSON:
4686  es->indent--;
4687  appendStringInfoChar(es->str, '\n');
4688  appendStringInfoSpaces(es->str, 2 * es->indent);
4689  appendStringInfoChar(es->str, labeled ? '}' : ']');
4691  break;
4692 
4693  case EXPLAIN_FORMAT_YAML:
4694  es->indent--;
4696  break;
4697  }
4698 }
static void ExplainXMLTag(const char *tagname, int flags, ExplainState *es)
Definition: explain.c:4953
#define X_CLOSING
Definition: explain.c:53
List * list_delete_first(List *list)
Definition: list.c:942
void appendStringInfoSpaces(StringInfo str, int count)
Definition: stringinfo.c:206

References appendStringInfoChar(), appendStringInfoSpaces(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainXMLTag(), ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, list_delete_first(), ExplainState::str, and X_CLOSING.

Referenced by ExplainFlushWorkersState(), ExplainNode(), ExplainOnePlan(), ExplainPrintJIT(), ExplainPrintSettings(), ExplainPrintTriggers(), report_triggers(), show_grouping_set_keys(), show_grouping_sets(), show_incremental_sort_group_info(), and show_modifytable_info().

◆ ExplainCloseWorker()

static void ExplainCloseWorker ( int  n,
ExplainState es 
)
static

Definition at line 4301 of file explain.c.

4302 {
4303  ExplainWorkersState *wstate = es->workers_state;
4304 
4305  Assert(wstate);
4306  Assert(n >= 0 && n < wstate->num_workers);
4307  Assert(wstate->worker_inited[n]);
4308 
4309  /*
4310  * Save formatting state in case we do another ExplainOpenWorker(), then
4311  * pop the formatting stack.
4312  */
4313  ExplainSaveGroup(es, 2, &wstate->worker_state_save[n]);
4314 
4315  /*
4316  * In TEXT format, if we didn't actually produce any output line(s) then
4317  * truncate off the partial line emitted by ExplainOpenWorker. (This is
4318  * to avoid bogus output if, say, show_buffer_usage chooses not to print
4319  * anything for the worker.) Also fix up the indent level.
4320  */
4321  if (es->format == EXPLAIN_FORMAT_TEXT)
4322  {
4323  while (es->str->len > 0 && es->str->data[es->str->len - 1] != '\n')
4324  es->str->data[--(es->str->len)] = '\0';
4325 
4326  es->indent--;
4327  }
4328 
4329  /* Restore prior output buffer pointer */
4330  es->str = wstate->prev_str;
4331 }
static void ExplainSaveGroup(ExplainState *es, int depth, int *state_save)
Definition: explain.c:4757
Assert(fmt[strlen(fmt) - 1] !='\n')
ExplainWorkersState * workers_state
Definition: explain.h:61
bool * worker_inited
Definition: explain.h:31
int * worker_state_save
Definition: explain.h:33
StringInfo prev_str
Definition: explain.h:34

References Assert(), StringInfoData::data, EXPLAIN_FORMAT_TEXT, ExplainSaveGroup(), ExplainState::format, ExplainState::indent, StringInfoData::len, ExplainWorkersState::prev_str, ExplainState::str, ExplainWorkersState::worker_inited, ExplainWorkersState::worker_state_save, and ExplainState::workers_state.

Referenced by ExplainNode(), show_hashagg_info(), show_incremental_sort_info(), show_memoize_info(), and show_sort_info().

◆ ExplainCreateWorkersState()

static ExplainWorkersState * ExplainCreateWorkersState ( int  num_workers)
static

Definition at line 4222 of file explain.c.

4223 {
4224  ExplainWorkersState *wstate;
4225 
4226  wstate = (ExplainWorkersState *) palloc(sizeof(ExplainWorkersState));
4227  wstate->num_workers = num_workers;
4228  wstate->worker_inited = (bool *) palloc0(num_workers * sizeof(bool));
4229  wstate->worker_str = (StringInfoData *)
4230  palloc0(num_workers * sizeof(StringInfoData));
4231  wstate->worker_state_save = (int *) palloc(num_workers * sizeof(int));
4232  return wstate;
4233 }
void * palloc0(Size size)
Definition: mcxt.c:1230
void * palloc(Size size)
Definition: mcxt.c:1199
StringInfoData * worker_str
Definition: explain.h:32

References ExplainWorkersState::num_workers, palloc(), palloc0(), ExplainWorkersState::worker_inited, ExplainWorkersState::worker_state_save, and ExplainWorkersState::worker_str.

Referenced by ExplainNode().

◆ ExplainCustomChildren()

static void ExplainCustomChildren ( CustomScanState css,
List ancestors,
ExplainState es 
)
static

Definition at line 4200 of file explain.c.

4201 {
4202  ListCell *cell;
4203  const char *label =
4204  (list_length(css->custom_ps) != 1 ? "children" : "child");
4205 
4206  foreach(cell, css->custom_ps)
4207  ExplainNode((PlanState *) lfirst(cell), ancestors, label, NULL, es);
4208 }
static void ExplainNode(PlanState *planstate, List *ancestors, const char *relationship, const char *plan_name, ExplainState *es)
Definition: explain.c:1167
static char * label
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
List * custom_ps
Definition: execnodes.h:1963

References CustomScanState::custom_ps, ExplainNode(), label, lfirst, and list_length().

Referenced by ExplainNode().

◆ ExplainDummyGroup()

static void ExplainDummyGroup ( const char *  objtype,
const char *  labelname,
ExplainState es 
)
static

Definition at line 4818 of file explain.c.

4819 {
4820  switch (es->format)
4821  {
4822  case EXPLAIN_FORMAT_TEXT:
4823  /* nothing to do */
4824  break;
4825 
4826  case EXPLAIN_FORMAT_XML:
4827  ExplainXMLTag(objtype, X_CLOSE_IMMEDIATE, es);
4828  break;
4829 
4830  case EXPLAIN_FORMAT_JSON:
4832  appendStringInfoSpaces(es->str, 2 * es->indent);
4833  if (labelname)
4834  {
4835  escape_json(es->str, labelname);
4836  appendStringInfoString(es->str, ": ");
4837  }
4838  escape_json(es->str, objtype);
4839  break;
4840 
4841  case EXPLAIN_FORMAT_YAML:
4843  if (labelname)
4844  {
4845  escape_yaml(es->str, labelname);
4846  appendStringInfoString(es->str, ": ");
4847  }
4848  else
4849  {
4850  appendStringInfoString(es->str, "- ");
4851  }
4852  escape_yaml(es->str, objtype);
4853  break;
4854  }
4855 }
#define X_CLOSE_IMMEDIATE
Definition: explain.c:54
static void ExplainYAMLLineStarting(ExplainState *es)
Definition: explain.c:5015
static void ExplainJSONLineEnding(ExplainState *es)
Definition: explain.c:4995
static void escape_yaml(StringInfo buf, const char *str)
Definition: explain.c:5040

References appendStringInfoSpaces(), appendStringInfoString(), escape_json(), escape_yaml(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainJSONLineEnding(), ExplainXMLTag(), ExplainYAMLLineStarting(), ExplainState::format, ExplainState::indent, ExplainState::str, and X_CLOSE_IMMEDIATE.

Referenced by ExplainOneUtility().

◆ ExplainEndOutput()

void ExplainEndOutput ( ExplainState es)

Definition at line 4895 of file explain.c.

4896 {
4897  switch (es->format)
4898  {
4899  case EXPLAIN_FORMAT_TEXT:
4900  /* nothing to do */
4901  break;
4902 
4903  case EXPLAIN_FORMAT_XML:
4904  es->indent--;
4905  appendStringInfoString(es->str, "</explain>");
4906  break;
4907 
4908  case EXPLAIN_FORMAT_JSON:
4909  es->indent--;
4910  appendStringInfoString(es->str, "\n]");
4912  break;
4913 
4914  case EXPLAIN_FORMAT_YAML:
4916  break;
4917  }
4918 }

References appendStringInfoString(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, list_delete_first(), and ExplainState::str.

Referenced by explain_ExecutorEnd(), and ExplainQuery().

◆ ExplainFlushWorkersState()

static void ExplainFlushWorkersState ( ExplainState es)
static

Definition at line 4337 of file explain.c.

4338 {
4339  ExplainWorkersState *wstate = es->workers_state;
4340 
4341  ExplainOpenGroup("Workers", "Workers", false, es);
4342  for (int i = 0; i < wstate->num_workers; i++)
4343  {
4344  if (wstate->worker_inited[i])
4345  {
4346  /* This must match previous ExplainOpenSetAsideGroup call */
4347  ExplainOpenGroup("Worker", NULL, true, es);
4348  appendStringInfoString(es->str, wstate->worker_str[i].data);
4349  ExplainCloseGroup("Worker", NULL, true, es);
4350 
4351  pfree(wstate->worker_str[i].data);
4352  }
4353  }
4354  ExplainCloseGroup("Workers", "Workers", false, es);
4355 
4356  pfree(wstate->worker_inited);
4357  pfree(wstate->worker_str);
4358  pfree(wstate->worker_state_save);
4359  pfree(wstate);
4360 }
void ExplainOpenGroup(const char *objtype, const char *labelname, bool labeled, ExplainState *es)
Definition: explain.c:4608
void ExplainCloseGroup(const char *objtype, const char *labelname, bool labeled, ExplainState *es)
Definition: explain.c:4671
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1306

References appendStringInfoString(), StringInfoData::data, ExplainCloseGroup(), ExplainOpenGroup(), i, ExplainWorkersState::num_workers, pfree(), ExplainState::str, ExplainWorkersState::worker_inited, ExplainWorkersState::worker_state_save, ExplainWorkersState::worker_str, and ExplainState::workers_state.

Referenced by ExplainNode().

◆ ExplainIndentText()

◆ ExplainIndexScanDetails()

static void ExplainIndexScanDetails ( Oid  indexid,
ScanDirection  indexorderdir,
ExplainState es 
)
static

Definition at line 3729 of file explain.c.

3731 {
3732  const char *indexname = explain_get_index_name(indexid);
3733 
3734  if (es->format == EXPLAIN_FORMAT_TEXT)
3735  {
3736  if (ScanDirectionIsBackward(indexorderdir))
3737  appendStringInfoString(es->str, " Backward");
3738  appendStringInfo(es->str, " using %s", quote_identifier(indexname));
3739  }
3740  else
3741  {
3742  const char *scandir;
3743 
3744  switch (indexorderdir)
3745  {
3746  case BackwardScanDirection:
3747  scandir = "Backward";
3748  break;
3750  scandir = "NoMovement";
3751  break;
3752  case ForwardScanDirection:
3753  scandir = "Forward";
3754  break;
3755  default:
3756  scandir = "???";
3757  break;
3758  }
3759  ExplainPropertyText("Scan Direction", scandir, es);
3760  ExplainPropertyText("Index Name", indexname, es);
3761  }
3762 }
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
Definition: explain.c:4543
static const char * explain_get_index_name(Oid indexId)
Definition: explain.c:3507
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11529
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:41
@ NoMovementScanDirection
Definition: sdir.h:25
@ BackwardScanDirection
Definition: sdir.h:24
@ ForwardScanDirection
Definition: sdir.h:26
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91

References appendStringInfo(), appendStringInfoString(), BackwardScanDirection, EXPLAIN_FORMAT_TEXT, explain_get_index_name(), ExplainPropertyText(), ExplainState::format, ForwardScanDirection, NoMovementScanDirection, quote_identifier(), ScanDirectionIsBackward, and ExplainState::str.

Referenced by ExplainNode().

◆ ExplainJSONLineEnding()

static void ExplainJSONLineEnding ( ExplainState es)
static

◆ ExplainMemberNodes()

static void ExplainMemberNodes ( PlanState **  planstates,
int  nplans,
List ancestors,
ExplainState es 
)
static

Definition at line 4125 of file explain.c.

4127 {
4128  int j;
4129 
4130  for (j = 0; j < nplans; j++)
4131  ExplainNode(planstates[j], ancestors,
4132  "Member", NULL, es);
4133 }
int j
Definition: isn.c:74

References ExplainNode(), and j.

Referenced by ExplainNode().

◆ ExplainMissingMembers()

static void ExplainMissingMembers ( int  nplans,
int  nchildren,
ExplainState es 
)
static

Definition at line 4143 of file explain.c.

4144 {
4145  if (nplans < nchildren || es->format != EXPLAIN_FORMAT_TEXT)
4146  ExplainPropertyInteger("Subplans Removed", NULL,
4147  nchildren - nplans, es);
4148 }
void ExplainPropertyInteger(const char *qlabel, const char *unit, int64 value, ExplainState *es)
Definition: explain.c:4552
static char format

References EXPLAIN_FORMAT_TEXT, ExplainPropertyInteger(), and format.

Referenced by ExplainNode().

◆ ExplainModifyTarget()

static void ExplainModifyTarget ( ModifyTable plan,
ExplainState es 
)
static

Definition at line 3781 of file explain.c.

3782 {
3783  ExplainTargetRel((Plan *) plan, plan->nominalRelation, es);
3784 }
static void ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
Definition: explain.c:3790

References ExplainTargetRel(), and ModifyTable::nominalRelation.

Referenced by ExplainNode().

◆ ExplainNode()

static void ExplainNode ( PlanState planstate,
List ancestors,
const char *  relationship,
const char *  plan_name,
ExplainState es 
)
static

Definition at line 1167 of file explain.c.

1170 {
1171  Plan *plan = planstate->plan;
1172  const char *pname; /* node type name for text output */
1173  const char *sname; /* node type name for non-text output */
1174  const char *strategy = NULL;
1175  const char *partialmode = NULL;
1176  const char *operation = NULL;
1177  const char *custom_name = NULL;
1178  ExplainWorkersState *save_workers_state = es->workers_state;
1179  int save_indent = es->indent;
1180  bool haschildren;
1181 
1182  /*
1183  * Prepare per-worker output buffers, if needed. We'll append the data in
1184  * these to the main output string further down.
1185  */
1186  if (planstate->worker_instrument && es->analyze && !es->hide_workers)
1188  else
1189  es->workers_state = NULL;
1190 
1191  /* Identify plan node type, and print generic details */
1192  switch (nodeTag(plan))
1193  {
1194  case T_Result:
1195  pname = sname = "Result";
1196  break;
1197  case T_ProjectSet:
1198  pname = sname = "ProjectSet";
1199  break;
1200  case T_ModifyTable:
1201  sname = "ModifyTable";
1202  switch (((ModifyTable *) plan)->operation)
1203  {
1204  case CMD_INSERT:
1205  pname = operation = "Insert";
1206  break;
1207  case CMD_UPDATE:
1208  pname = operation = "Update";
1209  break;
1210  case CMD_DELETE:
1211  pname = operation = "Delete";
1212  break;
1213  case CMD_MERGE:
1214  pname = operation = "Merge";
1215  break;
1216  default:
1217  pname = "???";
1218  break;
1219  }
1220  break;
1221  case T_Append:
1222  pname = sname = "Append";
1223  break;
1224  case T_MergeAppend:
1225  pname = sname = "Merge Append";
1226  break;
1227  case T_RecursiveUnion:
1228  pname = sname = "Recursive Union";
1229  break;
1230  case T_BitmapAnd:
1231  pname = sname = "BitmapAnd";
1232  break;
1233  case T_BitmapOr:
1234  pname = sname = "BitmapOr";
1235  break;
1236  case T_NestLoop:
1237  pname = sname = "Nested Loop";
1238  break;
1239  case T_MergeJoin:
1240  pname = "Merge"; /* "Join" gets added by jointype switch */
1241  sname = "Merge Join";
1242  break;
1243  case T_HashJoin:
1244  pname = "Hash"; /* "Join" gets added by jointype switch */
1245  sname = "Hash Join";
1246  break;
1247  case T_SeqScan:
1248  pname = sname = "Seq Scan";
1249  break;
1250  case T_SampleScan:
1251  pname = sname = "Sample Scan";
1252  break;
1253  case T_Gather:
1254  pname = sname = "Gather";
1255  break;
1256  case T_GatherMerge:
1257  pname = sname = "Gather Merge";
1258  break;
1259  case T_IndexScan:
1260  pname = sname = "Index Scan";
1261  break;
1262  case T_IndexOnlyScan:
1263  pname = sname = "Index Only Scan";
1264  break;
1265  case T_BitmapIndexScan:
1266  pname = sname = "Bitmap Index Scan";
1267  break;
1268  case T_BitmapHeapScan:
1269  pname = sname = "Bitmap Heap Scan";
1270  break;
1271  case T_TidScan:
1272  pname = sname = "Tid Scan";
1273  break;
1274  case T_TidRangeScan:
1275  pname = sname = "Tid Range Scan";
1276  break;
1277  case T_SubqueryScan:
1278  pname = sname = "Subquery Scan";
1279  break;
1280  case T_FunctionScan:
1281  pname = sname = "Function Scan";
1282  break;
1283  case T_TableFuncScan:
1284  pname = sname = "Table Function Scan";
1285  break;
1286  case T_ValuesScan:
1287  pname = sname = "Values Scan";
1288  break;
1289  case T_CteScan:
1290  pname = sname = "CTE Scan";
1291  break;
1292  case T_NamedTuplestoreScan:
1293  pname = sname = "Named Tuplestore Scan";
1294  break;
1295  case T_WorkTableScan:
1296  pname = sname = "WorkTable Scan";
1297  break;
1298  case T_ForeignScan:
1299  sname = "Foreign Scan";
1300  switch (((ForeignScan *) plan)->operation)
1301  {
1302  case CMD_SELECT:
1303  pname = "Foreign Scan";
1304  operation = "Select";
1305  break;
1306  case CMD_INSERT:
1307  pname = "Foreign Insert";
1308  operation = "Insert";
1309  break;
1310  case CMD_UPDATE:
1311  pname = "Foreign Update";
1312  operation = "Update";
1313  break;
1314  case CMD_DELETE:
1315  pname = "Foreign Delete";
1316  operation = "Delete";
1317  break;
1318  default:
1319  pname = "???";
1320  break;
1321  }
1322  break;
1323  case T_CustomScan:
1324  sname = "Custom Scan";
1325  custom_name = ((CustomScan *) plan)->methods->CustomName;
1326  if (custom_name)
1327  pname = psprintf("Custom Scan (%s)", custom_name);
1328  else
1329  pname = sname;
1330  break;
1331  case T_Material:
1332  pname = sname = "Materialize";
1333  break;
1334  case T_Memoize:
1335  pname = sname = "Memoize";
1336  break;
1337  case T_Sort:
1338  pname = sname = "Sort";
1339  break;
1340  case T_IncrementalSort:
1341  pname = sname = "Incremental Sort";
1342  break;
1343  case T_Group:
1344  pname = sname = "Group";
1345  break;
1346  case T_Agg:
1347  {
1348  Agg *agg = (Agg *) plan;
1349 
1350  sname = "Aggregate";
1351  switch (agg->aggstrategy)
1352  {
1353  case AGG_PLAIN:
1354  pname = "Aggregate";
1355  strategy = "Plain";
1356  break;
1357  case AGG_SORTED:
1358  pname = "GroupAggregate";
1359  strategy = "Sorted";
1360  break;
1361  case AGG_HASHED:
1362  pname = "HashAggregate";
1363  strategy = "Hashed";
1364  break;
1365  case AGG_MIXED:
1366  pname = "MixedAggregate";
1367  strategy = "Mixed";
1368  break;
1369  default:
1370  pname = "Aggregate ???";
1371  strategy = "???";
1372  break;
1373  }
1374 
1375  if (DO_AGGSPLIT_SKIPFINAL(agg->aggsplit))
1376  {
1377  partialmode = "Partial";
1378  pname = psprintf("%s %s", partialmode, pname);
1379  }
1380  else if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
1381  {
1382  partialmode = "Finalize";
1383  pname = psprintf("%s %s", partialmode, pname);
1384  }
1385  else
1386  partialmode = "Simple";
1387  }
1388  break;
1389  case T_WindowAgg:
1390  pname = sname = "WindowAgg";
1391  break;
1392  case T_Unique:
1393  pname = sname = "Unique";
1394  break;
1395  case T_SetOp:
1396  sname = "SetOp";
1397  switch (((SetOp *) plan)->strategy)
1398  {
1399  case SETOP_SORTED:
1400  pname = "SetOp";
1401  strategy = "Sorted";
1402  break;
1403  case SETOP_HASHED:
1404  pname = "HashSetOp";
1405  strategy = "Hashed";
1406  break;
1407  default:
1408  pname = "SetOp ???";
1409  strategy = "???";
1410  break;
1411  }
1412  break;
1413  case T_LockRows:
1414  pname = sname = "LockRows";
1415  break;
1416  case T_Limit:
1417  pname = sname = "Limit";
1418  break;
1419  case T_Hash:
1420  pname = sname = "Hash";
1421  break;
1422  default:
1423  pname = sname = "???";
1424  break;
1425  }
1426 
1427  ExplainOpenGroup("Plan",
1428  relationship ? NULL : "Plan",
1429  true, es);
1430 
1431  if (es->format == EXPLAIN_FORMAT_TEXT)
1432  {
1433  if (plan_name)
1434  {
1435  ExplainIndentText(es);
1436  appendStringInfo(es->str, "%s\n", plan_name);
1437  es->indent++;
1438  }
1439  if (es->indent)
1440  {
1441  ExplainIndentText(es);
1442  appendStringInfoString(es->str, "-> ");
1443  es->indent += 2;
1444  }
1445  if (plan->parallel_aware)
1446  appendStringInfoString(es->str, "Parallel ");
1447  if (plan->async_capable)
1448  appendStringInfoString(es->str, "Async ");
1449  appendStringInfoString(es->str, pname);
1450  es->indent++;
1451  }
1452  else
1453  {
1454  ExplainPropertyText("Node Type", sname, es);
1455  if (strategy)
1456  ExplainPropertyText("Strategy", strategy, es);
1457  if (partialmode)
1458  ExplainPropertyText("Partial Mode", partialmode, es);
1459  if (operation)
1460  ExplainPropertyText("Operation", operation, es);
1461  if (relationship)
1462  ExplainPropertyText("Parent Relationship", relationship, es);
1463  if (plan_name)
1464  ExplainPropertyText("Subplan Name", plan_name, es);
1465  if (custom_name)
1466  ExplainPropertyText("Custom Plan Provider", custom_name, es);
1467  ExplainPropertyBool("Parallel Aware", plan->parallel_aware, es);
1468  ExplainPropertyBool("Async Capable", plan->async_capable, es);
1469  }
1470 
1471  switch (nodeTag(plan))
1472  {
1473  case T_SeqScan:
1474  case T_SampleScan:
1475  case T_BitmapHeapScan:
1476  case T_TidScan:
1477  case T_TidRangeScan:
1478  case T_SubqueryScan:
1479  case T_FunctionScan:
1480  case T_TableFuncScan:
1481  case T_ValuesScan:
1482  case T_CteScan:
1483  case T_WorkTableScan:
1484  ExplainScanTarget((Scan *) plan, es);
1485  break;
1486  case T_ForeignScan:
1487  case T_CustomScan:
1488  if (((Scan *) plan)->scanrelid > 0)
1489  ExplainScanTarget((Scan *) plan, es);
1490  break;
1491  case T_IndexScan:
1492  {
1493  IndexScan *indexscan = (IndexScan *) plan;
1494 
1495  ExplainIndexScanDetails(indexscan->indexid,
1496  indexscan->indexorderdir,
1497  es);
1498  ExplainScanTarget((Scan *) indexscan, es);
1499  }
1500  break;
1501  case T_IndexOnlyScan:
1502  {
1503  IndexOnlyScan *indexonlyscan = (IndexOnlyScan *) plan;
1504 
1505  ExplainIndexScanDetails(indexonlyscan->indexid,
1506  indexonlyscan->indexorderdir,
1507  es);
1508  ExplainScanTarget((Scan *) indexonlyscan, es);
1509  }
1510  break;
1511  case T_BitmapIndexScan:
1512  {
1513  BitmapIndexScan *bitmapindexscan = (BitmapIndexScan *) plan;
1514  const char *indexname =
1515  explain_get_index_name(bitmapindexscan->indexid);
1516 
1517  if (es->format == EXPLAIN_FORMAT_TEXT)
1518  appendStringInfo(es->str, " on %s",
1519  quote_identifier(indexname));
1520  else
1521  ExplainPropertyText("Index Name", indexname, es);
1522  }
1523  break;
1524  case T_ModifyTable:
1525  ExplainModifyTarget((ModifyTable *) plan, es);
1526  break;
1527  case T_NestLoop:
1528  case T_MergeJoin:
1529  case T_HashJoin:
1530  {
1531  const char *jointype;
1532 
1533  switch (((Join *) plan)->jointype)
1534  {
1535  case JOIN_INNER:
1536  jointype = "Inner";
1537  break;
1538  case JOIN_LEFT:
1539  jointype = "Left";
1540  break;
1541  case JOIN_FULL:
1542  jointype = "Full";
1543  break;
1544  case JOIN_RIGHT:
1545  jointype = "Right";
1546  break;
1547  case JOIN_SEMI:
1548  jointype = "Semi";
1549  break;
1550  case JOIN_ANTI:
1551  jointype = "Anti";
1552  break;
1553  default:
1554  jointype = "???";
1555  break;
1556  }
1557  if (es->format == EXPLAIN_FORMAT_TEXT)
1558  {
1559  /*
1560  * For historical reasons, the join type is interpolated
1561  * into the node type name...
1562  */
1563  if (((Join *) plan)->jointype != JOIN_INNER)
1564  appendStringInfo(es->str, " %s Join", jointype);
1565  else if (!IsA(plan, NestLoop))
1566  appendStringInfoString(es->str, " Join");
1567  }
1568  else
1569  ExplainPropertyText("Join Type", jointype, es);
1570  }
1571  break;
1572  case T_SetOp:
1573  {
1574  const char *setopcmd;
1575 
1576  switch (((SetOp *) plan)->cmd)
1577  {
1578  case SETOPCMD_INTERSECT:
1579  setopcmd = "Intersect";
1580  break;
1582  setopcmd = "Intersect All";
1583  break;
1584  case SETOPCMD_EXCEPT:
1585  setopcmd = "Except";
1586  break;
1587  case SETOPCMD_EXCEPT_ALL:
1588  setopcmd = "Except All";
1589  break;
1590  default:
1591  setopcmd = "???";
1592  break;
1593  }
1594  if (es->format == EXPLAIN_FORMAT_TEXT)
1595  appendStringInfo(es->str, " %s", setopcmd);
1596  else
1597  ExplainPropertyText("Command", setopcmd, es);
1598  }
1599  break;
1600  default:
1601  break;
1602  }
1603 
1604  if (es->costs)
1605  {
1606  if (es->format == EXPLAIN_FORMAT_TEXT)
1607  {
1608  appendStringInfo(es->str, " (cost=%.2f..%.2f rows=%.0f width=%d)",
1609  plan->startup_cost, plan->total_cost,
1610  plan->plan_rows, plan->plan_width);
1611  }
1612  else
1613  {
1614  ExplainPropertyFloat("Startup Cost", NULL, plan->startup_cost,
1615  2, es);
1616  ExplainPropertyFloat("Total Cost", NULL, plan->total_cost,
1617  2, es);
1618  ExplainPropertyFloat("Plan Rows", NULL, plan->plan_rows,
1619  0, es);
1620  ExplainPropertyInteger("Plan Width", NULL, plan->plan_width,
1621  es);
1622  }
1623  }
1624 
1625  /*
1626  * We have to forcibly clean up the instrumentation state because we
1627  * haven't done ExecutorEnd yet. This is pretty grotty ...
1628  *
1629  * Note: contrib/auto_explain could cause instrumentation to be set up
1630  * even though we didn't ask for it here. Be careful not to print any
1631  * instrumentation results the user didn't ask for. But we do the
1632  * InstrEndLoop call anyway, if possible, to reduce the number of cases
1633  * auto_explain has to contend with.
1634  */
1635  if (planstate->instrument)
1636  InstrEndLoop(planstate->instrument);
1637 
1638  if (es->analyze &&
1639  planstate->instrument && planstate->instrument->nloops > 0)
1640  {
1641  double nloops = planstate->instrument->nloops;
1642  double startup_ms = 1000.0 * planstate->instrument->startup / nloops;
1643  double total_ms = 1000.0 * planstate->instrument->total / nloops;
1644  double rows = planstate->instrument->ntuples / nloops;
1645 
1646  if (es->format == EXPLAIN_FORMAT_TEXT)
1647  {
1648  if (es->timing)
1649  appendStringInfo(es->str,
1650  " (actual time=%.3f..%.3f rows=%.0f loops=%.0f)",
1651  startup_ms, total_ms, rows, nloops);
1652  else
1653  appendStringInfo(es->str,
1654  " (actual rows=%.0f loops=%.0f)",
1655  rows, nloops);
1656  }
1657  else
1658  {
1659  if (es->timing)
1660  {
1661  ExplainPropertyFloat("Actual Startup Time", "ms", startup_ms,
1662  3, es);
1663  ExplainPropertyFloat("Actual Total Time", "ms", total_ms,
1664  3, es);
1665  }
1666  ExplainPropertyFloat("Actual Rows", NULL, rows, 0, es);
1667  ExplainPropertyFloat("Actual Loops", NULL, nloops, 0, es);
1668  }
1669  }
1670  else if (es->analyze)
1671  {
1672  if (es->format == EXPLAIN_FORMAT_TEXT)
1673  appendStringInfoString(es->str, " (never executed)");
1674  else
1675  {
1676  if (es->timing)
1677  {
1678  ExplainPropertyFloat("Actual Startup Time", "ms", 0.0, 3, es);
1679  ExplainPropertyFloat("Actual Total Time", "ms", 0.0, 3, es);
1680  }
1681  ExplainPropertyFloat("Actual Rows", NULL, 0.0, 0, es);
1682  ExplainPropertyFloat("Actual Loops", NULL, 0.0, 0, es);
1683  }
1684  }
1685 
1686  /* in text format, first line ends here */
1687  if (es->format == EXPLAIN_FORMAT_TEXT)
1688  appendStringInfoChar(es->str, '\n');
1689 
1690  /* prepare per-worker general execution details */
1691  if (es->workers_state && es->verbose)
1692  {
1693  WorkerInstrumentation *w = planstate->worker_instrument;
1694 
1695  for (int n = 0; n < w->num_workers; n++)
1696  {
1697  Instrumentation *instrument = &w->instrument[n];
1698  double nloops = instrument->nloops;
1699  double startup_ms;
1700  double total_ms;
1701  double rows;
1702 
1703  if (nloops <= 0)
1704  continue;
1705  startup_ms = 1000.0 * instrument->startup / nloops;
1706  total_ms = 1000.0 * instrument->total / nloops;
1707  rows = instrument->ntuples / nloops;
1708 
1709  ExplainOpenWorker(n, es);
1710 
1711  if (es->format == EXPLAIN_FORMAT_TEXT)
1712  {
1713  ExplainIndentText(es);
1714  if (es->timing)
1715  appendStringInfo(es->str,
1716  "actual time=%.3f..%.3f rows=%.0f loops=%.0f\n",
1717  startup_ms, total_ms, rows, nloops);
1718  else
1719  appendStringInfo(es->str,
1720  "actual rows=%.0f loops=%.0f\n",
1721  rows, nloops);
1722  }
1723  else
1724  {
1725  if (es->timing)
1726  {
1727  ExplainPropertyFloat("Actual Startup Time", "ms",
1728  startup_ms, 3, es);
1729  ExplainPropertyFloat("Actual Total Time", "ms",
1730  total_ms, 3, es);
1731  }
1732  ExplainPropertyFloat("Actual Rows", NULL, rows, 0, es);
1733  ExplainPropertyFloat("Actual Loops", NULL, nloops, 0, es);
1734  }
1735 
1736  ExplainCloseWorker(n, es);
1737  }
1738  }
1739 
1740  /* target list */
1741  if (es->verbose)
1742  show_plan_tlist(planstate, ancestors, es);
1743 
1744  /* unique join */
1745  switch (nodeTag(plan))
1746  {
1747  case T_NestLoop:
1748  case T_MergeJoin:
1749  case T_HashJoin:
1750  /* try not to be too chatty about this in text mode */
1751  if (es->format != EXPLAIN_FORMAT_TEXT ||
1752  (es->verbose && ((Join *) plan)->inner_unique))
1753  ExplainPropertyBool("Inner Unique",
1754  ((Join *) plan)->inner_unique,
1755  es);
1756  break;
1757  default:
1758  break;
1759  }
1760 
1761  /* quals, sort keys, etc */
1762  switch (nodeTag(plan))
1763  {
1764  case T_IndexScan:
1765  show_scan_qual(((IndexScan *) plan)->indexqualorig,
1766  "Index Cond", planstate, ancestors, es);
1767  if (((IndexScan *) plan)->indexqualorig)
1768  show_instrumentation_count("Rows Removed by Index Recheck", 2,
1769  planstate, es);
1770  show_scan_qual(((IndexScan *) plan)->indexorderbyorig,
1771  "Order By", planstate, ancestors, es);
1772  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1773  if (plan->qual)
1774  show_instrumentation_count("Rows Removed by Filter", 1,
1775  planstate, es);
1776  break;
1777  case T_IndexOnlyScan:
1778  show_scan_qual(((IndexOnlyScan *) plan)->indexqual,
1779  "Index Cond", planstate, ancestors, es);
1780  if (((IndexOnlyScan *) plan)->recheckqual)
1781  show_instrumentation_count("Rows Removed by Index Recheck", 2,
1782  planstate, es);
1783  show_scan_qual(((IndexOnlyScan *) plan)->indexorderby,
1784  "Order By", planstate, ancestors, es);
1785  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1786  if (plan->qual)
1787  show_instrumentation_count("Rows Removed by Filter", 1,
1788  planstate, es);
1789  if (es->analyze)
1790  ExplainPropertyFloat("Heap Fetches", NULL,
1791  planstate->instrument->ntuples2, 0, es);
1792  break;
1793  case T_BitmapIndexScan:
1794  show_scan_qual(((BitmapIndexScan *) plan)->indexqualorig,
1795  "Index Cond", planstate, ancestors, es);
1796  break;
1797  case T_BitmapHeapScan:
1798  show_scan_qual(((BitmapHeapScan *) plan)->bitmapqualorig,
1799  "Recheck Cond", planstate, ancestors, es);
1800  if (((BitmapHeapScan *) plan)->bitmapqualorig)
1801  show_instrumentation_count("Rows Removed by Index Recheck", 2,
1802  planstate, es);
1803  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1804  if (plan->qual)
1805  show_instrumentation_count("Rows Removed by Filter", 1,
1806  planstate, es);
1807  if (es->analyze)
1808  show_tidbitmap_info((BitmapHeapScanState *) planstate, es);
1809  break;
1810  case T_SampleScan:
1811  show_tablesample(((SampleScan *) plan)->tablesample,
1812  planstate, ancestors, es);
1813  /* fall through to print additional fields the same as SeqScan */
1814  /* FALLTHROUGH */
1815  case T_SeqScan:
1816  case T_ValuesScan:
1817  case T_CteScan:
1818  case T_NamedTuplestoreScan:
1819  case T_WorkTableScan:
1820  case T_SubqueryScan:
1821  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1822  if (plan->qual)
1823  show_instrumentation_count("Rows Removed by Filter", 1,
1824  planstate, es);
1825  break;
1826  case T_Gather:
1827  {
1828  Gather *gather = (Gather *) plan;
1829 
1830  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1831  if (plan->qual)
1832  show_instrumentation_count("Rows Removed by Filter", 1,
1833  planstate, es);
1834  ExplainPropertyInteger("Workers Planned", NULL,
1835  gather->num_workers, es);
1836 
1837  /* Show params evaluated at gather node */
1838  if (gather->initParam)
1839  show_eval_params(gather->initParam, es);
1840 
1841  if (es->analyze)
1842  {
1843  int nworkers;
1844 
1845  nworkers = ((GatherState *) planstate)->nworkers_launched;
1846  ExplainPropertyInteger("Workers Launched", NULL,
1847  nworkers, es);
1848  }
1849 
1850  if (gather->single_copy || es->format != EXPLAIN_FORMAT_TEXT)
1851  ExplainPropertyBool("Single Copy", gather->single_copy, es);
1852  }
1853  break;
1854  case T_GatherMerge:
1855  {
1856  GatherMerge *gm = (GatherMerge *) plan;
1857 
1858  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1859  if (plan->qual)
1860  show_instrumentation_count("Rows Removed by Filter", 1,
1861  planstate, es);
1862  ExplainPropertyInteger("Workers Planned", NULL,
1863  gm->num_workers, es);
1864 
1865  /* Show params evaluated at gather-merge node */
1866  if (gm->initParam)
1867  show_eval_params(gm->initParam, es);
1868 
1869  if (es->analyze)
1870  {
1871  int nworkers;
1872 
1873  nworkers = ((GatherMergeState *) planstate)->nworkers_launched;
1874  ExplainPropertyInteger("Workers Launched", NULL,
1875  nworkers, es);
1876  }
1877  }
1878  break;
1879  case T_FunctionScan:
1880  if (es->verbose)
1881  {
1882  List *fexprs = NIL;
1883  ListCell *lc;
1884 
1885  foreach(lc, ((FunctionScan *) plan)->functions)
1886  {
1887  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
1888 
1889  fexprs = lappend(fexprs, rtfunc->funcexpr);
1890  }
1891  /* We rely on show_expression to insert commas as needed */
1892  show_expression((Node *) fexprs,
1893  "Function Call", planstate, ancestors,
1894  es->verbose, es);
1895  }
1896  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1897  if (plan->qual)
1898  show_instrumentation_count("Rows Removed by Filter", 1,
1899  planstate, es);
1900  break;
1901  case T_TableFuncScan:
1902  if (es->verbose)
1903  {
1904  TableFunc *tablefunc = ((TableFuncScan *) plan)->tablefunc;
1905 
1906  show_expression((Node *) tablefunc,
1907  "Table Function Call", planstate, ancestors,
1908  es->verbose, es);
1909  }
1910  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1911  if (plan->qual)
1912  show_instrumentation_count("Rows Removed by Filter", 1,
1913  planstate, es);
1914  break;
1915  case T_TidScan:
1916  {
1917  /*
1918  * The tidquals list has OR semantics, so be sure to show it
1919  * as an OR condition.
1920  */
1921  List *tidquals = ((TidScan *) plan)->tidquals;
1922 
1923  if (list_length(tidquals) > 1)
1924  tidquals = list_make1(make_orclause(tidquals));
1925  show_scan_qual(tidquals, "TID Cond", planstate, ancestors, es);
1926  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1927  if (plan->qual)
1928  show_instrumentation_count("Rows Removed by Filter", 1,
1929  planstate, es);
1930  }
1931  break;
1932  case T_TidRangeScan:
1933  {
1934  /*
1935  * The tidrangequals list has AND semantics, so be sure to
1936  * show it as an AND condition.
1937  */
1938  List *tidquals = ((TidRangeScan *) plan)->tidrangequals;
1939 
1940  if (list_length(tidquals) > 1)
1941  tidquals = list_make1(make_andclause(tidquals));
1942  show_scan_qual(tidquals, "TID Cond", planstate, ancestors, es);
1943  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1944  if (plan->qual)
1945  show_instrumentation_count("Rows Removed by Filter", 1,
1946  planstate, es);
1947  }
1948  break;
1949  case T_ForeignScan:
1950  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1951  if (plan->qual)
1952  show_instrumentation_count("Rows Removed by Filter", 1,
1953  planstate, es);
1954  show_foreignscan_info((ForeignScanState *) planstate, es);
1955  break;
1956  case T_CustomScan:
1957  {
1958  CustomScanState *css = (CustomScanState *) planstate;
1959 
1960  show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1961  if (plan->qual)
1962  show_instrumentation_count("Rows Removed by Filter", 1,
1963  planstate, es);
1964  if (css->methods->ExplainCustomScan)
1965  css->methods->ExplainCustomScan(css, ancestors, es);
1966  }
1967  break;
1968  case T_NestLoop:
1969  show_upper_qual(((NestLoop *) plan)->join.joinqual,
1970  "Join Filter", planstate, ancestors, es);
1971  if (((NestLoop *) plan)->join.joinqual)
1972  show_instrumentation_count("Rows Removed by Join Filter", 1,
1973  planstate, es);
1974  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
1975  if (plan->qual)
1976  show_instrumentation_count("Rows Removed by Filter", 2,
1977  planstate, es);
1978  break;
1979  case T_MergeJoin:
1980  show_upper_qual(((MergeJoin *) plan)->mergeclauses,
1981  "Merge Cond", planstate, ancestors, es);
1982  show_upper_qual(((MergeJoin *) plan)->join.joinqual,
1983  "Join Filter", planstate, ancestors, es);
1984  if (((MergeJoin *) plan)->join.joinqual)
1985  show_instrumentation_count("Rows Removed by Join Filter", 1,
1986  planstate, es);
1987  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
1988  if (plan->qual)
1989  show_instrumentation_count("Rows Removed by Filter", 2,
1990  planstate, es);
1991  break;
1992  case T_HashJoin:
1993  show_upper_qual(((HashJoin *) plan)->hashclauses,
1994  "Hash Cond", planstate, ancestors, es);
1995  show_upper_qual(((HashJoin *) plan)->join.joinqual,
1996  "Join Filter", planstate, ancestors, es);
1997  if (((HashJoin *) plan)->join.joinqual)
1998  show_instrumentation_count("Rows Removed by Join Filter", 1,
1999  planstate, es);
2000  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2001  if (plan->qual)
2002  show_instrumentation_count("Rows Removed by Filter", 2,
2003  planstate, es);
2004  break;
2005  case T_Agg:
2006  show_agg_keys(castNode(AggState, planstate), ancestors, es);
2007  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2008  show_hashagg_info((AggState *) planstate, es);
2009  if (plan->qual)
2010  show_instrumentation_count("Rows Removed by Filter", 1,
2011  planstate, es);
2012  break;
2013  case T_WindowAgg:
2014  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2015  if (plan->qual)
2016  show_instrumentation_count("Rows Removed by Filter", 1,
2017  planstate, es);
2018  show_upper_qual(((WindowAgg *) plan)->runConditionOrig,
2019  "Run Condition", planstate, ancestors, es);
2020  break;
2021  case T_Group:
2022  show_group_keys(castNode(GroupState, planstate), ancestors, es);
2023  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2024  if (plan->qual)
2025  show_instrumentation_count("Rows Removed by Filter", 1,
2026  planstate, es);
2027  break;
2028  case T_Sort:
2029  show_sort_keys(castNode(SortState, planstate), ancestors, es);
2030  show_sort_info(castNode(SortState, planstate), es);
2031  break;
2032  case T_IncrementalSort:
2034  ancestors, es);
2036  es);
2037  break;
2038  case T_MergeAppend:
2040  ancestors, es);
2041  break;
2042  case T_Result:
2043  show_upper_qual((List *) ((Result *) plan)->resconstantqual,
2044  "One-Time Filter", planstate, ancestors, es);
2045  show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2046  if (plan->qual)
2047  show_instrumentation_count("Rows Removed by Filter", 1,
2048  planstate, es);
2049  break;
2050  case T_ModifyTable:
2051  show_modifytable_info(castNode(ModifyTableState, planstate), ancestors,
2052  es);
2053  break;
2054  case T_Hash:
2055  show_hash_info(castNode(HashState, planstate), es);
2056  break;
2057  case T_Memoize:
2058  show_memoize_info(castNode(MemoizeState, planstate), ancestors,
2059  es);
2060  break;
2061  default:
2062  break;
2063  }
2064 
2065  /*
2066  * Prepare per-worker JIT instrumentation. As with the overall JIT
2067  * summary, this is printed only if printing costs is enabled.
2068  */
2069  if (es->workers_state && es->costs && es->verbose)
2070  {
2072 
2073  if (w)
2074  {
2075  for (int n = 0; n < w->num_workers; n++)
2076  {
2077  ExplainOpenWorker(n, es);
2078  ExplainPrintJIT(es, planstate->state->es_jit_flags,
2079  &w->jit_instr[n]);
2080  ExplainCloseWorker(n, es);
2081  }
2082  }
2083  }
2084 
2085  /* Show buffer/WAL usage */
2086  if (es->buffers && planstate->instrument)
2087  show_buffer_usage(es, &planstate->instrument->bufusage, false);
2088  if (es->wal && planstate->instrument)
2089  show_wal_usage(es, &planstate->instrument->walusage);
2090 
2091  /* Prepare per-worker buffer/WAL usage */
2092  if (es->workers_state && (es->buffers || es->wal) && es->verbose)
2093  {
2094  WorkerInstrumentation *w = planstate->worker_instrument;
2095 
2096  for (int n = 0; n < w->num_workers; n++)
2097  {
2098  Instrumentation *instrument = &w->instrument[n];
2099  double nloops = instrument->nloops;
2100 
2101  if (nloops <= 0)
2102  continue;
2103 
2104  ExplainOpenWorker(n, es);
2105  if (es->buffers)
2106  show_buffer_usage(es, &instrument->bufusage, false);
2107  if (es->wal)
2108  show_wal_usage(es, &instrument->walusage);
2109  ExplainCloseWorker(n, es);
2110  }
2111  }
2112 
2113  /* Show per-worker details for this plan node, then pop that stack */
2114  if (es->workers_state)
2116  es->workers_state = save_workers_state;
2117 
2118  /*
2119  * If partition pruning was done during executor initialization, the
2120  * number of child plans we'll display below will be less than the number
2121  * of subplans that was specified in the plan. To make this a bit less
2122  * mysterious, emit an indication that this happened. Note that this
2123  * field is emitted now because we want it to be a property of the parent
2124  * node; it *cannot* be emitted within the Plans sub-node we'll open next.
2125  */
2126  switch (nodeTag(plan))
2127  {
2128  case T_Append:
2129  ExplainMissingMembers(((AppendState *) planstate)->as_nplans,
2130  list_length(((Append *) plan)->appendplans),
2131  es);
2132  break;
2133  case T_MergeAppend:
2134  ExplainMissingMembers(((MergeAppendState *) planstate)->ms_nplans,
2135  list_length(((MergeAppend *) plan)->mergeplans),
2136  es);
2137  break;
2138  default:
2139  break;
2140  }
2141 
2142  /* Get ready to display the child plans */
2143  haschildren = planstate->initPlan ||
2144  outerPlanState(planstate) ||
2145  innerPlanState(planstate) ||
2146  IsA(plan, Append) ||
2147  IsA(plan, MergeAppend) ||
2148  IsA(plan, BitmapAnd) ||
2149  IsA(plan, BitmapOr) ||
2150  IsA(plan, SubqueryScan) ||
2151  (IsA(planstate, CustomScanState) &&
2152  ((CustomScanState *) planstate)->custom_ps != NIL) ||
2153  planstate->subPlan;
2154  if (haschildren)
2155  {
2156  ExplainOpenGroup("Plans", "Plans", false, es);
2157  /* Pass current Plan as head of ancestors list for children */
2158  ancestors = lcons(plan, ancestors);
2159  }
2160 
2161  /* initPlan-s */
2162  if (planstate->initPlan)
2163  ExplainSubPlans(planstate->initPlan, ancestors, "InitPlan", es);
2164 
2165  /* lefttree */
2166  if (outerPlanState(planstate))
2167  ExplainNode(outerPlanState(planstate), ancestors,
2168  "Outer", NULL, es);
2169 
2170  /* righttree */
2171  if (innerPlanState(planstate))
2172  ExplainNode(innerPlanState(planstate), ancestors,
2173  "Inner", NULL, es);
2174 
2175  /* special child plans */
2176  switch (nodeTag(plan))
2177  {
2178  case T_Append:
2179  ExplainMemberNodes(((AppendState *) planstate)->appendplans,
2180  ((AppendState *) planstate)->as_nplans,
2181  ancestors, es);
2182  break;
2183  case T_MergeAppend:
2184  ExplainMemberNodes(((MergeAppendState *) planstate)->mergeplans,
2185  ((MergeAppendState *) planstate)->ms_nplans,
2186  ancestors, es);
2187  break;
2188  case T_BitmapAnd:
2189  ExplainMemberNodes(((BitmapAndState *) planstate)->bitmapplans,
2190  ((BitmapAndState *) planstate)->nplans,
2191  ancestors, es);
2192  break;
2193  case T_BitmapOr:
2194  ExplainMemberNodes(((BitmapOrState *) planstate)->bitmapplans,
2195  ((BitmapOrState *) planstate)->nplans,
2196  ancestors, es);
2197  break;
2198  case T_SubqueryScan:
2199  ExplainNode(((SubqueryScanState *) planstate)->subplan, ancestors,
2200  "Subquery", NULL, es);
2201  break;
2202  case T_CustomScan:
2203  ExplainCustomChildren((CustomScanState *) planstate,
2204  ancestors, es);
2205  break;
2206  default:
2207  break;
2208  }
2209 
2210  /* subPlan-s */
2211  if (planstate->subPlan)
2212  ExplainSubPlans(planstate->subPlan, ancestors, "SubPlan", es);
2213 
2214  /* end of child plans */
2215  if (haschildren)
2216  {
2217  ancestors = list_delete_first(ancestors);
2218  ExplainCloseGroup("Plans", "Plans", false, es);
2219  }
2220 
2221  /* in text format, undo whatever indentation we added */
2222  if (es->format == EXPLAIN_FORMAT_TEXT)
2223  es->indent = save_indent;
2224 
2225  ExplainCloseGroup("Plan",
2226  relationship ? NULL : "Plan",
2227  true, es);
2228 }
#define outerPlanState(node)
Definition: execnodes.h:1125
#define innerPlanState(node)
Definition: execnodes.h:1124
static void show_modifytable_info(ModifyTableState *mtstate, List *ancestors, ExplainState *es)
Definition: explain.c:3913
static void show_plan_tlist(PlanState *planstate, List *ancestors, ExplainState *es)
Definition: explain.c:2234
static void show_memoize_info(MemoizeState *mstate, List *ancestors, ExplainState *es)
Definition: explain.c:3132
static void show_group_keys(GroupState *gstate, List *ancestors, ExplainState *es)
Definition: explain.c:2544
static void ExplainModifyTarget(ModifyTable *plan, ExplainState *es)
Definition: explain.c:3781
static void show_agg_keys(AggState *astate, List *ancestors, ExplainState *es)
Definition: explain.c:2412
static void show_hashagg_info(AggState *aggstate, ExplainState *es)
Definition: explain.c:3276
static void show_scan_qual(List *qual, const char *qlabel, PlanState *planstate, List *ancestors, ExplainState *es)
Definition: explain.c:2336
static void ExplainIndexScanDetails(Oid indexid, ScanDirection indexorderdir, ExplainState *es)
Definition: explain.c:3729
static void show_eval_params(Bitmapset *bms_params, ExplainState *es)
Definition: explain.c:3477
static void show_instrumentation_count(const char *qlabel, int which, PlanState *planstate, ExplainState *es)
Definition: explain.c:3427
static void ExplainMemberNodes(PlanState **planstates, int nplans, List *ancestors, ExplainState *es)
Definition: explain.c:4125
static void ExplainPrintJIT(ExplainState *es, int jit_flags, JitInstrumentation *ji)
Definition: explain.c:875
static void show_incremental_sort_info(IncrementalSortState *incrsortstate, ExplainState *es)
Definition: explain.c:2955
static void show_tablesample(TableSampleClause *tsc, PlanState *planstate, List *ancestors, ExplainState *es)
Definition: explain.c:2684
static void show_upper_qual(List *qual, const char *qlabel, PlanState *planstate, List *ancestors, ExplainState *es)
Definition: explain.c:2350
static void show_sort_info(SortState *sortstate, ExplainState *es)
Definition: explain.c:2750
static void ExplainMissingMembers(int nplans, int nchildren, ExplainState *es)
Definition: explain.c:4143
static void ExplainFlushWorkersState(ExplainState *es)
Definition: explain.c:4337
static void show_hash_info(HashState *hashstate, ExplainState *es)
Definition: explain.c:3041
void ExplainPropertyFloat(const char *qlabel, const char *unit, double value, int ndigits, ExplainState *es)
Definition: explain.c:4579
static void show_buffer_usage(ExplainState *es, const BufferUsage *usage, bool planning)
Definition: explain.c:3529
static void show_expression(Node *node, const char *qlabel, PlanState *planstate, List *ancestors, bool useprefix, ExplainState *es)
Definition: explain.c:2292
static void ExplainIndentText(ExplainState *es)
Definition: explain.c:4980
static void show_tidbitmap_info(BitmapHeapScanState *planstate, ExplainState *es)
Definition: explain.c:3397
static void ExplainSubPlans(List *plans, List *ancestors, const char *relationship, ExplainState *es)
Definition: explain.c:4157
static void show_foreignscan_info(ForeignScanState *fsstate, ExplainState *es)
Definition: explain.c:3456
static void ExplainScanTarget(Scan *plan, ExplainState *es)
Definition: explain.c:3768
static void show_merge_append_keys(MergeAppendState *mstate, List *ancestors, ExplainState *es)
Definition: explain.c:2396
static void ExplainCloseWorker(int n, ExplainState *es)
Definition: explain.c:4301
static void ExplainOpenWorker(int n, ExplainState *es)
Definition: explain.c:4239
static void show_wal_usage(ExplainState *es, const WalUsage *usage)
Definition: explain.c:3691
void ExplainPropertyBool(const char *qlabel, bool value, ExplainState *es)
Definition: explain.c:4593
static void show_sort_keys(SortState *sortstate, List *ancestors, ExplainState *es)
Definition: explain.c:2364
static ExplainWorkersState * ExplainCreateWorkersState(int num_workers)
Definition: explain.c:4222
static void show_incremental_sort_keys(IncrementalSortState *incrsortstate, List *ancestors, ExplainState *es)
Definition: explain.c:2379
static void ExplainCustomChildren(CustomScanState *css, List *ancestors, ExplainState *es)
Definition: explain.c:4200
void InstrEndLoop(Instrumentation *instr)
Definition: instrument.c:140
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * lappend(List *list, void *datum)
Definition: list.c:338
List * lcons(void *datum, List *list)
Definition: list.c:494
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:636
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:652
@ SETOPCMD_EXCEPT
Definition: nodes.h:397
@ SETOPCMD_EXCEPT_ALL
Definition: nodes.h:398
@ SETOPCMD_INTERSECT_ALL
Definition: nodes.h:396
@ SETOPCMD_INTERSECT
Definition: nodes.h:395
@ SETOP_HASHED
Definition: nodes.h:404
@ SETOP_SORTED
Definition: nodes.h:403
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:383
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define nodeTag(nodeptr)
Definition: nodes.h:122
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:382
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
@ AGG_SORTED
Definition: nodes.h:352
@ AGG_HASHED
Definition: nodes.h:353
@ AGG_MIXED
Definition: nodes.h:354
@ AGG_PLAIN
Definition: nodes.h:351
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_INNER
Definition: nodes.h:293
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_LEFT
Definition: nodes.h:294
@ JOIN_ANTI
Definition: nodes.h:308
#define NIL
Definition: pg_list.h:66
#define list_make1(x1)
Definition: pg_list.h:210
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static const struct fns functions
Definition: regcomp.c:357
Definition: plannodes.h:993
AggSplit aggsplit
Definition: plannodes.h:1000
AggStrategy aggstrategy
Definition: plannodes.h:997
void(* ExplainCustomScan)(CustomScanState *node, List *ancestors, ExplainState *es)
Definition: extensible.h:155
const struct CustomExecMethods * methods
Definition: execnodes.h:1965
int es_jit_flags
Definition: execnodes.h:700
bool verbose
Definition: explain.h:41
bool hide_workers
Definition: explain.h:59
bool timing
Definition: explain.h:46
bool analyze
Definition: explain.h:42
bool wal
Definition: explain.h:45
bool costs
Definition: explain.h:43
bool buffers
Definition: explain.h:44
Bitmapset * initParam
Definition: plannodes.h:1182
int num_workers
Definition: plannodes.h:1156
int num_workers
Definition: plannodes.h:1139
Bitmapset * initParam
Definition: plannodes.h:1143
bool single_copy
Definition: plannodes.h:1141
ScanDirection indexorderdir
Definition: plannodes.h:498
ScanDirection indexorderdir
Definition: plannodes.h:456
Oid indexid
Definition: plannodes.h:450
double startup
Definition: instrument.h:82
WalUsage walusage
Definition: instrument.h:90
double ntuples
Definition: instrument.h:84
BufferUsage bufusage
Definition: instrument.h:89
double ntuples2
Definition: instrument.h:85
Definition: pg_list.h:52
Definition: nodes.h:118
struct SharedJitInstrumentation * worker_jit_instrument
Definition: execnodes.h:1043
Instrumentation * instrument
Definition: execnodes.h:1039
Plan * plan
Definition: execnodes.h:1029
EState * state
Definition: execnodes.h:1031
WorkerInstrumentation * worker_instrument
Definition: execnodes.h:1040
JitInstrumentation jit_instr[FLEXIBLE_ARRAY_MEMBER]
Definition: jit.h:51
Instrumentation instrument[FLEXIBLE_ARRAY_MEMBER]
Definition: instrument.h:96

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Agg::aggsplit, Agg::aggstrategy, ExplainState::analyze, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Plan::async_capable, ExplainState::buffers, Instrumentation::bufusage, castNode, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_SELECT, CMD_UPDATE, ExplainState::costs, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_SKIPFINAL, EState::es_jit_flags, EXPLAIN_FORMAT_TEXT, explain_get_index_name(), ExplainCloseGroup(), ExplainCloseWorker(), ExplainCreateWorkersState(), ExplainCustomChildren(), CustomExecMethods::ExplainCustomScan, ExplainFlushWorkersState(), ExplainIndentText(), ExplainIndexScanDetails(), ExplainMemberNodes(), ExplainMissingMembers(), ExplainModifyTarget(), ExplainOpenGroup(), ExplainOpenWorker(), ExplainPrintJIT(), ExplainPropertyBool(), ExplainPropertyFloat(), ExplainPropertyInteger(), ExplainPropertyText(), ExplainScanTarget(), ExplainSubPlans(), ExplainState::format, RangeTblFunction::funcexpr, functions, ExplainState::hide_workers, if(), ExplainState::indent, IndexScan::indexid, IndexOnlyScan::indexid, BitmapIndexScan::indexid, IndexScan::indexorderdir, IndexOnlyScan::indexorderdir, Gather::initParam, GatherMerge::initParam, PlanState::initPlan, innerPlanState, InstrEndLoop(), WorkerInstrumentation::instrument, PlanState::instrument, IsA, SharedJitInstrumentation::jit_instr, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JOIN_SEMI, lappend(), lcons(), lfirst, list_delete_first(), list_length(), list_make1, make_andclause(), make_orclause(), CustomScanState::methods, NIL, Instrumentation::nloops, nodeTag, Instrumentation::ntuples, Instrumentation::ntuples2, WorkerInstrumentation::num_workers, SharedJitInstrumentation::num_workers, Gather::num_workers, GatherMerge::num_workers, outerPlanState, Plan::parallel_aware, PlanState::plan, Plan::plan_rows, Plan::plan_width, psprintf(), quote_identifier(), SETOP_HASHED, SETOP_SORTED, SETOPCMD_EXCEPT, SETOPCMD_EXCEPT_ALL, SETOPCMD_INTERSECT, SETOPCMD_INTERSECT_ALL, show_agg_keys(), show_buffer_usage(), show_eval_params(), show_expression(), show_foreignscan_info(), show_group_keys(), show_hash_info(), show_hashagg_info(), show_incremental_sort_info(), show_incremental_sort_keys(), show_instrumentation_count(), show_memoize_info(), show_merge_append_keys(), show_modifytable_info(), show_plan_tlist(), show_scan_qual(), show_sort_info(), show_sort_keys(), show_tablesample(), show_tidbitmap_info(), show_upper_qual(), show_wal_usage(), Gather::single_copy, Instrumentation::startup, Plan::startup_cost, PlanState::state, ExplainState::str, PlanState::subPlan, ExplainState::timing, Instrumentation::total, Plan::total_cost, ExplainState::verbose, ExplainState::wal, Instrumentation::walusage, PlanState::worker_instrument, PlanState::worker_jit_instrument, and ExplainState::workers_state.

Referenced by ExplainCustomChildren(), ExplainMemberNodes(), ExplainPrintPlan(), and ExplainSubPlans().

◆ ExplainOnePlan()

void ExplainOnePlan ( PlannedStmt plannedstmt,
IntoClause into,
ExplainState es,
const char *  queryString,
ParamListInfo  params,
QueryEnvironment queryEnv,
const instr_time planduration,
const BufferUsage bufusage 
)

Definition at line 518 of file explain.c.

522 {
524  QueryDesc *queryDesc;
525  instr_time starttime;
526  double totaltime = 0;
527  int eflags;
528  int instrument_option = 0;
529 
530  Assert(plannedstmt->commandType != CMD_UTILITY);
531 
532  if (es->analyze && es->timing)
533  instrument_option |= INSTRUMENT_TIMER;
534  else if (es->analyze)
535  instrument_option |= INSTRUMENT_ROWS;
536 
537  if (es->buffers)
538  instrument_option |= INSTRUMENT_BUFFERS;
539  if (es->wal)
540  instrument_option |= INSTRUMENT_WAL;
541 
542  /*
543  * We always collect timing for the entire statement, even when node-level
544  * timing is off, so we don't look at es->timing here. (We could skip
545  * this if !es->summary, but it's hardly worth the complication.)
546  */
547  INSTR_TIME_SET_CURRENT(starttime);
548 
549  /*
550  * Use a snapshot with an updated command ID to ensure this query sees
551  * results of any previously executed queries.
552  */
555 
556  /*
557  * Normally we discard the query's output, but if explaining CREATE TABLE
558  * AS, we'd better use the appropriate tuple receiver.
559  */
560  if (into)
562  else
564 
565  /* Create a QueryDesc for the query */
566  queryDesc = CreateQueryDesc(plannedstmt, queryString,
568  dest, params, queryEnv, instrument_option);
569 
570  /* Select execution options */
571  if (es->analyze)
572  eflags = 0; /* default run-to-completion flags */
573  else
574  eflags = EXEC_FLAG_EXPLAIN_ONLY;
575  if (into)
576  eflags |= GetIntoRelEFlags(into);
577 
578  /* call ExecutorStart to prepare the plan for execution */
579  ExecutorStart(queryDesc, eflags);
580 
581  /* Execute the plan for statistics if asked for */
582  if (es->analyze)
583  {
584  ScanDirection dir;
585 
586  /* EXPLAIN ANALYZE CREATE TABLE AS WITH NO DATA is weird */
587  if (into && into->skipData)
589  else
590  dir = ForwardScanDirection;
591 
592  /* run the plan */
593  ExecutorRun(queryDesc, dir, 0L, true);
594 
595  /* run cleanup too */
596  ExecutorFinish(queryDesc);
597 
598  /* We can't run ExecutorEnd 'till we're done printing the stats... */
599  totaltime += elapsed_time(&starttime);
600  }
601 
602  ExplainOpenGroup("Query", NULL, true, es);
603 
604  /* Create textual dump of plan tree */
605  ExplainPrintPlan(es, queryDesc);
606 
607  /*
608  * COMPUTE_QUERY_ID_REGRESS means COMPUTE_QUERY_ID_AUTO, but we don't show
609  * the queryid in any of the EXPLAIN plans to keep stable the results
610  * generated by regression test suites.
611  */
612  if (es->verbose && plannedstmt->queryId != UINT64CONST(0) &&
614  {
615  /*
616  * Output the queryid as an int64 rather than a uint64 so we match
617  * what would be seen in the BIGINT pg_stat_statements.queryid column.
618  */
619  ExplainPropertyInteger("Query Identifier", NULL, (int64)
620  plannedstmt->queryId, es);
621  }
622 
623  /* Show buffer usage in planning */
624  if (bufusage)
625  {
626  ExplainOpenGroup("Planning", "Planning", true, es);
627  show_buffer_usage(es, bufusage, true);
628  ExplainCloseGroup("Planning", "Planning", true, es);
629  }
630 
631  if (es->summary && planduration)
632  {
633  double plantime = INSTR_TIME_GET_DOUBLE(*planduration);
634 
635  ExplainPropertyFloat("Planning Time", "ms", 1000.0 * plantime, 3, es);
636  }
637 
638  /* Print info about runtime of triggers */
639  if (es->analyze)
640  ExplainPrintTriggers(es, queryDesc);
641 
642  /*
643  * Print info about JITing. Tied to es->costs because we don't want to
644  * display this in regression tests, as it'd cause output differences
645  * depending on build options. Might want to separate that out from COSTS
646  * at a later stage.
647  */
648  if (es->costs)
649  ExplainPrintJITSummary(es, queryDesc);
650 
651  /*
652  * Close down the query and free resources. Include time for this in the
653  * total execution time (although it should be pretty minimal).
654  */
655  INSTR_TIME_SET_CURRENT(starttime);
656 
657  ExecutorEnd(queryDesc);
658 
659  FreeQueryDesc(queryDesc);
660 
662 
663  /* We need a CCI just in case query expanded to multiple plans */
664  if (es->analyze)
666 
667  totaltime += elapsed_time(&starttime);
668 
669  /*
670  * We only report execution time if we actually ran the query (that is,
671  * the user specified ANALYZE), and if summary reporting is enabled (the
672  * user can set SUMMARY OFF to not have the timing information included in
673  * the output). By default, ANALYZE sets SUMMARY to true.
674  */
675  if (es->summary && es->analyze)
676  ExplainPropertyFloat("Execution Time", "ms", 1000.0 * totaltime, 3,
677  es);
678 
679  ExplainCloseGroup("Query", NULL, true, es);
680 }
DestReceiver * CreateIntoRelDestReceiver(IntoClause *intoClause)
Definition: createas.c:440
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:375
DestReceiver * None_Receiver
Definition: dest.c:96
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:461
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:401
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:131
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:300
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
void ExplainPrintJITSummary(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:849
static double elapsed_time(instr_time *starttime)
Definition: explain.c:1073
void ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:757
void ExplainPrintTriggers(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:806
@ INSTRUMENT_TIMER
Definition: instrument.h:59
@ INSTRUMENT_BUFFERS
Definition: instrument.h:60
@ INSTRUMENT_WAL
Definition: instrument.h:62
@ INSTRUMENT_ROWS
Definition: instrument.h:61
@ CMD_UTILITY
Definition: nodes.h:270
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
int compute_query_id
Definition: queryjumble.c:43
@ COMPUTE_QUERY_ID_REGRESS
Definition: queryjumble.h:59
ScanDirection
Definition: sdir.h:23
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:747
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:735
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:805
#define InvalidSnapshot
Definition: snapshot.h:123
bool summary
Definition: explain.h:47
bool skipData
Definition: primnodes.h:135
CmdType commandType
Definition: plannodes.h:53
uint64 queryId
Definition: plannodes.h:55
void CommandCounterIncrement(void)
Definition: xact.c:1077

References ExplainState::analyze, Assert(), ExplainState::buffers, CMD_UTILITY, CommandCounterIncrement(), PlannedStmt::commandType, compute_query_id, COMPUTE_QUERY_ID_REGRESS, ExplainState::costs, CreateIntoRelDestReceiver(), CreateQueryDesc(), generate_unaccent_rules::dest, elapsed_time(), EXEC_FLAG_EXPLAIN_ONLY, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ExplainCloseGroup(), ExplainOpenGroup(), ExplainPrintJITSummary(), ExplainPrintPlan(), ExplainPrintTriggers(), ExplainPropertyFloat(), ExplainPropertyInteger(), ForwardScanDirection, FreeQueryDesc(), GetActiveSnapshot(), GetIntoRelEFlags(), INSTR_TIME_GET_DOUBLE, INSTR_TIME_SET_CURRENT, INSTRUMENT_BUFFERS, INSTRUMENT_ROWS, INSTRUMENT_TIMER, INSTRUMENT_WAL, InvalidSnapshot, NoMovementScanDirection, None_Receiver, PopActiveSnapshot(), PushCopiedSnapshot(), PlannedStmt::queryId, show_buffer_usage(), IntoClause::skipData, ExplainState::summary, ExplainState::timing, UpdateActiveSnapshotCommandId(), ExplainState::verbose, and ExplainState::wal.

Referenced by ExplainExecuteQuery(), and ExplainOneQuery().

◆ ExplainOneQuery()

static void ExplainOneQuery ( Query query,
int  cursorOptions,
IntoClause into,
ExplainState es,
const char *  queryString,
ParamListInfo  params,
QueryEnvironment queryEnv 
)
static

Definition at line 367 of file explain.c.

371 {
372  /* planner will not cope with utility statements */
373  if (query->commandType == CMD_UTILITY)
374  {
375  ExplainOneUtility(query->utilityStmt, into, es, queryString, params,
376  queryEnv);
377  return;
378  }
379 
380  /* if an advisor plugin is present, let it manage things */
382  (*ExplainOneQuery_hook) (query, cursorOptions, into, es,
383  queryString, params, queryEnv);
384  else
385  {
386  PlannedStmt *plan;
387  instr_time planstart,
388  planduration;
389  BufferUsage bufusage_start,
390  bufusage;
391 
392  if (es->buffers)
393  bufusage_start = pgBufferUsage;
394  INSTR_TIME_SET_CURRENT(planstart);
395 
396  /* plan the query */
397  plan = pg_plan_query(query, queryString, cursorOptions, params);
398 
399  INSTR_TIME_SET_CURRENT(planduration);
400  INSTR_TIME_SUBTRACT(planduration, planstart);
401 
402  /* calc differences of buffer counters. */
403  if (es->buffers)
404  {
405  memset(&bufusage, 0, sizeof(BufferUsage));
406  BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
407  }
408 
409  /* run it (if needed) and produce output */
410  ExplainOnePlan(plan, into, es, queryString, params, queryEnv,
411  &planduration, (es->buffers ? &bufusage : NULL));
412  }
413 }
ExplainOneQuery_hook_type ExplainOneQuery_hook
Definition: explain.c:45
void ExplainOnePlan(PlannedStmt *plannedstmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, const instr_time *planduration, const BufferUsage *bufusage)
Definition: explain.c:518
void ExplainOneUtility(Node *utilityStmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
Definition: explain.c:428
BufferUsage pgBufferUsage
Definition: instrument.c:20
void BufferUsageAccumDiff(BufferUsage *dst, const BufferUsage *add, const BufferUsage *sub)
Definition: instrument.c:246
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:853
CmdType commandType
Definition: parsenodes.h:124
Node * utilityStmt
Definition: parsenodes.h:136

References ExplainState::buffers, BufferUsageAccumDiff(), CMD_UTILITY, Query::commandType, ExplainOnePlan(), ExplainOneQuery_hook, ExplainOneUtility(), INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, pg_plan_query(), pgBufferUsage, and Query::utilityStmt.

Referenced by ExplainOneUtility(), and ExplainQuery().

◆ ExplainOneUtility()

void ExplainOneUtility ( Node utilityStmt,
IntoClause into,
ExplainState es,
const char *  queryString,
ParamListInfo  params,
QueryEnvironment queryEnv 
)

Definition at line 428 of file explain.c.

431 {
432  if (utilityStmt == NULL)
433  return;
434 
435  if (IsA(utilityStmt, CreateTableAsStmt))
436  {
437  /*
438  * We have to rewrite the contained SELECT and then pass it back to
439  * ExplainOneQuery. Copy to be safe in the EXPLAIN EXECUTE case.
440  */
441  CreateTableAsStmt *ctas = (CreateTableAsStmt *) utilityStmt;
442  List *rewritten;
443 
444  /*
445  * Check if the relation exists or not. This is done at this stage to
446  * avoid query planning or execution.
447  */
448  if (CreateTableAsRelExists(ctas))
449  {
450  if (ctas->objtype == OBJECT_TABLE)
451  ExplainDummyGroup("CREATE TABLE AS", NULL, es);
452  else if (ctas->objtype == OBJECT_MATVIEW)
453  ExplainDummyGroup("CREATE MATERIALIZED VIEW", NULL, es);
454  else
455  elog(ERROR, "unexpected object type: %d",
456  (int) ctas->objtype);
457  return;
458  }
459 
460  rewritten = QueryRewrite(castNode(Query, copyObject(ctas->query)));
461  Assert(list_length(rewritten) == 1);
462  ExplainOneQuery(linitial_node(Query, rewritten),
463  CURSOR_OPT_PARALLEL_OK, ctas->into, es,
464  queryString, params, queryEnv);
465  }
466  else if (IsA(utilityStmt, DeclareCursorStmt))
467  {
468  /*
469  * Likewise for DECLARE CURSOR.
470  *
471  * Notice that if you say EXPLAIN ANALYZE DECLARE CURSOR then we'll
472  * actually run the query. This is different from pre-8.3 behavior
473  * but seems more useful than not running the query. No cursor will
474  * be created, however.
475  */
476  DeclareCursorStmt *dcs = (DeclareCursorStmt *) utilityStmt;
477  List *rewritten;
478 
479  rewritten = QueryRewrite(castNode(Query, copyObject(dcs->query)));
480  Assert(list_length(rewritten) == 1);
481  ExplainOneQuery(linitial_node(Query, rewritten),
482  dcs->options, NULL, es,
483  queryString, params, queryEnv);
484  }
485  else if (IsA(utilityStmt, ExecuteStmt))
486  ExplainExecuteQuery((ExecuteStmt *) utilityStmt, into, es,
487  queryString, params, queryEnv);
488  else if (IsA(utilityStmt, NotifyStmt))
489  {
490  if (es->format == EXPLAIN_FORMAT_TEXT)
491  appendStringInfoString(es->str, "NOTIFY\n");
492  else
493  ExplainDummyGroup("Notify", NULL, es);
494  }
495  else
496  {
497  if (es->format == EXPLAIN_FORMAT_TEXT)
499  "Utility statements have no plan structure\n");
500  else
501  ExplainDummyGroup("Utility Statement", NULL, es);
502  }
503 }
void ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
Definition: prepare.c:571
bool CreateTableAsRelExists(CreateTableAsStmt *ctas)
Definition: createas.c:393
static void ExplainDummyGroup(const char *objtype, const char *labelname, ExplainState *es)
Definition: explain.c:4818
static void ExplainOneQuery(Query *query, int cursorOptions, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
Definition: explain.c:367
#define copyObject(obj)
Definition: nodes.h:233
@ OBJECT_MATVIEW
Definition: parsenodes.h:1885
@ OBJECT_TABLE
Definition: parsenodes.h:1903
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2908
#define linitial_node(type, l)
Definition: pg_list.h:179
List * QueryRewrite(Query *parsetree)
IntoClause * into
Definition: parsenodes.h:3500
ObjectType objtype
Definition: parsenodes.h:3501

References appendStringInfoString(), Assert(), castNode, copyObject, CreateTableAsRelExists(), CURSOR_OPT_PARALLEL_OK, elog(), ERROR, EXPLAIN_FORMAT_TEXT, ExplainDummyGroup(), ExplainExecuteQuery(), ExplainOneQuery(), ExplainState::format, CreateTableAsStmt::into, IsA, linitial_node, list_length(), OBJECT_MATVIEW, OBJECT_TABLE, CreateTableAsStmt::objtype, DeclareCursorStmt::options, DeclareCursorStmt::query, CreateTableAsStmt::query, QueryRewrite(), and ExplainState::str.

Referenced by ExplainExecuteQuery(), and ExplainOneQuery().

◆ ExplainOpenGroup()

void ExplainOpenGroup ( const char *  objtype,
const char *  labelname,
bool  labeled,
ExplainState es 
)

Definition at line 4608 of file explain.c.

4610 {
4611  switch (es->format)
4612  {
4613  case EXPLAIN_FORMAT_TEXT:
4614  /* nothing to do */
4615  break;
4616 
4617  case EXPLAIN_FORMAT_XML:
4618  ExplainXMLTag(objtype, X_OPENING, es);
4619  es->indent++;
4620  break;
4621 
4622  case EXPLAIN_FORMAT_JSON:
4624  appendStringInfoSpaces(es->str, 2 * es->indent);
4625  if (labelname)
4626  {
4627  escape_json(es->str, labelname);
4628  appendStringInfoString(es->str, ": ");
4629  }
4630  appendStringInfoChar(es->str, labeled ? '{' : '[');
4631 
4632  /*
4633  * In JSON format, the grouping_stack is an integer list. 0 means
4634  * we've emitted nothing at this grouping level, 1 means we've
4635  * emitted something (and so the next item needs a comma). See
4636  * ExplainJSONLineEnding().
4637  */
4638  es->grouping_stack = lcons_int(0, es->grouping_stack);
4639  es->indent++;
4640  break;
4641 
4642  case EXPLAIN_FORMAT_YAML:
4643 
4644  /*
4645  * In YAML format, the grouping stack is an integer list. 0 means
4646  * we've emitted nothing at this grouping level AND this grouping
4647  * level is unlabeled and must be marked with "- ". See
4648  * ExplainYAMLLineStarting().
4649  */
4651  if (labelname)
4652  {
4653  appendStringInfo(es->str, "%s: ", labelname);
4654  es->grouping_stack = lcons_int(1, es->grouping_stack);
4655  }
4656  else
4657  {
4658  appendStringInfoString(es->str, "- ");
4659  es->grouping_stack = lcons_int(0, es->grouping_stack);
4660  }
4661  es->indent++;
4662  break;
4663  }
4664 }
#define X_OPENING
Definition: explain.c:52

References appendStringInfo(), appendStringInfoChar(), appendStringInfoSpaces(), appendStringInfoString(), escape_json(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainJSONLineEnding(), ExplainXMLTag(), ExplainYAMLLineStarting(), ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, lcons_int(), ExplainState::str, and X_OPENING.

Referenced by ExplainFlushWorkersState(), ExplainNode(), ExplainOnePlan(), ExplainPrintJIT(), ExplainPrintSettings(), ExplainPrintTriggers(), report_triggers(), show_grouping_set_keys(), show_grouping_sets(), show_incremental_sort_group_info(), and show_modifytable_info().

◆ ExplainOpenSetAsideGroup()

static void ExplainOpenSetAsideGroup ( const char *  objtype,
const char *  labelname,
bool  labeled,
int  depth,
ExplainState es 
)
static

Definition at line 4718 of file explain.c.

4720 {
4721  switch (es->format)
4722  {
4723  case EXPLAIN_FORMAT_TEXT:
4724  /* nothing to do */
4725  break;
4726 
4727  case EXPLAIN_FORMAT_XML:
4728  es->indent += depth;
4729  break;
4730 
4731  case EXPLAIN_FORMAT_JSON:
4732  es->grouping_stack = lcons_int(0, es->grouping_stack);
4733  es->indent += depth;
4734  break;
4735 
4736  case EXPLAIN_FORMAT_YAML:
4737  if (labelname)
4738  es->grouping_stack = lcons_int(1, es->grouping_stack);
4739  else
4740  es->grouping_stack = lcons_int(0, es->grouping_stack);
4741  es->indent += depth;
4742  break;
4743  }
4744 }

References EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, and lcons_int().

Referenced by ExplainOpenWorker().

◆ ExplainOpenWorker()

static void ExplainOpenWorker ( int  n,
ExplainState es 
)
static

Definition at line 4239 of file explain.c.

4240 {
4241  ExplainWorkersState *wstate = es->workers_state;
4242 
4243  Assert(wstate);
4244  Assert(n >= 0 && n < wstate->num_workers);
4245 
4246  /* Save prior output buffer pointer */
4247  wstate->prev_str = es->str;
4248 
4249  if (!wstate->worker_inited[n])
4250  {
4251  /* First time through, so create the buffer for this worker */
4252  initStringInfo(&wstate->worker_str[n]);
4253  es->str = &wstate->worker_str[n];
4254 
4255  /*
4256  * Push suitable initial formatting state for this worker's field
4257  * group. We allow one extra logical nesting level, since this group
4258  * will eventually be wrapped in an outer "Workers" group.
4259  */
4260  ExplainOpenSetAsideGroup("Worker", NULL, true, 2, es);
4261 
4262  /*
4263  * In non-TEXT formats we always emit a "Worker Number" field, even if
4264  * there's no other data for this worker.
4265  */
4266  if (es->format != EXPLAIN_FORMAT_TEXT)
4267  ExplainPropertyInteger("Worker Number", NULL, n, es);
4268 
4269  wstate->worker_inited[n] = true;
4270  }
4271  else
4272  {
4273  /* Resuming output for a worker we've already emitted some data for */
4274  es->str = &wstate->worker_str[n];
4275 
4276  /* Restore formatting state saved by last ExplainCloseWorker() */
4277  ExplainRestoreGroup(es, 2, &wstate->worker_state_save[n]);
4278  }
4279 
4280  /*
4281  * In TEXT format, prefix the first output line for this worker with
4282  * "Worker N:". Then, any additional lines should be indented one more
4283  * stop than the "Worker N" line is.
4284  */
4285  if (es->format == EXPLAIN_FORMAT_TEXT)
4286  {
4287  if (es->str->len == 0)
4288  {
4289  ExplainIndentText(es);
4290  appendStringInfo(es->str, "Worker %d: ", n);
4291  }
4292 
4293  es->indent++;
4294  }
4295 }
static void ExplainRestoreGroup(ExplainState *es, int depth, int *state_save)
Definition: explain.c:4787
static void ExplainOpenSetAsideGroup(const char *objtype, const char *labelname, bool labeled, int depth, ExplainState *es)
Definition: explain.c:4718
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References appendStringInfo(), Assert(), EXPLAIN_FORMAT_TEXT, ExplainIndentText(), ExplainOpenSetAsideGroup(), ExplainPropertyInteger(), ExplainRestoreGroup(), ExplainState::format, ExplainState::indent, initStringInfo(), StringInfoData::len, ExplainWorkersState::prev_str, ExplainState::str, ExplainWorkersState::worker_inited, ExplainWorkersState::worker_state_save, ExplainWorkersState::worker_str, and ExplainState::workers_state.

Referenced by ExplainNode(), show_hashagg_info(), show_incremental_sort_info(), show_memoize_info(), and show_sort_info().

◆ ExplainPreScanNode()

static bool ExplainPreScanNode ( PlanState planstate,
Bitmapset **  rels_used 
)
static

Definition at line 1092 of file explain.c.

1093 {
1094  Plan *plan = planstate->plan;
1095 
1096  switch (nodeTag(plan))
1097  {
1098  case T_SeqScan:
1099  case T_SampleScan:
1100  case T_IndexScan:
1101  case T_IndexOnlyScan:
1102  case T_BitmapHeapScan:
1103  case T_TidScan:
1104  case T_TidRangeScan:
1105  case T_SubqueryScan:
1106  case T_FunctionScan:
1107  case T_TableFuncScan:
1108  case T_ValuesScan:
1109  case T_CteScan:
1110  case T_NamedTuplestoreScan:
1111  case T_WorkTableScan:
1112  *rels_used = bms_add_member(*rels_used,
1113  ((Scan *) plan)->scanrelid);
1114  break;
1115  case T_ForeignScan:
1116  *rels_used = bms_add_members(*rels_used,
1117  ((ForeignScan *) plan)->fs_relids);
1118  break;
1119  case T_CustomScan:
1120  *rels_used = bms_add_members(*rels_used,
1121  ((CustomScan *) plan)->custom_relids);
1122  break;
1123  case T_ModifyTable:
1124  *rels_used = bms_add_member(*rels_used,
1125  ((ModifyTable *) plan)->nominalRelation);
1126  if (((ModifyTable *) plan)->exclRelRTI)
1127  *rels_used = bms_add_member(*rels_used,
1128  ((ModifyTable *) plan)->exclRelRTI);
1129  break;
1130  case T_Append:
1131  *rels_used = bms_add_members(*rels_used,
1132  ((Append *) plan)->apprelids);
1133  break;
1134  case T_MergeAppend:
1135  *rels_used = bms_add_members(*rels_used,
1136  ((MergeAppend *) plan)->apprelids);
1137  break;
1138  default:
1139  break;
1140  }
1141 
1142  return planstate_tree_walker(planstate, ExplainPreScanNode, rels_used);
1143 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:796
static bool ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used)
Definition: explain.c:1092
#define planstate_tree_walker(ps, w, c)
Definition: nodeFuncs.h:177

References bms_add_member(), bms_add_members(), nodeTag, PlanState::plan, and planstate_tree_walker.

Referenced by ExplainPrintPlan().

◆ ExplainPrintJIT()

static void ExplainPrintJIT ( ExplainState es,
int  jit_flags,
JitInstrumentation ji 
)
static

Definition at line 875 of file explain.c.

876 {
877  instr_time total_time;
878 
879  /* don't print information if no JITing happened */
880  if (!ji || ji->created_functions == 0)
881  return;
882 
883  /* calculate total time */
884  INSTR_TIME_SET_ZERO(total_time);
885  INSTR_TIME_ADD(total_time, ji->generation_counter);
886  INSTR_TIME_ADD(total_time, ji->inlining_counter);
887  INSTR_TIME_ADD(total_time, ji->optimization_counter);
888  INSTR_TIME_ADD(total_time, ji->emission_counter);
889 
890  ExplainOpenGroup("JIT", "JIT", true, es);
891 
892  /* for higher density, open code the text output format */
893  if (es->format == EXPLAIN_FORMAT_TEXT)
894  {
895  ExplainIndentText(es);
896  appendStringInfoString(es->str, "JIT:\n");
897  es->indent++;
898 
899  ExplainPropertyInteger("Functions", NULL, ji->created_functions, es);
900 
901  ExplainIndentText(es);
902  appendStringInfo(es->str, "Options: %s %s, %s %s, %s %s, %s %s\n",
903  "Inlining", jit_flags & PGJIT_INLINE ? "true" : "false",
904  "Optimization", jit_flags & PGJIT_OPT3 ? "true" : "false",
905  "Expressions", jit_flags & PGJIT_EXPR ? "true" : "false",
906  "Deforming", jit_flags & PGJIT_DEFORM ? "true" : "false");
907 
908  if (es->analyze && es->timing)
909  {
910  ExplainIndentText(es);
911  appendStringInfo(es->str,
912  "Timing: %s %.3f ms, %s %.3f ms, %s %.3f ms, %s %.3f ms, %s %.3f ms\n",
913  "Generation", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->generation_counter),
914  "Inlining", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->inlining_counter),
915  "Optimization", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->optimization_counter),
916  "Emission", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->emission_counter),
917  "Total", 1000.0 * INSTR_TIME_GET_DOUBLE(total_time));
918  }
919 
920  es->indent--;
921  }
922  else
923  {
924  ExplainPropertyInteger("Functions", NULL, ji->created_functions, es);
925 
926  ExplainOpenGroup("Options", "Options", true, es);
927  ExplainPropertyBool("Inlining", jit_flags & PGJIT_INLINE, es);
928  ExplainPropertyBool("Optimization", jit_flags & PGJIT_OPT3, es);
929  ExplainPropertyBool("Expressions", jit_flags & PGJIT_EXPR, es);
930  ExplainPropertyBool("Deforming", jit_flags & PGJIT_DEFORM, es);
931  ExplainCloseGroup("Options", "Options", true, es);
932 
933  if (es->analyze && es->timing)
934  {
935  ExplainOpenGroup("Timing", "Timing", true, es);
936 
937  ExplainPropertyFloat("Generation", "ms",
939  3, es);
940  ExplainPropertyFloat("Inlining", "ms",
942  3, es);
943  ExplainPropertyFloat("Optimization", "ms",
945  3, es);
946  ExplainPropertyFloat("Emission", "ms",
948  3, es);
949  ExplainPropertyFloat("Total", "ms",
950  1000.0 * INSTR_TIME_GET_DOUBLE(total_time),
951  3, es);
952 
953  ExplainCloseGroup("Timing", "Timing", true, es);
954  }
955  }
956 
957  ExplainCloseGroup("JIT", "JIT", true, es);
958 }
#define INSTR_TIME_ADD(x, y)
Definition: instr_time.h:91
#define INSTR_TIME_SET_ZERO(t)
Definition: instr_time.h:87
#define PGJIT_OPT3
Definition: jit.h:21
#define PGJIT_EXPR
Definition: jit.h:23
#define PGJIT_DEFORM
Definition: jit.h:24
#define PGJIT_INLINE
Definition: jit.h:22
instr_time generation_counter
Definition: jit.h:33
size_t created_functions
Definition: jit.h:30
instr_time optimization_counter
Definition: jit.h:39
instr_time emission_counter
Definition: jit.h:42
instr_time inlining_counter
Definition: jit.h:36

References ExplainState::analyze, appendStringInfo(), appendStringInfoString(), JitInstrumentation::created_functions, JitInstrumentation::emission_counter, EXPLAIN_FORMAT_TEXT, ExplainCloseGroup(), ExplainIndentText(), ExplainOpenGroup(), ExplainPropertyBool(), ExplainPropertyFloat(), ExplainPropertyInteger(), ExplainState::format, JitInstrumentation::generation_counter, ExplainState::indent, JitInstrumentation::inlining_counter, INSTR_TIME_ADD, INSTR_TIME_GET_DOUBLE, INSTR_TIME_SET_ZERO, JitInstrumentation::optimization_counter, PGJIT_DEFORM, PGJIT_EXPR, PGJIT_INLINE, PGJIT_OPT3, ExplainState::str, and ExplainState::timing.

Referenced by ExplainNode(), and ExplainPrintJITSummary().

◆ ExplainPrintJITSummary()

void ExplainPrintJITSummary ( ExplainState es,
QueryDesc queryDesc 
)

Definition at line 849 of file explain.c.

850 {
851  JitInstrumentation ji = {0};
852 
853  if (!(queryDesc->estate->es_jit_flags & PGJIT_PERFORM))
854  return;
855 
856  /*
857  * Work with a copy instead of modifying the leader state, since this
858  * function may be called twice
859  */
860  if (queryDesc->estate->es_jit)
861  InstrJitAgg(&ji, &queryDesc->estate->es_jit->instr);
862 
863  /* If this process has done JIT in parallel workers, merge stats */
864  if (queryDesc->estate->es_jit_worker_instr)
865  InstrJitAgg(&ji, queryDesc->estate->es_jit_worker_instr);
866 
867  ExplainPrintJIT(es, queryDesc->estate->es_jit_flags, &ji);
868 }
void InstrJitAgg(JitInstrumentation *dst, JitInstrumentation *add)
Definition: jit.c:184
#define PGJIT_PERFORM
Definition: jit.h:20
struct JitContext * es_jit
Definition: execnodes.h:701
struct JitInstrumentation * es_jit_worker_instr
Definition: execnodes.h:702
JitInstrumentation instr
Definition: jit.h:61
EState * estate
Definition: execdesc.h:48

References EState::es_jit, EState::es_jit_flags, EState::es_jit_worker_instr, QueryDesc::estate, ExplainPrintJIT(), JitContext::instr, InstrJitAgg(), and PGJIT_PERFORM.

Referenced by explain_ExecutorEnd(), and ExplainOnePlan().

◆ ExplainPrintPlan()

void ExplainPrintPlan ( ExplainState es,
QueryDesc queryDesc 
)

Definition at line 757 of file explain.c.

758 {
759  Bitmapset *rels_used = NULL;
760  PlanState *ps;
761 
762  /* Set up ExplainState fields associated with this plan tree */
763  Assert(queryDesc->plannedstmt != NULL);
764  es->pstmt = queryDesc->plannedstmt;
765  es->rtable = queryDesc->plannedstmt->rtable;
766  ExplainPreScanNode(queryDesc->planstate, &rels_used);
769  es->rtable_names);
770  es->printed_subplans = NULL;
771 
772  /*
773  * Sometimes we mark a Gather node as "invisible", which means that it's
774  * not to be displayed in EXPLAIN output. The purpose of this is to allow
775  * running regression tests with force_parallel_mode=regress to get the
776  * same results as running the same tests with force_parallel_mode=off.
777  * Such marking is currently only supported on a Gather at the top of the
778  * plan. We skip that node, and we must also hide per-worker detail data
779  * further down in the plan tree.
780  */
781  ps = queryDesc->planstate;
782  if (IsA(ps, GatherState) && ((Gather *) ps->plan)->invisible)
783  {
784  ps = outerPlanState(ps);
785  es->hide_workers = true;
786  }
787  ExplainNode(ps, NIL, NULL, NULL, es);
788 
789  /*
790  * If requested, include information about GUC parameters with values that
791  * don't match the built-in defaults.
792  */
794 }
static void ExplainPrintSettings(ExplainState *es)
Definition: explain.c:687
List * select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
Definition: ruleutils.c:3793
List * deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
Definition: ruleutils.c:3701
Bitmapset * printed_subplans
Definition: explain.h:58
List * rtable_names
Definition: explain.h:56
List * rtable
Definition: explain.h:55
PlannedStmt * pstmt
Definition: explain.h:54
List * deparse_cxt
Definition: explain.h:57
List * rtable
Definition: plannodes.h:76
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * planstate
Definition: execdesc.h:49

References Assert(), deparse_context_for_plan_tree(), ExplainState::deparse_cxt, ExplainNode(), ExplainPreScanNode(), ExplainPrintSettings(), ExplainState::hide_workers, IsA, NIL, outerPlanState, PlanState::plan, QueryDesc::plannedstmt, QueryDesc::planstate, ExplainState::printed_subplans, ExplainState::pstmt, ExplainState::rtable, PlannedStmt::rtable, ExplainState::rtable_names, and select_rtable_names_for_explain().

Referenced by explain_ExecutorEnd(), and ExplainOnePlan().

◆ ExplainPrintSettings()

static void ExplainPrintSettings ( ExplainState es)
static

Definition at line 687 of file explain.c.

688 {
689  int num;
690  struct config_generic **gucs;
691 
692  /* bail out if information about settings not requested */
693  if (!es->settings)
694  return;
695 
696  /* request an array of relevant settings */
697  gucs = get_explain_guc_options(&num);
698 
699  if (es->format != EXPLAIN_FORMAT_TEXT)
700  {
701  ExplainOpenGroup("Settings", "Settings", true, es);
702 
703  for (int i = 0; i < num; i++)
704  {
705  char *setting;
706  struct config_generic *conf = gucs[i];
707 
708  setting = GetConfigOptionByName(conf->name, NULL, true);
709 
710  ExplainPropertyText(conf->name, setting, es);
711  }
712 
713  ExplainCloseGroup("Settings", "Settings", true, es);
714  }
715  else
716  {
718 
719  /* In TEXT mode, print nothing if there are no options */
720  if (num <= 0)
721  return;
722 
724 
725  for (int i = 0; i < num; i++)
726  {
727  char *setting;
728  struct config_generic *conf = gucs[i];
729 
730  if (i > 0)
731  appendStringInfoString(&str, ", ");
732 
733  setting = GetConfigOptionByName(conf->name, NULL, true);
734 
735  if (setting)
736  appendStringInfo(&str, "%s = '%s'", conf->name, setting);
737  else
738  appendStringInfo(&str, "%s = NULL", conf->name);
739  }
740 
741  ExplainPropertyText("Settings", str.data, es);
742  }
743 }
struct config_generic ** get_explain_guc_options(int *num)
Definition: guc.c:5139
char * GetConfigOptionByName(const char *name, const char **varname, bool missing_ok)
Definition: guc.c:5235
bool settings
Definition: explain.h:48
const char * name
Definition: guc_tables.h:155

References appendStringInfo(), appendStringInfoString(), EXPLAIN_FORMAT_TEXT, ExplainCloseGroup(), ExplainOpenGroup(), ExplainPropertyText(), ExplainState::format, get_explain_guc_options(), GetConfigOptionByName(), i, initStringInfo(), config_generic::name, ExplainState::settings, and generate_unaccent_rules::str.

Referenced by ExplainPrintPlan().

◆ ExplainPrintTriggers()

void ExplainPrintTriggers ( ExplainState es,
QueryDesc queryDesc 
)

Definition at line 806 of file explain.c.

807 {
808  ResultRelInfo *rInfo;
809  bool show_relname;
810  List *resultrels;
811  List *routerels;
812  List *targrels;
813  ListCell *l;
814 
815  resultrels = queryDesc->estate->es_opened_result_relations;
816  routerels = queryDesc->estate->es_tuple_routing_result_relations;
817  targrels = queryDesc->estate->es_trig_target_relations;
818 
819  ExplainOpenGroup("Triggers", "Triggers", false, es);
820 
821  show_relname = (list_length(resultrels) > 1 ||
822  routerels != NIL || targrels != NIL);
823  foreach(l, resultrels)
824  {
825  rInfo = (ResultRelInfo *) lfirst(l);
826  report_triggers(rInfo, show_relname, es);
827  }
828 
829  foreach(l, routerels)
830  {
831  rInfo = (ResultRelInfo *) lfirst(l);
832  report_triggers(rInfo, show_relname, es);
833  }
834 
835  foreach(l, targrels)
836  {
837  rInfo = (ResultRelInfo *) lfirst(l);
838  report_triggers(rInfo, show_relname, es);
839  }
840 
841  ExplainCloseGroup("Triggers", "Triggers", false, es);
842 }
static void report_triggers(ResultRelInfo *rInfo, bool show_relname, ExplainState *es)
Definition: explain.c:1002
List * es_tuple_routing_result_relations
Definition: execnodes.h:643
List * es_trig_target_relations
Definition: execnodes.h:646
List * es_opened_result_relations
Definition: execnodes.h:633

References EState::es_opened_result_relations, EState::es_trig_target_relations, EState::es_tuple_routing_result_relations, QueryDesc::estate, ExplainCloseGroup(), ExplainOpenGroup(), lfirst, list_length(), NIL, and report_triggers().

Referenced by explain_ExecutorEnd(), and ExplainOnePlan().

◆ ExplainProperty()

static void ExplainProperty ( const char *  qlabel,
const char *  unit,
const char *  value,
bool  numeric,
ExplainState es 
)
static

Definition at line 4490 of file explain.c.

4492 {
4493  switch (es->format)
4494  {
4495  case EXPLAIN_FORMAT_TEXT:
4496  ExplainIndentText(es);
4497  if (unit)
4498  appendStringInfo(es->str, "%s: %s %s\n", qlabel, value, unit);
4499  else
4500  appendStringInfo(es->str, "%s: %s\n", qlabel, value);
4501  break;
4502 
4503  case EXPLAIN_FORMAT_XML:
4504  {
4505  char *str;
4506 
4507  appendStringInfoSpaces(es->str, es->indent * 2);
4508  ExplainXMLTag(qlabel, X_OPENING | X_NOWHITESPACE, es);
4509  str = escape_xml(value);
4511  pfree(str);
4512  ExplainXMLTag(qlabel, X_CLOSING | X_NOWHITESPACE, es);
4513  appendStringInfoChar(es->str, '\n');
4514  }
4515  break;
4516 
4517  case EXPLAIN_FORMAT_JSON:
4519  appendStringInfoSpaces(es->str, es->indent * 2);
4520  escape_json(es->str, qlabel);
4521  appendStringInfoString(es->str, ": ");
4522  if (numeric)
4524  else
4525  escape_json(es->str, value);
4526  break;
4527 
4528  case EXPLAIN_FORMAT_YAML:
4530  appendStringInfo(es->str, "%s: ", qlabel);
4531  if (numeric)
4533  else
4534  escape_yaml(es->str, value);
4535  break;
4536  }
4537 }
#define X_NOWHITESPACE
Definition: explain.c:55
static struct @143 value
char * escape_xml(const char *str)
Definition: xml.c:2352

References appendStringInfo(), appendStringInfoChar(), appendStringInfoSpaces(), appendStringInfoString(), escape_json(), escape_xml(), escape_yaml(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainIndentText(), ExplainJSONLineEnding(), ExplainXMLTag(), ExplainYAMLLineStarting(), ExplainState::format, ExplainState::indent, pfree(), generate_unaccent_rules::str, ExplainState::str, value, X_CLOSING, X_NOWHITESPACE, and X_OPENING.

Referenced by ExplainPropertyBool(), ExplainPropertyFloat(), ExplainPropertyInteger(), ExplainPropertyText(), and ExplainPropertyUInteger().

◆ ExplainPropertyBool()

void ExplainPropertyBool ( const char *  qlabel,
bool  value,
ExplainState es 
)

Definition at line 4593 of file explain.c.

4594 {
4595  ExplainProperty(qlabel, NULL, value ? "true" : "false", true, es);
4596 }
static void ExplainProperty(const char *qlabel, const char *unit, const char *value, bool numeric, ExplainState *es)
Definition: explain.c:4490

References ExplainProperty(), and value.

Referenced by ExplainNode(), and ExplainPrintJIT().

◆ ExplainPropertyFloat()

void ExplainPropertyFloat ( const char *  qlabel,
const char *  unit,
double  value,
int  ndigits,
ExplainState es 
)

Definition at line 4579 of file explain.c.

4581 {
4582  char *buf;
4583 
4584  buf = psprintf("%.*f", ndigits, value);
4585  ExplainProperty(qlabel, unit, buf, true, es);
4586  pfree(buf);
4587 }

References buf, ExplainProperty(), pfree(), psprintf(), and value.

Referenced by ExplainNode(), ExplainOnePlan(), ExplainPrintJIT(), report_triggers(), show_buffer_usage(), show_instrumentation_count(), and show_modifytable_info().

◆ ExplainPropertyInteger()

void ExplainPropertyInteger ( const char *  qlabel,
const char *  unit,
int64  value,
ExplainState es 
)

◆ ExplainPropertyList()

void ExplainPropertyList ( const char *  qlabel,
List data,
ExplainState es 
)

Definition at line 4367 of file explain.c.

4368 {
4369  ListCell *lc;
4370  bool first = true;
4371 
4372  switch (es->format)
4373  {
4374  case EXPLAIN_FORMAT_TEXT:
4375  ExplainIndentText(es);
4376  appendStringInfo(es->str, "%s: ", qlabel);
4377  foreach(lc, data)
4378  {
4379  if (!first)
4380  appendStringInfoString(es->str, ", ");
4381  appendStringInfoString(es->str, (const char *) lfirst(lc));
4382  first = false;
4383  }
4384  appendStringInfoChar(es->str, '\n');
4385  break;
4386 
4387  case EXPLAIN_FORMAT_XML:
4388  ExplainXMLTag(qlabel, X_OPENING, es);
4389  foreach(lc, data)
4390  {
4391  char *str;
4392 
4393  appendStringInfoSpaces(es->str, es->indent * 2 + 2);
4394  appendStringInfoString(es->str, "<Item>");
4395  str = escape_xml((const char *) lfirst(lc));
4397  pfree(str);
4398  appendStringInfoString(es->str, "</Item>\n");
4399  }
4400  ExplainXMLTag(qlabel, X_CLOSING, es);
4401  break;
4402 
4403  case EXPLAIN_FORMAT_JSON:
4405  appendStringInfoSpaces(es->str, es->indent * 2);
4406  escape_json(es->str, qlabel);
4407  appendStringInfoString(es->str, ": [");
4408  foreach(lc, data)
4409  {
4410  if (!first)
4411  appendStringInfoString(es->str, ", ");
4412  escape_json(es->str, (const char *) lfirst(lc));
4413  first = false;
4414  }
4415  appendStringInfoChar(es->str, ']');
4416  break;
4417 
4418  case EXPLAIN_FORMAT_YAML:
4420  appendStringInfo(es->str, "%s: ", qlabel);
4421  foreach(lc, data)
4422  {
4423  appendStringInfoChar(es->str, '\n');
4424  appendStringInfoSpaces(es->str, es->indent * 2 + 2);
4425  appendStringInfoString(es->str, "- ");
4426  escape_yaml(es->str, (const char *) lfirst(lc));
4427  }
4428  break;
4429  }
4430 }
const void * data

References appendStringInfo(), appendStringInfoChar(), appendStringInfoSpaces(), appendStringInfoString(), data, escape_json(), escape_xml(), escape_yaml(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainIndentText(), ExplainJSONLineEnding(), ExplainXMLTag(), ExplainYAMLLineStarting(), ExplainState::format, ExplainState::indent, lfirst, pfree(), generate_unaccent_rules::str, ExplainState::str, X_CLOSING, and X_OPENING.

Referenced by ExplainPropertyListNested(), show_eval_params(), show_incremental_sort_group_info(), show_modifytable_info(), show_plan_tlist(), show_sort_group_keys(), and show_tablesample().

◆ ExplainPropertyListNested()

void ExplainPropertyListNested ( const char *  qlabel,
List data,
ExplainState es 
)

Definition at line 4437 of file explain.c.

4438 {
4439  ListCell *lc;
4440  bool first = true;
4441 
4442  switch (es->format)
4443  {
4444  case EXPLAIN_FORMAT_TEXT:
4445  case EXPLAIN_FORMAT_XML:
4446  ExplainPropertyList(qlabel, data, es);
4447  return;
4448 
4449  case EXPLAIN_FORMAT_JSON:
4451  appendStringInfoSpaces(es->str, es->indent * 2);
4452  appendStringInfoChar(es->str, '[');
4453  foreach(lc, data)
4454  {
4455  if (!first)
4456  appendStringInfoString(es->str, ", ");
4457  escape_json(es->str, (const char *) lfirst(lc));
4458  first = false;
4459  }
4460  appendStringInfoChar(es->str, ']');
4461  break;
4462 
4463  case EXPLAIN_FORMAT_YAML:
4465  appendStringInfoString(es->str, "- [");
4466  foreach(lc, data)
4467  {
4468  if (!first)
4469  appendStringInfoString(es->str, ", ");
4470  escape_yaml(es->str, (const char *) lfirst(lc));
4471  first = false;
4472  }
4473  appendStringInfoChar(es->str, ']');
4474  break;
4475  }
4476 }
void ExplainPropertyList(const char *qlabel, List *data, ExplainState *es)
Definition: explain.c:4367

References appendStringInfoChar(), appendStringInfoSpaces(), appendStringInfoString(), data, escape_json(), escape_yaml(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainJSONLineEnding(), ExplainPropertyList(), ExplainYAMLLineStarting(), ExplainState::format, ExplainState::indent, lfirst, and ExplainState::str.

Referenced by show_grouping_set_keys().

◆ ExplainPropertyText()

◆ ExplainPropertyUInteger()

void ExplainPropertyUInteger ( const char *  qlabel,
const char *  unit,
uint64  value,
ExplainState es 
)

Definition at line 4565 of file explain.c.

4567 {
4568  char buf[32];
4569 
4570  snprintf(buf, sizeof(buf), UINT64_FORMAT, value);
4571  ExplainProperty(qlabel, unit, buf, true, es);
4572 }
#define UINT64_FORMAT
Definition: c.h:485

References buf, ExplainProperty(), snprintf, UINT64_FORMAT, and value.

Referenced by show_wal_usage().

◆ ExplainQuery()

void ExplainQuery ( ParseState pstate,
ExplainStmt stmt,
ParamListInfo  params,
DestReceiver dest 
)

Definition at line 164 of file explain.c.

166 {
168  TupOutputState *tstate;
169  JumbleState *jstate = NULL;
170  Query *query;
171  List *rewritten;
172  ListCell *lc;
173  bool timing_set = false;
174  bool summary_set = false;
175 
176  /* Parse options list. */
177  foreach(lc, stmt->options)
178  {
179  DefElem *opt = (DefElem *) lfirst(lc);
180 
181  if (strcmp(opt->defname, "analyze") == 0)
182  es->analyze = defGetBoolean(opt);
183  else if (strcmp(opt->defname, "verbose") == 0)
184  es->verbose = defGetBoolean(opt);
185  else if (strcmp(opt->defname, "costs") == 0)
186  es->costs = defGetBoolean(opt);
187  else if (strcmp(opt->defname, "buffers") == 0)
188  es->buffers = defGetBoolean(opt);
189  else if (strcmp(opt->defname, "wal") == 0)
190  es->wal = defGetBoolean(opt);
191  else if (strcmp(opt->defname, "settings") == 0)
192  es->settings = defGetBoolean(opt);
193  else if (strcmp(opt->defname, "timing") == 0)
194  {
195  timing_set = true;
196  es->timing = defGetBoolean(opt);
197  }
198  else if (strcmp(opt->defname, "summary") == 0)
199  {
200  summary_set = true;
201  es->summary = defGetBoolean(opt);
202  }
203  else if (strcmp(opt->defname, "format") == 0)
204  {
205  char *p = defGetString(opt);
206 
207  if (strcmp(p, "text") == 0)
209  else if (strcmp(p, "xml") == 0)
211  else if (strcmp(p, "json") == 0)
213  else if (strcmp(p, "yaml") == 0)
215  else
216  ereport(ERROR,
217  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
218  errmsg("unrecognized value for EXPLAIN option \"%s\": \"%s\"",
219  opt->defname, p),
220  parser_errposition(pstate, opt->location)));
221  }
222  else
223  ereport(ERROR,
224  (errcode(ERRCODE_SYNTAX_ERROR),
225  errmsg("unrecognized EXPLAIN option \"%s\"",
226  opt->defname),
227  parser_errposition(pstate, opt->location)));
228  }
229 
230  if (es->wal && !es->analyze)
231  ereport(ERROR,
232  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
233  errmsg("EXPLAIN option WAL requires ANALYZE")));
234 
235  /* if the timing was not set explicitly, set default value */
236  es->timing = (timing_set) ? es->timing : es->analyze;
237 
238  /* check that timing is used with EXPLAIN ANALYZE */
239  if (es->timing && !es->analyze)
240  ereport(ERROR,
241  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
242  errmsg("EXPLAIN option TIMING requires ANALYZE")));
243 
244  /* if the summary was not set explicitly, set default value */
245  es->summary = (summary_set) ? es->summary : es->analyze;
246 
247  query = castNode(Query, stmt->query);
248  if (IsQueryIdEnabled())
249  jstate = JumbleQuery(query, pstate->p_sourcetext);
250 
252  (*post_parse_analyze_hook) (pstate, query, jstate);
253 
254  /*
255  * Parse analysis was done already, but we still have to run the rule
256  * rewriter. We do not do AcquireRewriteLocks: we assume the query either
257  * came straight from the parser, or suitable locks were acquired by
258  * plancache.c.
259  */
260  rewritten = QueryRewrite(castNode(Query, stmt->query));
261 
262  /* emit opening boilerplate */
263  ExplainBeginOutput(es);
264 
265  if (rewritten == NIL)
266  {
267  /*
268  * In the case of an INSTEAD NOTHING, tell at least that. But in
269  * non-text format, the output is delimited, so this isn't necessary.
270  */
271  if (es->format == EXPLAIN_FORMAT_TEXT)
272  appendStringInfoString(es->str, "Query rewrites to nothing\n");
273  }
274  else
275  {
276  ListCell *l;
277 
278  /* Explain every plan */
279  foreach(l, rewritten)
280  {
282  CURSOR_OPT_PARALLEL_OK, NULL, es,
283  pstate->p_sourcetext, params, pstate->p_queryEnv);
284 
285  /* Separate plans with an appropriate separator */
286  if (lnext(rewritten, l) != NULL)
288  }
289  }
290 
291  /* emit closing boilerplate */
292  ExplainEndOutput(es);
293  Assert(es->indent == 0);
294 
295  /* output tuples */
297  &TTSOpsVirtual);
298  if (es->format == EXPLAIN_FORMAT_TEXT)
299  do_text_output_multiline(tstate, es->str->data);
300  else
301  do_text_output_oneline(tstate, es->str->data);
302  end_tup_output(tstate);
303 
304  pfree(es->str->data);
305 }
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
void end_tup_output(TupOutputState *tstate)
Definition: execTuples.c:2333
void do_text_output_multiline(TupOutputState *tstate, const char *txt)
Definition: execTuples.c:2303
TupOutputState * begin_tup_output_tupdesc(DestReceiver *dest, TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2255
#define do_text_output_oneline(tstate, str_to_emit)
Definition: executor.h:507
void ExplainSeparatePlans(ExplainState *es)
Definition: explain.c:4924
void ExplainEndOutput(ExplainState *es)
Definition: explain.c:4895
TupleDesc ExplainResultDesc(ExplainStmt *stmt)
Definition: explain.c:328
void ExplainBeginOutput(ExplainState *es)
Definition: explain.c:4864
ExplainState * NewExplainState(void)
Definition: explain.c:311
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:59
#define lfirst_node(type, lc)
Definition: pg_list.h:174
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
JumbleState * JumbleQuery(Query *query, const char *querytext)
Definition: queryjumble.c:102
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:77
char * defname
Definition: parsenodes.h:777
int location
Definition: parsenodes.h:781
Node * query
Definition: parsenodes.h:3479
List * options
Definition: parsenodes.h:3480
const char * p_sourcetext
Definition: parse_node.h:182

References ExplainState::analyze, appendStringInfoString(), Assert(), begin_tup_output_tupdesc(), ExplainState::buffers, castNode, ExplainState::costs, CURSOR_OPT_PARALLEL_OK, StringInfoData::data, defGetBoolean(), defGetString(), DefElem::defname, generate_unaccent_rules::dest, do_text_output_multiline(), do_text_output_oneline, end_tup_output(), ereport, errcode(), errmsg(), ERROR, EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainBeginOutput(), ExplainEndOutput(), ExplainOneQuery(), ExplainResultDesc(), ExplainSeparatePlans(), ExplainState::format, if(), ExplainState::indent, IsQueryIdEnabled(), JumbleQuery(), lfirst, lfirst_node, lnext(), DefElem::location, NewExplainState(), NIL, ExplainStmt::options, ParseState::p_queryEnv, ParseState::p_sourcetext, parser_errposition(), pfree(), post_parse_analyze_hook, ExplainStmt::query, QueryRewrite(), ExplainState::settings, ExplainState::str, ExplainState::summary, ExplainState::timing, TTSOpsVirtual, ExplainState::verbose, and ExplainState::wal.

Referenced by standard_ProcessUtility().

◆ ExplainQueryParameters()

void ExplainQueryParameters ( ExplainState es,
ParamListInfo  params,
int  maxlen 
)

Definition at line 984 of file explain.c.

985 {
986  char *str;
987 
988  /* This check is consistent with errdetail_params() */
989  if (params == NULL || params->numParams <= 0 || maxlen == 0)
990  return;
991 
992  str = BuildParamLogString(params, NULL, maxlen);
993  if (str && str[0] != '\0')
994  ExplainPropertyText("Query Parameters", str, es);
995 }
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335

References BuildParamLogString(), ExplainPropertyText(), ParamListInfoData::numParams, and generate_unaccent_rules::str.

Referenced by explain_ExecutorEnd().

◆ ExplainQueryText()

void ExplainQueryText ( ExplainState es,
QueryDesc queryDesc 
)

Definition at line 969 of file explain.c.

970 {
971  if (queryDesc->sourceText)
972  ExplainPropertyText("Query Text", queryDesc->sourceText, es);
973 }
const char * sourceText
Definition: execdesc.h:38

References ExplainPropertyText(), and QueryDesc::sourceText.

Referenced by explain_ExecutorEnd().

◆ ExplainRestoreGroup()

static void ExplainRestoreGroup ( ExplainState es,
int  depth,
int *  state_save 
)
static

Definition at line 4787 of file explain.c.

4788 {
4789  switch (es->format)
4790  {
4791  case EXPLAIN_FORMAT_TEXT:
4792  /* nothing to do */
4793  break;
4794 
4795  case EXPLAIN_FORMAT_XML:
4796  es->indent += depth;
4797  break;
4798 
4799  case EXPLAIN_FORMAT_JSON:
4800  es->grouping_stack = lcons_int(*state_save, es->grouping_stack);
4801  es->indent += depth;
4802  break;
4803 
4804  case EXPLAIN_FORMAT_YAML:
4805  es->grouping_stack = lcons_int(*state_save, es->grouping_stack);
4806  es->indent += depth;
4807  break;
4808  }
4809 }

References EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, and lcons_int().

Referenced by ExplainOpenWorker().

◆ ExplainResultDesc()

TupleDesc ExplainResultDesc ( ExplainStmt stmt)

Definition at line 328 of file explain.c.

329 {
330  TupleDesc tupdesc;
331  ListCell *lc;
332  Oid result_type = TEXTOID;
333 
334  /* Check for XML format option */
335  foreach(lc, stmt->options)
336  {
337  DefElem *opt = (DefElem *) lfirst(lc);
338 
339  if (strcmp(opt->defname, "format") == 0)
340  {
341  char *p = defGetString(opt);
342 
343  if (strcmp(p, "xml") == 0)
344  result_type = XMLOID;
345  else if (strcmp(p, "json") == 0)
346  result_type = JSONOID;
347  else
348  result_type = TEXTOID;
349  /* don't "break", as ExplainQuery will use the last value */
350  }
351  }
352 
353  /* Need a tuple descriptor representing a single TEXT or XML column */
354  tupdesc = CreateTemplateTupleDesc(1);
355  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "QUERY PLAN",
356  result_type, -1, 0);
357  return tupdesc;
358 }
int16 AttrNumber
Definition: attnum.h:21
unsigned int Oid
Definition: postgres_ext.h:31
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:583

References CreateTemplateTupleDesc(), defGetString(), DefElem::defname, lfirst, ExplainStmt::options, and TupleDescInitEntry().

Referenced by ExplainQuery(), and UtilityTupleDescriptor().

◆ ExplainSaveGroup()

static void ExplainSaveGroup ( ExplainState es,
int  depth,
int *  state_save 
)
static

Definition at line 4757 of file explain.c.

4758 {
4759  switch (es->format)
4760  {
4761  case EXPLAIN_FORMAT_TEXT:
4762  /* nothing to do */
4763  break;
4764 
4765  case EXPLAIN_FORMAT_XML:
4766  es->indent -= depth;
4767  break;
4768 
4769  case EXPLAIN_FORMAT_JSON:
4770  es->indent -= depth;
4771  *state_save = linitial_int(es->grouping_stack);
4773  break;
4774 
4775  case EXPLAIN_FORMAT_YAML:
4776  es->indent -= depth;
4777  *state_save = linitial_int(es->grouping_stack);
4779  break;
4780  }
4781 }

References EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainState::format, ExplainState::grouping_stack, ExplainState::indent, linitial_int, and list_delete_first().

Referenced by ExplainCloseWorker().

◆ ExplainScanTarget()

static void ExplainScanTarget ( Scan plan,
ExplainState es 
)
static

Definition at line 3768 of file explain.c.

3769 {
3770  ExplainTargetRel((Plan *) plan, plan->scanrelid, es);
3771 }

References ExplainTargetRel(), and Scan::scanrelid.

Referenced by ExplainNode().

◆ ExplainSeparatePlans()

void ExplainSeparatePlans ( ExplainState es)

Definition at line 4924 of file explain.c.

4925 {
4926  switch (es->format)
4927  {
4928  case EXPLAIN_FORMAT_TEXT:
4929  /* add a blank line */
4930  appendStringInfoChar(es->str, '\n');
4931  break;
4932 
4933  case EXPLAIN_FORMAT_XML:
4934  case EXPLAIN_FORMAT_JSON:
4935  case EXPLAIN_FORMAT_YAML:
4936  /* nothing to do */
4937  break;
4938  }
4939 }

References appendStringInfoChar(), EXPLAIN_FORMAT_JSON, EXPLAIN_FORMAT_TEXT, EXPLAIN_FORMAT_XML, EXPLAIN_FORMAT_YAML, ExplainState::format, and ExplainState::str.

Referenced by ExplainExecuteQuery(), and ExplainQuery().

◆ ExplainSubPlans()

static void ExplainSubPlans ( List plans,
List ancestors,
const char *  relationship,
ExplainState es 
)
static

Definition at line 4157 of file explain.c.

4159 {
4160  ListCell *lst;
4161 
4162  foreach(lst, plans)
4163  {
4164  SubPlanState *sps = (SubPlanState *) lfirst(lst);
4165  SubPlan *sp = sps->subplan;
4166 
4167  /*
4168  * There can be multiple SubPlan nodes referencing the same physical
4169  * subplan (same plan_id, which is its index in PlannedStmt.subplans).
4170  * We should print a subplan only once, so track which ones we already
4171  * printed. This state must be global across the plan tree, since the
4172  * duplicate nodes could be in different plan nodes, eg both a bitmap
4173  * indexscan's indexqual and its parent heapscan's recheck qual. (We
4174  * do not worry too much about which plan node we show the subplan as
4175  * attached to in such cases.)
4176  */
4177  if (bms_is_member(sp->plan_id, es->printed_subplans))
4178  continue;
4180  sp->plan_id);
4181 
4182  /*
4183  * Treat the SubPlan node as an ancestor of the plan node(s) within
4184  * it, so that ruleutils.c can find the referents of subplan
4185  * parameters.
4186  */
4187  ancestors = lcons(sp, ancestors);
4188 
4189  ExplainNode(sps->planstate, ancestors,
4190  relationship, sp->plan_name, es);
4191 
4192  ancestors = list_delete_first(ancestors);
4193  }
4194 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
struct PlanState * planstate
Definition: execnodes.h:945
SubPlan * subplan
Definition: execnodes.h:944
int plan_id
Definition: primnodes.h:893
char * plan_name
Definition: primnodes.h:895

References bms_add_member(), bms_is_member(), ExplainNode(), lcons(), lfirst, list_delete_first(), SubPlan::plan_id, SubPlan::plan_name, SubPlanState::planstate, ExplainState::printed_subplans, and SubPlanState::subplan.

Referenced by ExplainNode().

◆ ExplainTargetRel()

static void ExplainTargetRel ( Plan plan,
Index  rti,
ExplainState es 
)
static

Definition at line 3790 of file explain.c.

3791 {
3792  char *objectname = NULL;
3793  char *namespace = NULL;
3794  const char *objecttag = NULL;
3795  RangeTblEntry *rte;
3796  char *refname;
3797 
3798  rte = rt_fetch(rti, es->rtable);
3799  refname = (char *) list_nth(es->rtable_names, rti - 1);
3800  if (refname == NULL)
3801  refname = rte->eref->aliasname;
3802 
3803  switch (nodeTag(plan))
3804  {
3805  case T_SeqScan:
3806  case T_SampleScan:
3807  case T_IndexScan:
3808  case T_IndexOnlyScan:
3809  case T_BitmapHeapScan:
3810  case T_TidScan:
3811  case T_TidRangeScan:
3812  case T_ForeignScan:
3813  case T_CustomScan:
3814  case T_ModifyTable:
3815  /* Assert it's on a real relation */
3816  Assert(rte->rtekind == RTE_RELATION);
3817  objectname = get_rel_name(rte->relid);
3818  if (es->verbose)
3819  namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid));
3820  objecttag = "Relation Name";
3821  break;
3822  case T_FunctionScan:
3823  {
3824  FunctionScan *fscan = (FunctionScan *) plan;
3825 
3826  /* Assert it's on a RangeFunction */
3827  Assert(rte->rtekind == RTE_FUNCTION);
3828 
3829  /*
3830  * If the expression is still a function call of a single
3831  * function, we can get the real name of the function.
3832  * Otherwise, punt. (Even if it was a single function call
3833  * originally, the optimizer could have simplified it away.)
3834  */
3835  if (list_length(fscan->functions) == 1)
3836  {
3837  RangeTblFunction *rtfunc = (RangeTblFunction *) linitial(fscan->functions);
3838 
3839  if (IsA(rtfunc->funcexpr, FuncExpr))
3840  {
3841  FuncExpr *funcexpr = (FuncExpr *) rtfunc->funcexpr;
3842  Oid funcid = funcexpr->funcid;
3843 
3844  objectname = get_func_name(funcid);
3845  if (es->verbose)
3846  namespace = get_namespace_name_or_temp(get_func_namespace(funcid));
3847  }
3848  }
3849  objecttag = "Function Name";
3850  }
3851  break;
3852  case T_TableFuncScan:
3853  Assert(rte->rtekind == RTE_TABLEFUNC);
3854  objectname = "xmltable";
3855  objecttag = "Table Function Name";
3856  break;
3857  case T_ValuesScan:
3858  Assert(rte->rtekind == RTE_VALUES);
3859  break;
3860  case T_CteScan:
3861  /* Assert it's on a non-self-reference CTE */
3862  Assert(rte->rtekind == RTE_CTE);
3863  Assert(!rte->self_reference);
3864  objectname = rte->ctename;
3865  objecttag = "CTE Name";
3866  break;
3867  case T_NamedTuplestoreScan:
3869  objectname = rte->enrname;
3870  objecttag = "Tuplestore Name";
3871  break;
3872  case T_WorkTableScan:
3873  /* Assert it's on a self-reference CTE */
3874  Assert(rte->rtekind == RTE_CTE);
3875  Assert(rte->self_reference);
3876  objectname = rte->ctename;
3877  objecttag = "CTE Name";
3878  break;
3879  default:
3880  break;
3881  }
3882 
3883  if (es->format == EXPLAIN_FORMAT_TEXT)
3884  {
3885  appendStringInfoString(es->str, " on");
3886  if (namespace != NULL)
3887  appendStringInfo(es->str, " %s.%s", quote_identifier(namespace),
3888  quote_identifier(objectname));
3889  else if (objectname != NULL)
3890  appendStringInfo(es->str, " %s", quote_identifier(objectname));
3891  if (objectname == NULL || strcmp(refname, objectname) != 0)
3892  appendStringInfo(es->str, " %s", quote_identifier(refname));
3893  }
3894  else
3895  {
3896  if (objecttag != NULL && objectname != NULL)
3897  ExplainPropertyText(objecttag, objectname, es);
3898  if (namespace != NULL)
3899  ExplainPropertyText("Schema", namespace, es);
3900  ExplainPropertyText("Alias", refname, es);
3901  }
3902 }
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3355
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1590
Oid get_func_namespace(Oid funcid)
Definition: lsyscache.c:1614
@ RTE_CTE
Definition: parsenodes.h:1017
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1018
@ RTE_VALUES
Definition: parsenodes.h:1016
@ RTE_FUNCTION
Definition: parsenodes.h:1014
@ RTE_TABLEFUNC
Definition: parsenodes.h:1015
@ RTE_RELATION
Definition: parsenodes.h:1011
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define linitial(l)
Definition: pg_list.h:176
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297
char * aliasname
Definition: primnodes.h:42
Oid funcid
Definition: primnodes.h:598
List * functions
Definition: plannodes.h:610
char * ctename
Definition: parsenodes.h:1140
bool self_reference
Definition: parsenodes.h:1142
Alias * eref
Definition: parsenodes.h:1176
char * enrname
Definition: parsenodes.h:1169
RTEKind rtekind
Definition: parsenodes.h:1030

References Alias::aliasname, appendStringInfo(), appendStringInfoString(), Assert(), RangeTblEntry::eref, EXPLAIN_FORMAT_TEXT, ExplainPropertyText(), ExplainState::format, RangeTblFunction::funcexpr, FuncExpr::funcid, FunctionScan::functions, get_func_name(), get_func_namespace(), get_namespace_name_or_temp(), get_rel_name(), get_rel_namespace(), IsA, linitial, list_length(), list_nth(), nodeTag, quote_identifier(), RangeTblEntry::relid, rt_fetch, ExplainState::rtable, ExplainState::rtable_names, RTE_CTE, RTE_FUNCTION, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, ExplainState::str, and ExplainState::verbose.

Referenced by ExplainModifyTarget(), ExplainScanTarget(), and show_modifytable_info().

◆ ExplainXMLTag()

static void ExplainXMLTag ( const char *  tagname,
int  flags,
ExplainState es 
)
static

Definition at line 4953 of file explain.c.

4954 {
4955  const char *s;
4956  const char *valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
4957 
4958  if ((flags & X_NOWHITESPACE) == 0)
4959  appendStringInfoSpaces(es->str, 2 * es->indent);
4960  appendStringInfoCharMacro(es->str, '<');
4961  if ((flags & X_CLOSING) != 0)
4962  appendStringInfoCharMacro(es->str, '/');
4963  for (s = tagname; *s; s++)
4964  appendStringInfoChar(es->str, strchr(valid, *s) ? *s : '-');
4965  if ((flags & X_CLOSE_IMMEDIATE) != 0)
4966  appendStringInfoString(es->str, " /");
4967  appendStringInfoCharMacro(es->str, '>');
4968  if ((flags & X_NOWHITESPACE) == 0)
4969  appendStringInfoCharMacro(es->str, '\n');
4970 }
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:128

References appendStringInfoChar(), appendStringInfoCharMacro, appendStringInfoSpaces(), appendStringInfoString(), ExplainState::indent, ExplainState::str, X_CLOSE_IMMEDIATE, X_CLOSING, and X_NOWHITESPACE.

Referenced by ExplainCloseGroup(), ExplainDummyGroup(), ExplainOpenGroup(), ExplainProperty(), and ExplainPropertyList().

◆ ExplainYAMLLineStarting()

static void ExplainYAMLLineStarting ( ExplainState es)
static

◆ NewExplainState()

ExplainState* NewExplainState ( void  )

Definition at line 311 of file explain.c.

312 {
313  ExplainState *es = (ExplainState *) palloc0(sizeof(ExplainState));
314 
315  /* Set default options (most fields can be left as zeroes). */
316  es->costs = true;
317  /* Prepare output buffer. */
318  es->str = makeStringInfo();
319 
320  return es;
321 }
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41

References ExplainState::costs, makeStringInfo(), palloc0(), and ExplainState::str.

Referenced by explain_ExecutorEnd(), and ExplainQuery().

◆ report_triggers()

static void report_triggers ( ResultRelInfo rInfo,
bool  show_relname,
ExplainState es 
)
static

Definition at line 1002 of file explain.c.

1003 {
1004  int nt;
1005 
1006  if (!rInfo->ri_TrigDesc || !rInfo->ri_TrigInstrument)
1007  return;
1008  for (nt = 0; nt < rInfo->ri_TrigDesc->numtriggers; nt++)
1009  {
1010  Trigger *trig = rInfo->ri_TrigDesc->triggers + nt;
1011  Instrumentation *instr = rInfo->ri_TrigInstrument + nt;
1012  char *relname;
1013  char *conname = NULL;
1014 
1015  /* Must clean up instrumentation state */
1016  InstrEndLoop(instr);
1017 
1018  /*
1019  * We ignore triggers that were never invoked; they likely aren't
1020  * relevant to the current query type.
1021  */
1022  if (instr->ntuples == 0)
1023  continue;
1024 
1025  ExplainOpenGroup("Trigger", NULL, true, es);
1026 
1028  if (OidIsValid(trig->tgconstraint))
1029  conname = get_constraint_name(trig->tgconstraint);
1030 
1031  /*
1032  * In text format, we avoid printing both the trigger name and the
1033  * constraint name unless VERBOSE is specified. In non-text formats
1034  * we just print everything.
1035  */
1036  if (es->format == EXPLAIN_FORMAT_TEXT)
1037  {
1038  if (es->verbose || conname == NULL)
1039  appendStringInfo(es->str, "Trigger %s", trig->tgname);
1040  else
1041  appendStringInfoString(es->str, "Trigger");
1042  if (conname)
1043  appendStringInfo(es->str, " for constraint %s", conname);
1044  if (show_relname)
1045  appendStringInfo(es->str, " on %s", relname);
1046  if (es->timing)
1047  appendStringInfo(es->str, ": time=%.3f calls=%.0f\n",
1048  1000.0 * instr->total, instr->ntuples);
1049  else
1050  appendStringInfo(es->str, ": calls=%.0f\n", instr->ntuples);
1051  }
1052  else
1053  {
1054  ExplainPropertyText("Trigger Name", trig->tgname, es);
1055  if (conname)
1056  ExplainPropertyText("Constraint Name", conname, es);
1057  ExplainPropertyText("Relation", relname, es);
1058  if (es->timing)
1059  ExplainPropertyFloat("Time", "ms", 1000.0 * instr->total, 3,
1060  es);
1061  ExplainPropertyFloat("Calls", NULL, instr->ntuples, 0, es);
1062  }
1063 
1064  if (conname)
1065  pfree(conname);
1066 
1067  ExplainCloseGroup("Trigger", NULL, true, es);
1068  }
1069 }
#define OidIsValid(objectId)
Definition: c.h:711
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1107
NameData relname
Definition: pg_class.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:535
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:484
Relation ri_RelationDesc
Definition: execnodes.h:448
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:475
int numtriggers
Definition: reltrigger.h:50
Trigger * triggers
Definition: reltrigger.h:49
Oid tgconstraint
Definition: reltrigger.h:35
char * tgname
Definition: reltrigger.h:27

References appendStringInfo(), appendStringInfoString(), EXPLAIN_FORMAT_TEXT, ExplainCloseGroup(), ExplainOpenGroup(), ExplainPropertyFloat(), ExplainPropertyText(), ExplainState::format, get_constraint_name(), InstrEndLoop(), Instrumentation::ntuples, TriggerDesc::numtriggers, OidIsValid, pfree(), RelationGetRelationName, relname, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigInstrument, ExplainState::str, Trigger::tgconstraint, Trigger::tgname, ExplainState::timing, Instrumentation::total, TriggerDesc::triggers, and ExplainState::verbose.

Referenced by ExplainPrintTriggers().

◆ show_agg_keys()

static void show_agg_keys ( AggState astate,
List ancestors,
ExplainState es 
)
static

Definition at line 2412 of file explain.c.

2414 {
2415  Agg *plan = (Agg *) astate->ss.ps.plan;
2416 
2417  if (plan->numCols > 0 || plan->groupingSets)
2418  {
2419  /* The key columns refer to the tlist of the child plan */
2420  ancestors = lcons(plan, ancestors);
2421 
2422  if (plan->groupingSets)
2423  show_grouping_sets(outerPlanState(astate), plan, ancestors, es);
2424  else
2425  show_sort_group_keys(outerPlanState(astate), "Group Key",
2426  plan->numCols, 0, plan->grpColIdx,
2427  NULL, NULL, NULL,
2428  ancestors, es);
2429 
2430  ancestors = list_delete_first(ancestors);
2431  }
2432 }
static void show_sort_group_keys(PlanState *planstate, const char *qlabel, int nkeys, int nPresortedKeys, AttrNumber *keycols, Oid *sortOperators, Oid *collations, bool *nullsFirst, List *ancestors, ExplainState *es)
Definition: explain.c:2564
static void show_grouping_sets(PlanState *planstate, Agg *agg, List *ancestors, ExplainState *es)
Definition: explain.c:2435
ScanState ss
Definition: execnodes.h:2358
List * groupingSets
Definition: plannodes.h:1024
int numCols
Definition: plannodes.h:1003
PlanState ps
Definition: execnodes.h:1454

References Agg::groupingSets, if(), lcons(), list_delete_first(), Agg::numCols, outerPlanState, PlanState::plan, ScanState::ps, show_grouping_sets(), show_sort_group_keys(), and AggState::ss.

Referenced by ExplainNode().

◆ show_buffer_usage()

static void show_buffer_usage ( ExplainState es,
const BufferUsage usage,
bool  planning 
)
static

Definition at line 3529 of file explain.c.

3530 {
3531  if (es->format == EXPLAIN_FORMAT_TEXT)
3532  {
3533  bool has_shared = (usage->shared_blks_hit > 0 ||
3534  usage->shared_blks_read > 0 ||
3535  usage->shared_blks_dirtied > 0 ||
3536  usage->shared_blks_written > 0);
3537  bool has_local = (usage->local_blks_hit > 0 ||
3538  usage->local_blks_read > 0 ||
3539  usage->local_blks_dirtied > 0 ||
3540  usage->local_blks_written > 0);
3541  bool has_temp = (usage->temp_blks_read > 0 ||
3542  usage->temp_blks_written > 0);
3543  bool has_timing = (!INSTR_TIME_IS_ZERO(usage->blk_read_time) ||
3544  !INSTR_TIME_IS_ZERO(usage->blk_write_time));
3545  bool has_temp_timing = (!INSTR_TIME_IS_ZERO(usage->temp_blk_read_time) ||
3546  !INSTR_TIME_IS_ZERO(usage->temp_blk_write_time));
3547  bool show_planning = (planning && (has_shared ||
3548  has_local || has_temp || has_timing ||
3549  has_temp_timing));
3550 
3551  if (show_planning)
3552  {
3553  ExplainIndentText(es);
3554  appendStringInfoString(es->str, "Planning:\n");
3555  es->indent++;
3556  }
3557 
3558  /* Show only positive counter values. */
3559  if (has_shared || has_local || has_temp)
3560  {
3561  ExplainIndentText(es);
3562  appendStringInfoString(es->str, "Buffers:");
3563 
3564  if (has_shared)
3565  {
3566  appendStringInfoString(es->str, " shared");
3567  if (usage->shared_blks_hit > 0)
3568  appendStringInfo(es->str, " hit=%lld",
3569  (long long) usage->shared_blks_hit);
3570  if (usage->shared_blks_read > 0)
3571  appendStringInfo(es->str, " read=%lld",
3572  (long long) usage->shared_blks_read);
3573  if (usage->shared_blks_dirtied > 0)
3574  appendStringInfo(es->str, " dirtied=%lld",
3575  (long long) usage->shared_blks_dirtied);
3576  if (usage->shared_blks_written > 0)
3577  appendStringInfo(es->str, " written=%lld",
3578  (long long) usage->shared_blks_written);
3579  if (has_local || has_temp)
3580  appendStringInfoChar(es->str, ',');
3581  }
3582  if (has_local)
3583  {
3584  appendStringInfoString(es->str, " local");
3585  if (usage->local_blks_hit > 0)
3586  appendStringInfo(es->str, " hit=%lld",
3587  (long long) usage->local_blks_hit);
3588  if (usage->local_blks_read > 0)
3589  appendStringInfo(es->str, " read=%lld",
3590  (long long) usage->local_blks_read);
3591  if (usage->local_blks_dirtied > 0)
3592  appendStringInfo(es->str, " dirtied=%lld",
3593  (long long) usage->local_blks_dirtied);
3594  if (usage->local_blks_written > 0)
3595  appendStringInfo(es->str, " written=%lld",
3596  (long long) usage->local_blks_written);
3597  if (has_temp)
3598  appendStringInfoChar(es->str, ',');
3599  }
3600  if (has_temp)
3601  {
3602  appendStringInfoString(es->str, " temp");
3603  if (usage->temp_blks_read > 0)
3604  appendStringInfo(es->str, " read=%lld",
3605  (long long) usage->temp_blks_read);
3606  if (usage->temp_blks_written > 0)
3607  appendStringInfo(es->str, " written=%lld",
3608  (long long) usage->temp_blks_written);
3609  }
3610  appendStringInfoChar(es->str, '\n');
3611  }
3612 
3613  /* As above, show only positive counter values. */
3614  if (has_timing || has_temp_timing)
3615  {
3616  ExplainIndentText(es);
3617  appendStringInfoString(es->str, "I/O Timings:");
3618 
3619  if (has_timing)
3620  {
3621  appendStringInfoString(es->str, " shared/local");
3622  if (!INSTR_TIME_IS_ZERO(usage->blk_read_time))
3623  appendStringInfo(es->str, " read=%0.3f",
3624  INSTR_TIME_GET_MILLISEC(usage->blk_read_time));
3625  if (!INSTR_TIME_IS_ZERO(usage->blk_write_time))
3626  appendStringInfo(es->str, " write=%0.3f",
3627  INSTR_TIME_GET_MILLISEC(usage->blk_write_time));
3628  if (has_temp_timing)
3629  appendStringInfoChar(es->str, ',');
3630  }
3631  if (has_temp_timing)
3632  {
3633  appendStringInfoString(es->str, " temp");
3634  if (!INSTR_TIME_IS_ZERO(usage->temp_blk_read_time))
3635  appendStringInfo(es->str, " read=%0.3f",
3636  INSTR_TIME_GET_MILLISEC(usage->temp_blk_read_time));
3637  if (!INSTR_TIME_IS_ZERO(usage->temp_blk_write_time))
3638  appendStringInfo(es->str, " write=%0.3f",
3639  INSTR_TIME_GET_MILLISEC(usage->temp_blk_write_time));
3640  }
3641  appendStringInfoChar(es->str, '\n');
3642  }
3643 
3644  if (show_planning)
3645  es->indent--;
3646  }
3647  else
3648  {
3649  ExplainPropertyInteger("Shared Hit Blocks", NULL,
3650  usage->shared_blks_hit, es);
3651  ExplainPropertyInteger("Shared Read Blocks", NULL,
3652  usage->shared_blks_read, es);
3653  ExplainPropertyInteger("Shared Dirtied Blocks", NULL,
3654  usage->shared_blks_dirtied, es);
3655  ExplainPropertyInteger("Shared Written Blocks", NULL,
3656  usage->shared_blks_written, es);
3657  ExplainPropertyInteger("Local Hit Blocks", NULL,
3658  usage->local_blks_hit, es);
3659  ExplainPropertyInteger("Local Read Blocks", NULL,
3660  usage->local_blks_read, es);
3661  ExplainPropertyInteger("Local Dirtied Blocks", NULL,
3662  usage->local_blks_dirtied, es);
3663  ExplainPropertyInteger("Local Written Blocks", NULL,
3664  usage->local_blks_written, es);
3665  ExplainPropertyInteger("Temp Read Blocks", NULL,
3666  usage->temp_blks_read, es);
3667  ExplainPropertyInteger("Temp Written Blocks", NULL,
3668  usage->temp_blks_written, es);
3669  if (track_io_timing)
3670  {
3671  ExplainPropertyFloat("I/O Read Time", "ms",
3672  INSTR_TIME_GET_MILLISEC(usage->blk_read_time),
3673  3, es);
3674  ExplainPropertyFloat("I/O Write Time", "ms",
3675  INSTR_TIME_GET_MILLISEC(usage->blk_write_time),
3676  3, es);
3677  ExplainPropertyFloat("Temp I/O Read Time", "ms",
3678  INSTR_TIME_GET_MILLISEC(usage->temp_blk_read_time),
3679  3, es);
3680  ExplainPropertyFloat("Temp I/O Write Time", "ms",
3681  INSTR_TIME_GET_MILLISEC(usage->temp_blk_write_time),
3682  3, es);
3683  }
3684  }
3685 }
bool track_io_timing
Definition: bufmgr.c:137
#define INSTR_TIME_IS_ZERO(t)
Definition: instr_time.h:85
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:135
static void usage(const char *progname)
Definition: vacuumlo.c:414

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), EXPLAIN_FORMAT_TEXT, ExplainIndentText(), ExplainPropertyFloat(), ExplainPropertyInteger(), ExplainState::format, ExplainState::indent, INSTR_TIME_GET_MILLISEC, INSTR_TIME_IS_ZERO, ExplainState::str, track_io_timing, and usage().

Referenced by ExplainNode(), and ExplainOnePlan().

◆ show_eval_params()

static void show_eval_params ( Bitmapset bms_params,
ExplainState es 
)
static

Definition at line 3477 of file explain.c.

3478 {
3479  int paramid = -1;
3480  List *params = NIL;
3481 
3482  Assert(bms_params);
3483 
3484  while ((paramid = bms_next_member(bms_params, paramid)) >= 0)
3485  {
3486  char param[32];
3487 
3488  snprintf(param, sizeof(param), "$%d", paramid);
3489  params = lappend(params, pstrdup(param));
3490  }
3491 
3492  if (params)
3493  ExplainPropertyList("Params Evaluated", params, es);
3494 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1047
char * pstrdup(const char *in)
Definition: mcxt.c:1483

References Assert(), bms_next_member(), ExplainPropertyList(), lappend(), NIL, pstrdup(), and snprintf.

Referenced by ExplainNode().

◆ show_expression()

static void show_expression ( Node node,
const char *  qlabel,
PlanState planstate,
List ancestors,
bool  useprefix,
ExplainState es 
)
static

Definition at line 2292 of file explain.c.

2295 {
2296  List *context;
2297  char *exprstr;
2298 
2299  /* Set up deparsing context */
2300  context = set_deparse_context_plan(es->deparse_cxt,
2301  planstate->plan,
2302  ancestors);
2303 
2304  /* Deparse the expression */
2305  exprstr = deparse_expression(node, context, useprefix, false);
2306 
2307  /* And add to es->str */
2308  ExplainPropertyText(qlabel, exprstr, es);
2309 }
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3596
List * set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
Definition: ruleutils.c:3770

References config_generic::context, ExplainState::deparse_cxt, deparse_expression(), ExplainPropertyText(), PlanState::plan, and set_deparse_context_plan().

Referenced by ExplainNode(), and show_qual().

◆ show_foreignscan_info()

static void show_foreignscan_info ( ForeignScanState fsstate,
ExplainState es 
)
static

Definition at line 3456 of file explain.c.

3457 {
3458  FdwRoutine *fdwroutine = fsstate->fdwroutine;
3459 
3460  /* Let the FDW emit whatever fields it wants */
3461  if (((ForeignScan *) fsstate->ss.ps.plan)->operation != CMD_SELECT)
3462  {
3463  if (fdwroutine->ExplainDirectModify != NULL)
3464  fdwroutine->ExplainDirectModify(fsstate, es);
3465  }
3466  else
3467  {
3468  if (fdwroutine->ExplainForeignScan != NULL)
3469  fdwroutine->ExplainForeignScan(fsstate, es);
3470  }
3471 }
ExplainForeignScan_function ExplainForeignScan
Definition: fdwapi.h:252
ExplainDirectModify_function ExplainDirectModify
Definition: fdwapi.h:254
struct FdwRoutine * fdwroutine
Definition: execnodes.h:1939
ScanState ss
Definition: execnodes.h:1934

References CMD_SELECT, FdwRoutine::ExplainDirectModify, FdwRoutine::ExplainForeignScan, ForeignScanState::fdwroutine, PlanState::plan, ScanState::ps, and ForeignScanState::ss.

Referenced by ExplainNode().

◆ show_group_keys()

static void show_group_keys ( GroupState gstate,
List ancestors,
ExplainState es 
)
static

Definition at line 2544 of file explain.c.

2546 {
2547  Group *plan = (Group *) gstate->ss.ps.plan;
2548 
2549  /* The key columns refer to the tlist of the child plan */
2550  ancestors = lcons(plan, ancestors);
2551  show_sort_group_keys(outerPlanState(gstate), "Group Key",
2552  plan->numCols, 0, plan->grpColIdx,
2553  NULL, NULL, NULL,
2554  ancestors, es);
2555  ancestors = list_delete_first(ancestors);
2556 }
ScanState ss
Definition: execnodes.h:2311
int numCols
Definition: plannodes.h:968

References lcons(), list_delete_first(), Group::numCols, outerPlanState, PlanState::plan, ScanState::ps, show_sort_group_keys(), and GroupState::ss.

Referenced by ExplainNode().

◆ show_grouping_set_keys()

static void show_grouping_set_keys ( PlanState planstate,
Agg aggnode,
Sort sortnode,
List context,
bool  useprefix,
List ancestors,
ExplainState es 
)
static

Definition at line 2466 of file explain.c.

2470 {
2471  Plan *plan = planstate->plan;
2472  char *exprstr;
2473  ListCell *lc;
2474  List *gsets = aggnode->groupingSets;
2475  AttrNumber *keycols = aggnode->grpColIdx;
2476  const char *keyname;
2477  const char *keysetname;
2478 
2479  if (aggnode->aggstrategy == AGG_HASHED || aggnode->aggstrategy == AGG_MIXED)
2480  {
2481  keyname = "Hash Key";
2482  keysetname = "Hash Keys";
2483  }
2484  else
2485  {
2486  keyname = "Group Key";
2487  keysetname = "Group Keys";
2488  }
2489 
2490  ExplainOpenGroup("Grouping Set", NULL, true, es);
2491 
2492  if (sortnode)
2493  {
2494  show_sort_group_keys(planstate, "Sort Key",
2495  sortnode->numCols, 0, sortnode->sortColIdx,
2496  sortnode->sortOperators, sortnode->collations,
2497  sortnode->nullsFirst,
2498  ancestors, es);
2499  if (es->format == EXPLAIN_FORMAT_TEXT)
2500  es->indent++;
2501  }
2502 
2503  ExplainOpenGroup(keysetname, keysetname, false, es);
2504 
2505  foreach(lc, gsets)
2506  {
2507  List *result = NIL;
2508  ListCell *lc2;
2509 
2510  foreach(lc2, (List *) lfirst(lc))
2511  {
2512  Index i = lfirst_int(lc2);
2513  AttrNumber keyresno = keycols[i];
2514  TargetEntry *target = get_tle_by_resno(plan->targetlist,
2515  keyresno);
2516 
2517  if (!target)
2518  elog(ERROR, "no tlist entry for key %d", keyresno);
2519  /* Deparse the expression, showing any top-level cast */
2520  exprstr = deparse_expression((Node *) target->expr, context,
2521  useprefix, true);
2522 
2523  result = lappend(result, exprstr);
2524  }
2525 
2526  if (!result && es->format == EXPLAIN_FORMAT_TEXT)
2527  ExplainPropertyText(keyname, "()", es);
2528  else
2529  ExplainPropertyListNested(keyname, result, es);
2530  }
2531 
2532  ExplainCloseGroup(keysetname, keysetname, false, es);
2533 
2534  if (sortnode && es->format == EXPLAIN_FORMAT_TEXT)
2535  es->indent--;
2536 
2537  ExplainCloseGroup("Grouping Set", NULL, true, es);
2538 }
unsigned int Index
Definition: c.h:550
void ExplainPropertyListNested(const char *qlabel, List *data, ExplainState *es)
Definition: explain.c:4437
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define lfirst_int(lc)
Definition: pg_list.h:171
List * targetlist
Definition: plannodes.h:153
int numCols
Definition: plannodes.h:932
Expr * expr
Definition: primnodes.h:1555

References AGG_HASHED, AGG_MIXED, Agg::aggstrategy, config_generic::context, deparse_expression(), elog(), ERROR, EXPLAIN_FORMAT_TEXT, ExplainCloseGroup(), ExplainOpenGroup(), ExplainPropertyListNested(), ExplainPropertyText(), TargetEntry::expr, ExplainState::format, get_tle_by_resno(), Agg::groupingSets, i, ExplainState::indent, lappend(), lfirst, lfirst_int, NIL, Sort::numCols, PlanState::plan, show_sort_group_keys(), and Plan::targetlist.

Referenced by show_grouping_sets().

◆ show_grouping_sets()

static void show_grouping_sets ( PlanState planstate,
Agg agg,
List ancestors,
ExplainState es 
)
static

Definition at line 2435 of file explain.c.

2437 {
2438  List *context;
2439  bool useprefix;
2440  ListCell *lc;
2441 
2442  /* Set up deparsing context */
2443  context = set_deparse_context_plan(es->deparse_cxt,
2444  planstate->plan,
2445  ancestors);
2446  useprefix = (list_length(es->rtable) > 1 || es->verbose);
2447 
2448  ExplainOpenGroup("Grouping Sets", "Grouping Sets", false, es);
2449 
2450  show_grouping_set_keys(planstate, agg, NULL,
2451  context, useprefix, ancestors, es);
2452 
2453  foreach(lc, agg->chain)
2454  {
2455  Agg *aggnode = lfirst(lc);
2456  Sort *sortnode = (Sort *) aggnode->plan.lefttree;
2457 
2458  show_grouping_set_keys(planstate, aggnode, sortnode,
2459  context, useprefix, ancestors, es);
2460  }
2461 
2462  ExplainCloseGroup("Grouping Sets", "Grouping Sets", false, es);
2463 }
static void show_grouping_set_keys(PlanState *planstate, Agg *aggnode, Sort *sortnode, List *context, bool useprefix, List *ancestors, ExplainState *es)
Definition: explain.c:2466
List * chain
Definition: plannodes.h:1027
Plan plan
Definition: plannodes.h:994
struct Plan * lefttree
Definition: plannodes.h:155

References Agg::chain, config_generic::context, ExplainState::deparse_cxt, ExplainCloseGroup(), ExplainOpenGroup(), Plan::lefttree, lfirst, list_length(), PlanState::plan, Agg::plan, ExplainState::rtable, set_deparse_context_plan(), show_grouping_set_keys(), and ExplainState::verbose.

Referenced by show_agg_keys().

◆ show_hash_info()

static void show_hash_info ( HashState hashstate,
ExplainState es 
)
static

Definition at line 3041 of file explain.c.

3042 {
3043  HashInstrumentation hinstrument = {0};
3044 
3045  /*
3046  * Collect stats from the local process, even when it's a parallel query.
3047  * In a parallel query, the leader process may or may not have run the
3048  * hash join, and even if it did it may not have built a hash table due to
3049  * timing (if it started late it might have seen no tuples in the outer
3050  * relation and skipped building the hash table). Therefore we have to be
3051  * prepared to get instrumentation data from all participants.
3052  */
3053  if (hashstate->hinstrument)
3054  memcpy(&hinstrument, hashstate->hinstrument,
3055  sizeof(HashInstrumentation));
3056 
3057  /*
3058  * Merge results from workers. In the parallel-oblivious case, the
3059  * results from all participants should be identical, except where
3060  * participants didn't run the join at all so have no data. In the
3061  * parallel-aware case, we need to consider all the results. Each worker
3062  * may have seen a different subset of batches and we want to report the
3063  * highest memory usage across all batches. We take the maxima of other
3064  * values too, for the same reasons as in ExecHashAccumInstrumentation.
3065  */
3066  if (hashstate->shared_info)
3067  {
3068  SharedHashInfo *shared_info = hashstate->shared_info;
3069  int i;
3070 
3071  for (i = 0; i < shared_info->num_workers; ++i)
3072  {
3073  HashInstrumentation *worker_hi = &shared_info->hinstrument[i];
3074 
3075  hinstrument.nbuckets = Max(hinstrument.nbuckets,
3076  worker_hi->nbuckets);
3077  hinstrument.nbuckets_original = Max(hinstrument.nbuckets_original,
3078  worker_hi->nbuckets_original);
3079  hinstrument.nbatch = Max(hinstrument.nbatch,
3080  worker_hi->nbatch);
3081  hinstrument.nbatch_original = Max(hinstrument.nbatch_original,
3082  worker_hi->nbatch_original);
3083  hinstrument.space_peak = Max(hinstrument.space_peak,
3084  worker_hi->space_peak);
3085  }
3086  }
3087 
3088  if (hinstrument.nbatch > 0)
3089  {
3090  long spacePeakKb = (hinstrument.space_peak + 1023) / 1024;
3091 
3092  if (es->format != EXPLAIN_FORMAT_TEXT)
3093  {
3094  ExplainPropertyInteger("Hash Buckets", NULL,
3095  hinstrument.nbuckets, es);
3096  ExplainPropertyInteger("Original Hash Buckets", NULL,
3097  hinstrument.nbuckets_original, es);
3098  ExplainPropertyInteger("Hash Batches", NULL,
3099  hinstrument.nbatch, es);
3100  ExplainPropertyInteger("Original Hash Batches", NULL,
3101  hinstrument.nbatch_original, es);
3102  ExplainPropertyInteger("Peak Memory Usage", "kB",
3103  spacePeakKb, es);
3104  }
3105  else if (hinstrument.nbatch_original != hinstrument.nbatch ||
3106  hinstrument.nbuckets_original != hinstrument.nbuckets)
3107  {
3108  ExplainIndentText(es);
3109  appendStringInfo(es->str,
3110  "Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: %ldkB\n",
3111  hinstrument.nbuckets,
3112  hinstrument.nbuckets_original,
3113  hinstrument.nbatch,
3114  hinstrument.nbatch_original,
3115  spacePeakKb);
3116  }
3117  else
3118  {
3119  ExplainIndentText(es);
3120  appendStringInfo(es->str,
3121  "Buckets: %d Batches: %d Memory Usage: %ldkB\n",
3122  hinstrument.nbuckets, hinstrument.nbatch,
3123  spacePeakKb);
3124  }
3125  }
3126 }
#define Max(x, y)
Definition: c.h:931
SharedHashInfo * shared_info
Definition: execnodes.h:2650
HashInstrumentation * hinstrument
Definition: execnodes.h:2657
HashInstrumentation hinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2631

References appendStringInfo(), EXPLAIN_FORMAT_TEXT, ExplainIndentText(), ExplainPropertyInteger(), ExplainState::format, SharedHashInfo::hinstrument, HashState::hinstrument, i, Max, HashInstrumentation::nbatch, HashInstrumentation::nbatch_original, HashInstrumentation::nbuckets, HashInstrumentation::nbuckets_original, SharedHashInfo::num_workers, HashState::shared_info, HashInstrumentation::space_peak, and ExplainState::str.

Referenced by ExplainNode().

◆ show_hashagg_info()

static void show_hashagg_info ( AggState aggstate,
ExplainState es 
)
static

Definition at line 3276 of file explain.c.

3277 {
3278  Agg *agg = (Agg *) aggstate->ss.ps.plan;
3279  int64 memPeakKb = (aggstate->hash_mem_peak + 1023) / 1024;
3280 
3281  if (agg->aggstrategy != AGG_HASHED &&
3282  agg->aggstrategy != AGG_MIXED)
3283  return;
3284 
3285  if (es->format != EXPLAIN_FORMAT_TEXT)
3286  {
3287  if (es->costs)
3288  ExplainPropertyInteger("Planned Partitions", NULL,
3289  aggstate->hash_planned_partitions, es);
3290 
3291  /*
3292  * During parallel query the leader may have not helped out. We
3293  * detect this by checking how much memory it used. If we find it
3294  * didn't do any work then we don't show its properties.
3295  */
3296  if (es->analyze && aggstate->hash_mem_peak > 0)
3297  {
3298  ExplainPropertyInteger("HashAgg Batches", NULL,
3299  aggstate->hash_batches_used, es);
3300  ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb, es);
3301  ExplainPropertyInteger("Disk Usage", "kB",
3302  aggstate->hash_disk_used, es);
3303  }
3304  }
3305  else
3306  {
3307  bool gotone = false;
3308 
3309  if (es->costs && aggstate->hash_planned_partitions > 0)
3310  {
3311  ExplainIndentText(es);
3312  appendStringInfo(es->str, "Planned Partitions: %d",
3313  aggstate->hash_planned_partitions);
3314  gotone = true;
3315  }
3316 
3317  /*
3318  * During parallel query the leader may have not helped out. We
3319  * detect this by checking how much memory it used. If we find it
3320  * didn't do any work then we don't show its properties.
3321  */
3322  if (es->analyze && aggstate->hash_mem_peak > 0)
3323  {
3324  if (!gotone)
3325  ExplainIndentText(es);
3326  else
3327  appendStringInfoString(es->str, " ");
3328 
3329  appendStringInfo(es->str, "Batches: %d Memory Usage: " INT64_FORMAT "kB",
3330  aggstate->hash_batches_used, memPeakKb);
3331  gotone = true;
3332 
3333  /* Only display disk usage if we spilled to disk */
3334  if (aggstate->hash_batches_used > 1)
3335  {
3336  appendStringInfo(es->str, " Disk Usage: " UINT64_FORMAT "kB",
3337  aggstate->hash_disk_used);
3338  }
3339  }
3340 
3341  if (gotone)
3342  appendStringInfoChar(es->str, '\n');
3343  }
3344 
3345  /* Display stats for each parallel worker */
3346  if (es->analyze && aggstate->shared_info != NULL)
3347  {
3348  for (int n = 0; n < aggstate->shared_info->num_workers; n++)
3349  {
3350  AggregateInstrumentation *sinstrument;
3351  uint64 hash_disk_used;
3352  int hash_batches_used;
3353 
3354  sinstrument = &aggstate->shared_info->sinstrument[n];
3355  /* Skip workers that didn't do anything */
3356  if (sinstrument->hash_mem_peak == 0)
3357  continue;
3358  hash_disk_used = sinstrument->hash_disk_used;
3359  hash_batches_used = sinstrument->hash_batches_used;
3360  memPeakKb = (sinstrument->hash_mem_peak + 1023) / 1024;
3361 
3362  if (es->workers_state)
3363  ExplainOpenWorker(n, es);
3364 
3365  if (es->format == EXPLAIN_FORMAT_TEXT)
3366  {
3367  ExplainIndentText(es);
3368 
3369  appendStringInfo(es->str, "Batches: %d Memory Usage: " INT64_FORMAT "kB",
3370  hash_batches_used, memPeakKb);
3371 
3372  /* Only display disk usage if we spilled to disk */
3373  if (hash_batches_used > 1)
3374  appendStringInfo(es->str, " Disk Usage: " UINT64_FORMAT "kB",
3375  hash_disk_used);
3376  appendStringInfoChar(es->str, '\n');
3377  }
3378  else
3379  {
3380  ExplainPropertyInteger("HashAgg Batches", NULL,
3381  hash_batches_used, es);
3382  ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb,
3383  es);
3384  ExplainPropertyInteger("Disk Usage", "kB", hash_disk_used, es);
3385  }
3386 
3387  if (es->workers_state)
3388  ExplainCloseWorker(n, es);
3389  }
3390  }
3391 }
uint64 hash_disk_used
Definition: execnodes.h:2418
int hash_planned_partitions
Definition: execnodes.h:2412
SharedAggInfo * shared_info
Definition: execnodes.h:2430
Size hash_mem_peak
Definition: execnodes.h:2415
int hash_batches_used
Definition: execnodes.h:2419
AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2334

References AGG_HASHED, AGG_MIXED, Agg::aggstrategy, ExplainState::analyze, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), ExplainState::costs, EXPLAIN_FORMAT_TEXT, ExplainCloseWorker(), ExplainIndentText(), ExplainOpenWorker(), ExplainPropertyInteger(), ExplainState::format, AggregateInstrumentation::hash_batches_used, AggState::hash_batches_used, AggregateInstrumentation::hash_disk_used, AggState::hash_disk_used, AggregateInstrumentation::hash_mem_peak, AggState::hash_mem_peak, AggState::hash_planned_partitions, INT64_FORMAT, SharedAggInfo::num_workers, PlanState::plan, ScanState::ps, AggState::shared_info, SharedAggInfo::sinstrument, AggState::ss, ExplainState::str, UINT64_FORMAT, and ExplainState::workers_state.

Referenced by ExplainNode().

◆ show_incremental_sort_group_info()

static void show_incremental_sort_group_info ( IncrementalSortGroupInfo groupInfo,
const char *  groupLabel,
bool  indent,
ExplainState es 
)
static

Definition at line 2841 of file explain.c.

2843 {
2844  ListCell *methodCell;
2845  List *methodNames = NIL;
2846 
2847  /* Generate a list of sort methods used across all groups. */
2848  for (int bit = 0; bit < NUM_TUPLESORTMETHODS; bit++)
2849  {
2850  TuplesortMethod sortMethod = (1 << bit);
2851 
2852  if (groupInfo->sortMethods & sortMethod)
2853  {
2854  const char *methodName = tuplesort_method_name(sortMethod);
2855 
2856  methodNames = lappend(methodNames, unconstify(char *, methodName));
2857  }
2858  }
2859 
2860  if (es->format == EXPLAIN_FORMAT_TEXT)
2861  {
2862  if (indent)
2863  appendStringInfoSpaces(es->str, es->indent * 2);
2864  appendStringInfo(es->str, "%s Groups: " INT64_FORMAT " Sort Method", groupLabel,
2865  groupInfo->groupCount);
2866  /* plural/singular based on methodNames size */
2867  if (list_length(methodNames) > 1)
2868  appendStringInfoString(es->str, "s: ");
2869  else
2870  appendStringInfoString(es->str, ": ");