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 *hashstate, 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)
 
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 1045 of file explain.c.

1046 {
1047  instr_time endtime;
1048 
1049  INSTR_TIME_SET_CURRENT(endtime);
1050  INSTR_TIME_SUBTRACT(endtime, *starttime);
1051  return INSTR_TIME_GET_DOUBLE(endtime);
1052 }
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
#define INSTR_TIME_GET_DOUBLE(t)
Definition: instr_time.h:199
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
struct timeval instr_time
Definition: instr_time.h:150

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 4924 of file explain.c.

4925 {
4926  escape_json(buf, str);
4927 }
void escape_json(StringInfo buf, const char *str)
Definition: json.c:1279
static char * buf
Definition: pg_test_fsync.c:70

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 3469 of file explain.c.

3470 {
3471  const char *result;
3472 
3474  result = (*explain_get_index_name_hook) (indexId);
3475  else
3476  result = NULL;
3477  if (result == NULL)
3478  {
3479  /* default behavior: look it up in the catalogs */
3480  result = get_rel_name(indexId);
3481  if (result == NULL)
3482  elog(ERROR, "cache lookup failed for index %u", indexId);
3483  }
3484  return result;
3485 }
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
explain_get_index_name_hook_type explain_get_index_name_hook
Definition: explain.c:48
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899

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 4748 of file explain.c.

4749 {
4750  switch (es->format)
4751  {
4752  case EXPLAIN_FORMAT_TEXT:
4753  /* nothing to do */
4754  break;
4755 
4756  case EXPLAIN_FORMAT_XML:
4758  "<explain xmlns=\"http://www.postgresql.org/2009/explain\">\n");
4759  es->indent++;
4760  break;
4761 
4762  case EXPLAIN_FORMAT_JSON:
4763  /* top-level structure is an array of plans */
4764  appendStringInfoChar(es->str, '[');
4765  es->grouping_stack = lcons_int(0, es->grouping_stack);
4766  es->indent++;
4767  break;
4768 
4769  case EXPLAIN_FORMAT_YAML:
4770  es->grouping_stack = lcons_int(0, es->grouping_stack);
4771  break;
4772  }
4773 }
@ 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:492
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 4555 of file explain.c.

4557 {
4558  switch (es->format)
4559  {
4560  case EXPLAIN_FORMAT_TEXT:
4561  /* nothing to do */
4562  break;
4563 
4564  case EXPLAIN_FORMAT_XML:
4565  es->indent--;
4566  ExplainXMLTag(objtype, X_CLOSING, es);
4567  break;
4568 
4569  case EXPLAIN_FORMAT_JSON:
4570  es->indent--;
4571  appendStringInfoChar(es->str, '\n');
4572  appendStringInfoSpaces(es->str, 2 * es->indent);
4573  appendStringInfoChar(es->str, labeled ? '}' : ']');
4575  break;
4576 
4577  case EXPLAIN_FORMAT_YAML:
4578  es->indent--;
4580  break;
4581  }
4582 }
static void ExplainXMLTag(const char *tagname, int flags, ExplainState *es)
Definition: explain.c:4837
#define X_CLOSING
Definition: explain.c:53
List * list_delete_first(List *list)
Definition: list.c:902
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 4185 of file explain.c.

4186 {
4187  ExplainWorkersState *wstate = es->workers_state;
4188 
4189  Assert(wstate);
4190  Assert(n >= 0 && n < wstate->num_workers);
4191  Assert(wstate->worker_inited[n]);
4192 
4193  /*
4194  * Save formatting state in case we do another ExplainOpenWorker(), then
4195  * pop the formatting stack.
4196  */
4197  ExplainSaveGroup(es, 2, &wstate->worker_state_save[n]);
4198 
4199  /*
4200  * In TEXT format, if we didn't actually produce any output line(s) then
4201  * truncate off the partial line emitted by ExplainOpenWorker. (This is
4202  * to avoid bogus output if, say, show_buffer_usage chooses not to print
4203  * anything for the worker.) Also fix up the indent level.
4204  */
4205  if (es->format == EXPLAIN_FORMAT_TEXT)
4206  {
4207  while (es->str->len > 0 && es->str->data[es->str->len - 1] != '\n')
4208  es->str->data[--(es->str->len)] = '\0';
4209 
4210  es->indent--;
4211  }
4212 
4213  /* Restore prior output buffer pointer */
4214  es->str = wstate->prev_str;
4215 }
static void ExplainSaveGroup(ExplainState *es, int depth, int *state_save)
Definition: explain.c:4641
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 4106 of file explain.c.

4107 {
4108  ExplainWorkersState *wstate;
4109 
4110  wstate = (ExplainWorkersState *) palloc(sizeof(ExplainWorkersState));
4111  wstate->num_workers = num_workers;
4112  wstate->worker_inited = (bool *) palloc0(num_workers * sizeof(bool));
4113  wstate->worker_str = (StringInfoData *)
4114  palloc0(num_workers * sizeof(StringInfoData));
4115  wstate->worker_state_save = (int *) palloc(num_workers * sizeof(int));
4116  return wstate;
4117 }
void * palloc0(Size size)
Definition: mcxt.c:1093
void * palloc(Size size)
Definition: mcxt.c:1062
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 4084 of file explain.c.

4085 {
4086  ListCell *cell;
4087  const char *label =
4088  (list_length(css->custom_ps) != 1 ? "children" : "child");
4089 
4090  foreach(cell, css->custom_ps)
4091  ExplainNode((PlanState *) lfirst(cell), ancestors, label, NULL, es);
4092 }
static void ExplainNode(PlanState *planstate, List *ancestors, const char *relationship, const char *plan_name, ExplainState *es)
Definition: explain.c:1139
static char * label
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * custom_ps
Definition: execnodes.h:1891

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 4702 of file explain.c.

4703 {
4704  switch (es->format)
4705  {
4706  case EXPLAIN_FORMAT_TEXT:
4707  /* nothing to do */
4708  break;
4709 
4710  case EXPLAIN_FORMAT_XML:
4711  ExplainXMLTag(objtype, X_CLOSE_IMMEDIATE, es);
4712  break;
4713 
4714  case EXPLAIN_FORMAT_JSON:
4716  appendStringInfoSpaces(es->str, 2 * es->indent);
4717  if (labelname)
4718  {
4719  escape_json(es->str, labelname);
4720  appendStringInfoString(es->str, ": ");
4721  }
4722  escape_json(es->str, objtype);
4723  break;
4724 
4725  case EXPLAIN_FORMAT_YAML:
4727  if (labelname)
4728  {
4729  escape_yaml(es->str, labelname);
4730  appendStringInfoString(es->str, ": ");
4731  }
4732  else
4733  {
4734  appendStringInfoString(es->str, "- ");
4735  }
4736  escape_yaml(es->str, objtype);
4737  break;
4738  }
4739 }
#define X_CLOSE_IMMEDIATE
Definition: explain.c:54
static void ExplainYAMLLineStarting(ExplainState *es)
Definition: explain.c:4899
static void ExplainJSONLineEnding(ExplainState *es)
Definition: explain.c:4879
static void escape_yaml(StringInfo buf, const char *str)
Definition: explain.c:4924

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 4779 of file explain.c.

4780 {
4781  switch (es->format)
4782  {
4783  case EXPLAIN_FORMAT_TEXT:
4784  /* nothing to do */
4785  break;
4786 
4787  case EXPLAIN_FORMAT_XML:
4788  es->indent--;
4789  appendStringInfoString(es->str, "</explain>");
4790  break;
4791 
4792  case EXPLAIN_FORMAT_JSON:
4793  es->indent--;
4794  appendStringInfoString(es->str, "\n]");
4796  break;
4797 
4798  case EXPLAIN_FORMAT_YAML:
4800  break;
4801  }
4802 }

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 4221 of file explain.c.

4222 {
4223  ExplainWorkersState *wstate = es->workers_state;
4224 
4225  ExplainOpenGroup("Workers", "Workers", false, es);
4226  for (int i = 0; i < wstate->num_workers; i++)
4227  {
4228  if (wstate->worker_inited[i])
4229  {
4230  /* This must match previous ExplainOpenSetAsideGroup call */
4231  ExplainOpenGroup("Worker", NULL, true, es);
4232  appendStringInfoString(es->str, wstate->worker_str[i].data);
4233  ExplainCloseGroup("Worker", NULL, true, es);
4234 
4235  pfree(wstate->worker_str[i].data);
4236  }
4237  }
4238  ExplainCloseGroup("Workers", "Workers", false, es);
4239 
4240  pfree(wstate->worker_inited);
4241  pfree(wstate->worker_str);
4242  pfree(wstate->worker_state_save);
4243  pfree(wstate);
4244 }
void ExplainOpenGroup(const char *objtype, const char *labelname, bool labeled, ExplainState *es)
Definition: explain.c:4492
void ExplainCloseGroup(const char *objtype, const char *labelname, bool labeled, ExplainState *es)
Definition: explain.c:4555
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1169

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 3665 of file explain.c.

3667 {
3668  const char *indexname = explain_get_index_name(indexid);
3669 
3670  if (es->format == EXPLAIN_FORMAT_TEXT)
3671  {
3672  if (ScanDirectionIsBackward(indexorderdir))
3673  appendStringInfoString(es->str, " Backward");
3674  appendStringInfo(es->str, " using %s", quote_identifier(indexname));
3675  }
3676  else
3677  {
3678  const char *scandir;
3679 
3680  switch (indexorderdir)
3681  {
3682  case BackwardScanDirection:
3683  scandir = "Backward";
3684  break;
3686  scandir = "NoMovement";
3687  break;
3688  case ForwardScanDirection:
3689  scandir = "Forward";
3690  break;
3691  default:
3692  scandir = "???";
3693  break;
3694  }
3695  ExplainPropertyText("Scan Direction", scandir, es);
3696  ExplainPropertyText("Index Name", indexname, es);
3697  }
3698 }
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
Definition: explain.c:4427
static const char * explain_get_index_name(Oid indexId)
Definition: explain.c:3469
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11440
#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 4009 of file explain.c.

4011 {
4012  int j;
4013 
4014  for (j = 0; j < nplans; j++)
4015  ExplainNode(planstates[j], ancestors,
4016  "Member", NULL, es);
4017 }
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 4027 of file explain.c.

4028 {
4029  if (nplans < nchildren || es->format != EXPLAIN_FORMAT_TEXT)
4030  ExplainPropertyInteger("Subplans Removed", NULL,
4031  nchildren - nplans, es);
4032 }
void ExplainPropertyInteger(const char *qlabel, const char *unit, int64 value, ExplainState *es)
Definition: explain.c:4436
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 3717 of file explain.c.

3718 {
3719  ExplainTargetRel((Plan *) plan, plan->nominalRelation, es);
3720 }
static void ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
Definition: explain.c:3726

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 1139 of file explain.c.

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

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_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, T_Agg, T_Append, T_BitmapAnd, T_BitmapHeapScan, T_BitmapIndexScan, T_BitmapOr, T_CteScan, T_CustomScan, T_ForeignScan, T_FunctionScan, T_Gather, T_GatherMerge, T_Group, T_Hash, T_HashJoin, T_IncrementalSort, T_IndexOnlyScan, T_IndexScan, T_Limit, T_LockRows, T_Material, T_Memoize, T_MergeAppend, T_MergeJoin, T_ModifyTable, T_NamedTuplestoreScan, T_NestLoop, T_ProjectSet, T_RecursiveUnion, T_Result, T_SampleScan, T_SeqScan, T_SetOp, T_Sort, T_SubqueryScan, T_TableFuncScan, T_TidRangeScan, T_TidScan, T_Unique, T_ValuesScan, T_WindowAgg, T_WorkTableScan, 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  if (es->verbose && plannedstmt->queryId != UINT64CONST(0))
608  {
609  /*
610  * Output the queryid as an int64 rather than a uint64 so we match
611  * what would be seen in the BIGINT pg_stat_statements.queryid column.
612  */
613  ExplainPropertyInteger("Query Identifier", NULL, (int64)
614  plannedstmt->queryId, es);
615  }
616 
617  /* Show buffer usage in planning */
618  if (bufusage)
619  {
620  ExplainOpenGroup("Planning", "Planning", true, es);
621  show_buffer_usage(es, bufusage, true);
622  ExplainCloseGroup("Planning", "Planning", true, es);
623  }
624 
625  if (es->summary && planduration)
626  {
627  double plantime = INSTR_TIME_GET_DOUBLE(*planduration);
628 
629  ExplainPropertyFloat("Planning Time", "ms", 1000.0 * plantime, 3, es);
630  }
631 
632  /* Print info about runtime of triggers */
633  if (es->analyze)
634  ExplainPrintTriggers(es, queryDesc);
635 
636  /*
637  * Print info about JITing. Tied to es->costs because we don't want to
638  * display this in regression tests, as it'd cause output differences
639  * depending on build options. Might want to separate that out from COSTS
640  * at a later stage.
641  */
642  if (es->costs)
643  ExplainPrintJITSummary(es, queryDesc);
644 
645  /*
646  * Close down the query and free resources. Include time for this in the
647  * total execution time (although it should be pretty minimal).
648  */
649  INSTR_TIME_SET_CURRENT(starttime);
650 
651  ExecutorEnd(queryDesc);
652 
653  FreeQueryDesc(queryDesc);
654 
656 
657  /* We need a CCI just in case query expanded to multiple plans */
658  if (es->analyze)
660 
661  totaltime += elapsed_time(&starttime);
662 
663  /*
664  * We only report execution time if we actually ran the query (that is,
665  * the user specified ANALYZE), and if summary reporting is enabled (the
666  * user can set SUMMARY OFF to not have the timing information included in
667  * the output). By default, ANALYZE sets SUMMARY to true.
668  */
669  if (es->summary && es->analyze)
670  ExplainPropertyFloat("Execution Time", "ms", 1000.0 * totaltime, 3,
671  es);
672 
673  ExplainCloseGroup("Query", NULL, true, es);
674 }
DestReceiver * CreateIntoRelDestReceiver(IntoClause *intoClause)
Definition: createas.c:428
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:375
DestReceiver * None_Receiver
Definition: dest.c:96
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:459
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:399
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:130
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:298
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
void ExplainPrintJITSummary(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:843
static double elapsed_time(instr_time *starttime)
Definition: explain.c:1045
void ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:751
void ExplainPrintTriggers(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:800
@ INSTRUMENT_TIMER
Definition: instrument.h:57
@ INSTRUMENT_BUFFERS
Definition: instrument.h:58
@ INSTRUMENT_WAL
Definition: instrument.h:60
@ INSTRUMENT_ROWS
Definition: instrument.h:59
@ CMD_UTILITY
Definition: nodes.h:690
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
ScanDirection
Definition: sdir.h:23
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:743
void PopActiveSnapshot(void)
Definition: snapmgr.c:774
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:731
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:801
#define InvalidSnapshot
Definition: snapshot.h:123
bool summary
Definition: explain.h:47
bool skipData
Definition: primnodes.h:119
CmdType commandType
Definition: plannodes.h:46
uint64 queryId
Definition: plannodes.h:48
void CommandCounterIncrement(void)
Definition: xact.c:1073

References ExplainState::analyze, Assert(), ExplainState::buffers, CMD_UTILITY, CommandCounterIncrement(), PlannedStmt::commandType, 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:244
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:830
CmdType commandType
Definition: parsenodes.h:119
Node * utilityStmt
Definition: parsenodes.h:127

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:605
bool CreateTableAsRelExists(CreateTableAsStmt *ctas)
Definition: createas.c:393
static void ExplainDummyGroup(const char *objtype, const char *labelname, ExplainState *es)
Definition: explain.c:4702
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:655
@ OBJECT_MATVIEW
Definition: parsenodes.h:1812
@ OBJECT_TABLE
Definition: parsenodes.h:1829
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2830
#define linitial_node(type, l)
Definition: pg_list.h:177
List * QueryRewrite(Query *parsetree)
IntoClause * into
Definition: parsenodes.h:3411
ObjectType objtype
Definition: parsenodes.h:3412

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 4492 of file explain.c.

4494 {
4495  switch (es->format)
4496  {
4497  case EXPLAIN_FORMAT_TEXT:
4498  /* nothing to do */
4499  break;
4500 
4501  case EXPLAIN_FORMAT_XML:
4502  ExplainXMLTag(objtype, X_OPENING, es);
4503  es->indent++;
4504  break;
4505 
4506  case EXPLAIN_FORMAT_JSON:
4508  appendStringInfoSpaces(es->str, 2 * es->indent);
4509  if (labelname)
4510  {
4511  escape_json(es->str, labelname);
4512  appendStringInfoString(es->str, ": ");
4513  }
4514  appendStringInfoChar(es->str, labeled ? '{' : '[');
4515 
4516  /*
4517  * In JSON format, the grouping_stack is an integer list. 0 means
4518  * we've emitted nothing at this grouping level, 1 means we've
4519  * emitted something (and so the next item needs a comma). See
4520  * ExplainJSONLineEnding().
4521  */
4522  es->grouping_stack = lcons_int(0, es->grouping_stack);
4523  es->indent++;
4524  break;
4525 
4526  case EXPLAIN_FORMAT_YAML:
4527 
4528  /*
4529  * In YAML format, the grouping stack is an integer list. 0 means
4530  * we've emitted nothing at this grouping level AND this grouping
4531  * level is unlabeled and must be marked with "- ". See
4532  * ExplainYAMLLineStarting().
4533  */
4535  if (labelname)
4536  {
4537  appendStringInfo(es->str, "%s: ", labelname);
4538  es->grouping_stack = lcons_int(1, es->grouping_stack);
4539  }
4540  else
4541  {
4542  appendStringInfoString(es->str, "- ");
4543  es->grouping_stack = lcons_int(0, es->grouping_stack);
4544  }
4545  es->indent++;
4546  break;
4547  }
4548 }
#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 4602 of file explain.c.

4604 {
4605  switch (es->format)
4606  {
4607  case EXPLAIN_FORMAT_TEXT:
4608  /* nothing to do */
4609  break;
4610 
4611  case EXPLAIN_FORMAT_XML:
4612  es->indent += depth;
4613  break;
4614 
4615  case EXPLAIN_FORMAT_JSON:
4616  es->grouping_stack = lcons_int(0, es->grouping_stack);
4617  es->indent += depth;
4618  break;
4619 
4620  case EXPLAIN_FORMAT_YAML:
4621  if (labelname)
4622  es->grouping_stack = lcons_int(1, es->grouping_stack);
4623  else
4624  es->grouping_stack = lcons_int(0, es->grouping_stack);
4625  es->indent += depth;
4626  break;
4627  }
4628 }

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 4123 of file explain.c.

4124 {
4125  ExplainWorkersState *wstate = es->workers_state;
4126 
4127  Assert(wstate);
4128  Assert(n >= 0 && n < wstate->num_workers);
4129 
4130  /* Save prior output buffer pointer */
4131  wstate->prev_str = es->str;
4132 
4133  if (!wstate->worker_inited[n])
4134  {
4135  /* First time through, so create the buffer for this worker */
4136  initStringInfo(&wstate->worker_str[n]);
4137  es->str = &wstate->worker_str[n];
4138 
4139  /*
4140  * Push suitable initial formatting state for this worker's field
4141  * group. We allow one extra logical nesting level, since this group
4142  * will eventually be wrapped in an outer "Workers" group.
4143  */
4144  ExplainOpenSetAsideGroup("Worker", NULL, true, 2, es);
4145 
4146  /*
4147  * In non-TEXT formats we always emit a "Worker Number" field, even if
4148  * there's no other data for this worker.
4149  */
4150  if (es->format != EXPLAIN_FORMAT_TEXT)
4151  ExplainPropertyInteger("Worker Number", NULL, n, es);
4152 
4153  wstate->worker_inited[n] = true;
4154  }
4155  else
4156  {
4157  /* Resuming output for a worker we've already emitted some data for */
4158  es->str = &wstate->worker_str[n];
4159 
4160  /* Restore formatting state saved by last ExplainCloseWorker() */
4161  ExplainRestoreGroup(es, 2, &wstate->worker_state_save[n]);
4162  }
4163 
4164  /*
4165  * In TEXT format, prefix the first output line for this worker with
4166  * "Worker N:". Then, any additional lines should be indented one more
4167  * stop than the "Worker N" line is.
4168  */
4169  if (es->format == EXPLAIN_FORMAT_TEXT)
4170  {
4171  if (es->str->len == 0)
4172  {
4173  ExplainIndentText(es);
4174  appendStringInfo(es->str, "Worker %d: ", n);
4175  }
4176 
4177  es->indent++;
4178  }
4179 }
static void ExplainRestoreGroup(ExplainState *es, int depth, int *state_save)
Definition: explain.c:4671
static void ExplainOpenSetAsideGroup(const char *objtype, const char *labelname, bool labeled, int depth, ExplainState *es)
Definition: explain.c:4602
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 1064 of file explain.c.

1065 {
1066  Plan *plan = planstate->plan;
1067 
1068  switch (nodeTag(plan))
1069  {
1070  case T_SeqScan:
1071  case T_SampleScan:
1072  case T_IndexScan:
1073  case T_IndexOnlyScan:
1074  case T_BitmapHeapScan:
1075  case T_TidScan:
1076  case T_TidRangeScan:
1077  case T_SubqueryScan:
1078  case T_FunctionScan:
1079  case T_TableFuncScan:
1080  case T_ValuesScan:
1081  case T_CteScan:
1082  case T_NamedTuplestoreScan:
1083  case T_WorkTableScan:
1084  *rels_used = bms_add_member(*rels_used,
1085  ((Scan *) plan)->scanrelid);
1086  break;
1087  case T_ForeignScan:
1088  *rels_used = bms_add_members(*rels_used,
1089  ((ForeignScan *) plan)->fs_relids);
1090  break;
1091  case T_CustomScan:
1092  *rels_used = bms_add_members(*rels_used,
1093  ((CustomScan *) plan)->custom_relids);
1094  break;
1095  case T_ModifyTable:
1096  *rels_used = bms_add_member(*rels_used,
1097  ((ModifyTable *) plan)->nominalRelation);
1098  if (((ModifyTable *) plan)->exclRelRTI)
1099  *rels_used = bms_add_member(*rels_used,
1100  ((ModifyTable *) plan)->exclRelRTI);
1101  break;
1102  case T_Append:
1103  *rels_used = bms_add_members(*rels_used,
1104  ((Append *) plan)->apprelids);
1105  break;
1106  case T_MergeAppend:
1107  *rels_used = bms_add_members(*rels_used,
1108  ((MergeAppend *) plan)->apprelids);
1109  break;
1110  default:
1111  break;
1112  }
1113 
1114  return planstate_tree_walker(planstate, ExplainPreScanNode, rels_used);
1115 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:795
static bool ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used)
Definition: explain.c:1064
bool planstate_tree_walker(PlanState *planstate, bool(*walker)(), void *context)
Definition: nodeFuncs.c:4035

References bms_add_member(), bms_add_members(), nodeTag, PlanState::plan, planstate_tree_walker(), T_Append, T_BitmapHeapScan, T_CteScan, T_CustomScan, T_ForeignScan, T_FunctionScan, T_IndexOnlyScan, T_IndexScan, T_MergeAppend, T_ModifyTable, T_NamedTuplestoreScan, T_SampleScan, T_SeqScan, T_SubqueryScan, T_TableFuncScan, T_TidRangeScan, T_TidScan, T_ValuesScan, and T_WorkTableScan.

Referenced by ExplainPrintPlan().

◆ ExplainPrintJIT()

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

Definition at line 869 of file explain.c.

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

844 {
845  JitInstrumentation ji = {0};
846 
847  if (!(queryDesc->estate->es_jit_flags & PGJIT_PERFORM))
848  return;
849 
850  /*
851  * Work with a copy instead of modifying the leader state, since this
852  * function may be called twice
853  */
854  if (queryDesc->estate->es_jit)
855  InstrJitAgg(&ji, &queryDesc->estate->es_jit->instr);
856 
857  /* If this process has done JIT in parallel workers, merge stats */
858  if (queryDesc->estate->es_jit_worker_instr)
859  InstrJitAgg(&ji, queryDesc->estate->es_jit_worker_instr);
860 
861  ExplainPrintJIT(es, queryDesc->estate->es_jit_flags, &ji);
862 }
void InstrJitAgg(JitInstrumentation *dst, JitInstrumentation *add)
Definition: jit.c:184
#define PGJIT_PERFORM
Definition: jit.h:20
struct JitContext * es_jit
Definition: execnodes.h:651
struct JitInstrumentation * es_jit_worker_instr
Definition: execnodes.h:652
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 751 of file explain.c.

752 {
753  Bitmapset *rels_used = NULL;
754  PlanState *ps;
755 
756  /* Set up ExplainState fields associated with this plan tree */
757  Assert(queryDesc->plannedstmt != NULL);
758  es->pstmt = queryDesc->plannedstmt;
759  es->rtable = queryDesc->plannedstmt->rtable;
760  ExplainPreScanNode(queryDesc->planstate, &rels_used);
763  es->rtable_names);
764  es->printed_subplans = NULL;
765 
766  /*
767  * Sometimes we mark a Gather node as "invisible", which means that it's
768  * not to be displayed in EXPLAIN output. The purpose of this is to allow
769  * running regression tests with force_parallel_mode=regress to get the
770  * same results as running the same tests with force_parallel_mode=off.
771  * Such marking is currently only supported on a Gather at the top of the
772  * plan. We skip that node, and we must also hide per-worker detail data
773  * further down in the plan tree.
774  */
775  ps = queryDesc->planstate;
776  if (IsA(ps, GatherState) && ((Gather *) ps->plan)->invisible)
777  {
778  ps = outerPlanState(ps);
779  es->hide_workers = true;
780  }
781  ExplainNode(ps, NIL, NULL, NULL, es);
782 
783  /*
784  * If requested, include information about GUC parameters with values that
785  * don't match the built-in defaults.
786  */
788 }
static void ExplainPrintSettings(ExplainState *es)
Definition: explain.c:681
List * select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
Definition: ruleutils.c:3752
List * deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
Definition: ruleutils.c:3660
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:66
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 681 of file explain.c.

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

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 800 of file explain.c.

801 {
802  ResultRelInfo *rInfo;
803  bool show_relname;
804  List *resultrels;
805  List *routerels;
806  List *targrels;
807  ListCell *l;
808 
809  resultrels = queryDesc->estate->es_opened_result_relations;
810  routerels = queryDesc->estate->es_tuple_routing_result_relations;
811  targrels = queryDesc->estate->es_trig_target_relations;
812 
813  ExplainOpenGroup("Triggers", "Triggers", false, es);
814 
815  show_relname = (list_length(resultrels) > 1 ||
816  routerels != NIL || targrels != NIL);
817  foreach(l, resultrels)
818  {
819  rInfo = (ResultRelInfo *) lfirst(l);
820  report_triggers(rInfo, show_relname, es);
821  }
822 
823  foreach(l, routerels)
824  {
825  rInfo = (ResultRelInfo *) lfirst(l);
826  report_triggers(rInfo, show_relname, es);
827  }
828 
829  foreach(l, targrels)
830  {
831  rInfo = (ResultRelInfo *) lfirst(l);
832  report_triggers(rInfo, show_relname, es);
833  }
834 
835  ExplainCloseGroup("Triggers", "Triggers", false, es);
836 }
static void report_triggers(ResultRelInfo *rInfo, bool show_relname, ExplainState *es)
Definition: explain.c:974
List * es_tuple_routing_result_relations
Definition: execnodes.h:593
List * es_trig_target_relations
Definition: execnodes.h:596
List * es_opened_result_relations
Definition: execnodes.h:583

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 4374 of file explain.c.

4376 {
4377  switch (es->format)
4378  {
4379  case EXPLAIN_FORMAT_TEXT:
4380  ExplainIndentText(es);
4381  if (unit)
4382  appendStringInfo(es->str, "%s: %s %s\n", qlabel, value, unit);
4383  else
4384  appendStringInfo(es->str, "%s: %s\n", qlabel, value);
4385  break;
4386 
4387  case EXPLAIN_FORMAT_XML:
4388  {
4389  char *str;
4390 
4391  appendStringInfoSpaces(es->str, es->indent * 2);
4392  ExplainXMLTag(qlabel, X_OPENING | X_NOWHITESPACE, es);
4393  str = escape_xml(value);
4395  pfree(str);
4396  ExplainXMLTag(qlabel, X_CLOSING | X_NOWHITESPACE, es);
4397  appendStringInfoChar(es->str, '\n');
4398  }
4399  break;
4400 
4401  case EXPLAIN_FORMAT_JSON:
4403  appendStringInfoSpaces(es->str, es->indent * 2);
4404  escape_json(es->str, qlabel);
4405  appendStringInfoString(es->str, ": ");
4406  if (numeric)
4408  else
4409  escape_json(es->str, value);
4410  break;
4411 
4412  case EXPLAIN_FORMAT_YAML:
4414  appendStringInfo(es->str, "%s: ", qlabel);
4415  if (numeric)
4417  else
4418  escape_yaml(es->str, value);
4419  break;
4420  }
4421 }
#define X_NOWHITESPACE
Definition: explain.c:55
static struct @142 value
char * escape_xml(const char *str)
Definition: xml.c:2353

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 4477 of file explain.c.

4478 {
4479  ExplainProperty(qlabel, NULL, value ? "true" : "false", true, es);
4480 }
static void ExplainProperty(const char *qlabel, const char *unit, const char *value, bool numeric, ExplainState *es)
Definition: explain.c:4374

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 4463 of file explain.c.

4465 {
4466  char *buf;
4467 
4468  buf = psprintf("%.*f", ndigits, value);
4469  ExplainProperty(qlabel, unit, buf, true, es);
4470  pfree(buf);
4471 }

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 4251 of file explain.c.

4252 {
4253  ListCell *lc;
4254  bool first = true;
4255 
4256  switch (es->format)
4257  {
4258  case EXPLAIN_FORMAT_TEXT:
4259  ExplainIndentText(es);
4260  appendStringInfo(es->str, "%s: ", qlabel);
4261  foreach(lc, data)
4262  {
4263  if (!first)
4264  appendStringInfoString(es->str, ", ");
4265  appendStringInfoString(es->str, (const char *) lfirst(lc));
4266  first = false;
4267  }
4268  appendStringInfoChar(es->str, '\n');
4269  break;
4270 
4271  case EXPLAIN_FORMAT_XML:
4272  ExplainXMLTag(qlabel, X_OPENING, es);
4273  foreach(lc, data)
4274  {
4275  char *str;
4276 
4277  appendStringInfoSpaces(es->str, es->indent * 2 + 2);
4278  appendStringInfoString(es->str, "<Item>");
4279  str = escape_xml((const char *) lfirst(lc));
4281  pfree(str);
4282  appendStringInfoString(es->str, "</Item>\n");
4283  }
4284  ExplainXMLTag(qlabel, X_CLOSING, es);
4285  break;
4286 
4287  case EXPLAIN_FORMAT_JSON:
4289  appendStringInfoSpaces(es->str, es->indent * 2);
4290  escape_json(es->str, qlabel);
4291  appendStringInfoString(es->str, ": [");
4292  foreach(lc, data)
4293  {
4294  if (!first)
4295  appendStringInfoString(es->str, ", ");
4296  escape_json(es->str, (const char *) lfirst(lc));
4297  first = false;
4298  }
4299  appendStringInfoChar(es->str, ']');
4300  break;
4301 
4302  case EXPLAIN_FORMAT_YAML:
4304  appendStringInfo(es->str, "%s: ", qlabel);
4305  foreach(lc, data)
4306  {
4307  appendStringInfoChar(es->str, '\n');
4308  appendStringInfoSpaces(es->str, es->indent * 2 + 2);
4309  appendStringInfoString(es->str, "- ");
4310  escape_yaml(es->str, (const char *) lfirst(lc));
4311  }
4312  break;
4313  }
4314 }
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 4321 of file explain.c.

4322 {
4323  ListCell *lc;
4324  bool first = true;
4325 
4326  switch (es->format)
4327  {
4328  case EXPLAIN_FORMAT_TEXT:
4329  case EXPLAIN_FORMAT_XML:
4330  ExplainPropertyList(qlabel, data, es);
4331  return;
4332 
4333  case EXPLAIN_FORMAT_JSON:
4335  appendStringInfoSpaces(es->str, es->indent * 2);
4336  appendStringInfoChar(es->str, '[');
4337  foreach(lc, data)
4338  {
4339  if (!first)
4340  appendStringInfoString(es->str, ", ");
4341  escape_json(es->str, (const char *) lfirst(lc));
4342  first = false;
4343  }
4344  appendStringInfoChar(es->str, ']');
4345  break;
4346 
4347  case EXPLAIN_FORMAT_YAML:
4349  appendStringInfoString(es->str, "- [");
4350  foreach(lc, data)
4351  {
4352  if (!first)
4353  appendStringInfoString(es->str, ", ");
4354  escape_yaml(es->str, (const char *) lfirst(lc));
4355  first = false;
4356  }
4357  appendStringInfoChar(es->str, ']');
4358  break;
4359  }
4360 }
void ExplainPropertyList(const char *qlabel, List *data, ExplainState *es)
Definition: explain.c:4251

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 4449 of file explain.c.

4451 {
4452  char buf[32];
4453 
4454  snprintf(buf, sizeof(buf), UINT64_FORMAT, value);
4455  ExplainProperty(qlabel, unit, buf, true, es);
4456 }
#define UINT64_FORMAT
Definition: c.h:484

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:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ereport(elevel,...)
Definition: elog.h:143
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
void end_tup_output(TupOutputState *tstate)
Definition: execTuples.c:2344
void do_text_output_multiline(TupOutputState *tstate, const char *txt)
Definition: execTuples.c:2314
TupOutputState * begin_tup_output_tupdesc(DestReceiver *dest, TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2266
#define do_text_output_oneline(tstate, str_to_emit)
Definition: executor.h:505
void ExplainSeparatePlans(ExplainState *es)
Definition: explain.c:4808
void ExplainEndOutput(ExplainState *es)
Definition: explain.c:4779
TupleDesc ExplainResultDesc(ExplainStmt *stmt)
Definition: explain.c:328
void ExplainBeginOutput(ExplainState *es)
Definition: explain.c:4748
ExplainState * NewExplainState(void)
Definition: explain.c:311
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:58
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
JumbleState * JumbleQuery(Query *query, const char *querytext)
Definition: queryjumble.c:101
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:78
char * defname
Definition: parsenodes.h:758
int location
Definition: parsenodes.h:761
Node * query
Definition: parsenodes.h:3390
List * options
Definition: parsenodes.h:3391
const char * p_sourcetext
Definition: parse_node.h:181

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().

◆ ExplainQueryText()

void ExplainQueryText ( ExplainState es,
QueryDesc queryDesc 
)

Definition at line 963 of file explain.c.

964 {
965  if (queryDesc->sourceText)
966  ExplainPropertyText("Query Text", queryDesc->sourceText, es);
967 }
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 4671 of file explain.c.

4672 {
4673  switch (es->format)
4674  {
4675  case EXPLAIN_FORMAT_TEXT:
4676  /* nothing to do */
4677  break;
4678 
4679  case EXPLAIN_FORMAT_XML:
4680  es->indent += depth;
4681  break;
4682 
4683  case EXPLAIN_FORMAT_JSON:
4684  es->grouping_stack = lcons_int(*state_save, es->grouping_stack);
4685  es->indent += depth;
4686  break;
4687 
4688  case EXPLAIN_FORMAT_YAML:
4689  es->grouping_stack = lcons_int(*state_save, es->grouping_stack);
4690  es->indent += depth;
4691  break;
4692  }
4693 }

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 4641 of file explain.c.

4642 {
4643  switch (es->format)
4644  {
4645  case EXPLAIN_FORMAT_TEXT:
4646  /* nothing to do */
4647  break;
4648 
4649  case EXPLAIN_FORMAT_XML:
4650  es->indent -= depth;
4651  break;
4652 
4653  case EXPLAIN_FORMAT_JSON:
4654  es->indent -= depth;
4655  *state_save = linitial_int(es->grouping_stack);
4657  break;
4658 
4659  case EXPLAIN_FORMAT_YAML:
4660  es->indent -= depth;
4661  *state_save = linitial_int(es->grouping_stack);
4663  break;
4664  }
4665 }

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 3704 of file explain.c.

3705 {
3706  ExplainTargetRel((Plan *) plan, plan->scanrelid, es);
3707 }

References ExplainTargetRel(), and Scan::scanrelid.

Referenced by ExplainNode().

◆ ExplainSeparatePlans()

void ExplainSeparatePlans ( ExplainState es)

Definition at line 4808 of file explain.c.

4809 {
4810  switch (es->format)
4811  {
4812  case EXPLAIN_FORMAT_TEXT:
4813  /* add a blank line */
4814  appendStringInfoChar(es->str, '\n');
4815  break;
4816 
4817  case EXPLAIN_FORMAT_XML:
4818  case EXPLAIN_FORMAT_JSON:
4819  case EXPLAIN_FORMAT_YAML:
4820  /* nothing to do */
4821  break;
4822  }
4823 }

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 4041 of file explain.c.

4043 {
4044  ListCell *lst;
4045 
4046  foreach(lst, plans)
4047  {
4048  SubPlanState *sps = (SubPlanState *) lfirst(lst);
4049  SubPlan *sp = sps->subplan;
4050 
4051  /*
4052  * There can be multiple SubPlan nodes referencing the same physical
4053  * subplan (same plan_id, which is its index in PlannedStmt.subplans).
4054  * We should print a subplan only once, so track which ones we already
4055  * printed. This state must be global across the plan tree, since the
4056  * duplicate nodes could be in different plan nodes, eg both a bitmap
4057  * indexscan's indexqual and its parent heapscan's recheck qual. (We
4058  * do not worry too much about which plan node we show the subplan as
4059  * attached to in such cases.)
4060  */
4061  if (bms_is_member(sp->plan_id, es->printed_subplans))
4062  continue;
4064  sp->plan_id);
4065 
4066  /*
4067  * Treat the SubPlan node as an ancestor of the plan node(s) within
4068  * it, so that ruleutils.c can find the referents of subplan
4069  * parameters.
4070  */
4071  ancestors = lcons(sp, ancestors);
4072 
4073  ExplainNode(sps->planstate, ancestors,
4074  relationship, sp->plan_name, es);
4075 
4076  ancestors = list_delete_first(ancestors);
4077  }
4078 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
struct PlanState * planstate
Definition: execnodes.h:889
SubPlan * subplan
Definition: execnodes.h:888
int plan_id
Definition: primnodes.h:752
char * plan_name
Definition: primnodes.h:754

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 3726 of file explain.c.

3727 {
3728  char *objectname = NULL;
3729  char *namespace = NULL;
3730  const char *objecttag = NULL;
3731  RangeTblEntry *rte;
3732  char *refname;
3733 
3734  rte = rt_fetch(rti, es->rtable);
3735  refname = (char *) list_nth(es->rtable_names, rti - 1);
3736  if (refname == NULL)
3737  refname = rte->eref->aliasname;
3738 
3739  switch (nodeTag(plan))
3740  {
3741  case T_SeqScan:
3742  case T_SampleScan:
3743  case T_IndexScan:
3744  case T_IndexOnlyScan:
3745  case T_BitmapHeapScan:
3746  case T_TidScan:
3747  case T_TidRangeScan:
3748  case T_ForeignScan:
3749  case T_CustomScan:
3750  case T_ModifyTable:
3751  /* Assert it's on a real relation */
3752  Assert(rte->rtekind == RTE_RELATION);
3753  objectname = get_rel_name(rte->relid);
3754  if (es->verbose)
3755  namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid));
3756  objecttag = "Relation Name";
3757  break;
3758  case T_FunctionScan:
3759  {
3760  FunctionScan *fscan = (FunctionScan *) plan;
3761 
3762  /* Assert it's on a RangeFunction */
3763  Assert(rte->rtekind == RTE_FUNCTION);
3764 
3765  /*
3766  * If the expression is still a function call of a single
3767  * function, we can get the real name of the function.
3768  * Otherwise, punt. (Even if it was a single function call
3769  * originally, the optimizer could have simplified it away.)
3770  */
3771  if (list_length(fscan->functions) == 1)
3772  {
3773  RangeTblFunction *rtfunc = (RangeTblFunction *) linitial(fscan->functions);
3774 
3775  if (IsA(rtfunc->funcexpr, FuncExpr))
3776  {
3777  FuncExpr *funcexpr = (FuncExpr *) rtfunc->funcexpr;
3778  Oid funcid = funcexpr->funcid;
3779 
3780  objectname = get_func_name(funcid);
3781  if (es->verbose)
3782  namespace = get_namespace_name_or_temp(get_func_namespace(funcid));
3783  }
3784  }
3785  objecttag = "Function Name";
3786  }
3787  break;
3788  case T_TableFuncScan:
3789  Assert(rte->rtekind == RTE_TABLEFUNC);
3790  objectname = "xmltable";
3791  objecttag = "Table Function Name";
3792  break;
3793  case T_ValuesScan:
3794  Assert(rte->rtekind == RTE_VALUES);
3795  break;
3796  case T_CteScan:
3797  /* Assert it's on a non-self-reference CTE */
3798  Assert(rte->rtekind == RTE_CTE);
3799  Assert(!rte->self_reference);
3800  objectname = rte->ctename;
3801  objecttag = "CTE Name";
3802  break;
3803  case T_NamedTuplestoreScan:
3805  objectname = rte->enrname;
3806  objecttag = "Tuplestore Name";
3807  break;
3808  case T_WorkTableScan:
3809  /* Assert it's on a self-reference CTE */
3810  Assert(rte->rtekind == RTE_CTE);
3811  Assert(rte->self_reference);
3812  objectname = rte->ctename;
3813  objecttag = "CTE Name";
3814  break;
3815  default:
3816  break;
3817  }
3818 
3819  if (es->format == EXPLAIN_FORMAT_TEXT)
3820  {
3821  appendStringInfoString(es->str, " on");
3822  if (namespace != NULL)
3823  appendStringInfo(es->str, " %s.%s", quote_identifier(namespace),
3824  quote_identifier(objectname));
3825  else if (objectname != NULL)
3826  appendStringInfo(es->str, " %s", quote_identifier(objectname));
3827  if (objectname == NULL || strcmp(refname, objectname) != 0)
3828  appendStringInfo(es->str, " %s", quote_identifier(refname));
3829  }
3830  else
3831  {
3832  if (objecttag != NULL && objectname != NULL)
3833  ExplainPropertyText(objecttag, objectname, es);
3834  if (namespace != NULL)
3835  ExplainPropertyText("Schema", namespace, es);
3836  ExplainPropertyText("Alias", refname, es);
3837  }
3838 }
char * get_namespace_name_or_temp(Oid nspid)
Definition: lsyscache.c:3340
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1579
Oid get_func_namespace(Oid funcid)
Definition: lsyscache.c:1603
@ RTE_CTE
Definition: parsenodes.h:996
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:997
@ RTE_VALUES
Definition: parsenodes.h:995
@ RTE_FUNCTION
Definition: parsenodes.h:993
@ RTE_TABLEFUNC
Definition: parsenodes.h:994
@ RTE_RELATION
Definition: parsenodes.h:990
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define linitial(l)
Definition: pg_list.h:174
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
char * aliasname
Definition: primnodes.h:42
Oid funcid
Definition: primnodes.h:495
List * functions
Definition: plannodes.h:555
char * ctename
Definition: parsenodes.h:1117
bool self_reference
Definition: parsenodes.h:1119
Alias * eref
Definition: parsenodes.h:1153
char * enrname
Definition: parsenodes.h:1146
RTEKind rtekind
Definition: parsenodes.h:1007

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, T_BitmapHeapScan, T_CteScan, T_CustomScan, T_ForeignScan, T_FunctionScan, T_IndexOnlyScan, T_IndexScan, T_ModifyTable, T_NamedTuplestoreScan, T_SampleScan, T_SeqScan, T_TableFuncScan, T_TidRangeScan, T_TidScan, T_ValuesScan, T_WorkTableScan, 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 4837 of file explain.c.

4838 {
4839  const char *s;
4840  const char *valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
4841 
4842  if ((flags & X_NOWHITESPACE) == 0)
4843  appendStringInfoSpaces(es->str, 2 * es->indent);
4844  appendStringInfoCharMacro(es->str, '<');
4845  if ((flags & X_CLOSING) != 0)
4846  appendStringInfoCharMacro(es->str, '/');
4847  for (s = tagname; *s; s++)
4848  appendStringInfoChar(es->str, strchr(valid, *s) ? *s : '-');
4849  if ((flags & X_CLOSE_IMMEDIATE) != 0)
4850  appendStringInfoString(es->str, " /");
4851  appendStringInfoCharMacro(es->str, '>');
4852  if ((flags & X_NOWHITESPACE) == 0)
4853  appendStringInfoCharMacro(es->str, '\n');
4854 }
#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 974 of file explain.c.

975 {
976  int nt;
977 
978  if (!rInfo->ri_TrigDesc || !rInfo->ri_TrigInstrument)
979  return;
980  for (nt = 0; nt < rInfo->ri_TrigDesc->numtriggers; nt++)
981  {
982  Trigger *trig = rInfo->ri_TrigDesc->triggers + nt;
983  Instrumentation *instr = rInfo->ri_TrigInstrument + nt;
984  char *relname;
985  char *conname = NULL;
986 
987  /* Must clean up instrumentation state */
988  InstrEndLoop(instr);
989 
990  /*
991  * We ignore triggers that were never invoked; they likely aren't
992  * relevant to the current query type.
993  */
994  if (instr->ntuples == 0)
995  continue;
996 
997  ExplainOpenGroup("Trigger", NULL, true, es);
998 
1000  if (OidIsValid(trig->tgconstraint))
1001  conname = get_constraint_name(trig->tgconstraint);
1002 
1003  /*
1004  * In text format, we avoid printing both the trigger name and the
1005  * constraint name unless VERBOSE is specified. In non-text formats
1006  * we just print everything.
1007  */
1008  if (es->format == EXPLAIN_FORMAT_TEXT)
1009  {
1010  if (es->verbose || conname == NULL)
1011  appendStringInfo(es->str, "Trigger %s", trig->tgname);
1012  else
1013  appendStringInfoString(es->str, "Trigger");
1014  if (conname)
1015  appendStringInfo(es->str, " for constraint %s", conname);
1016  if (show_relname)
1017  appendStringInfo(es->str, " on %s", relname);
1018  if (es->timing)
1019  appendStringInfo(es->str, ": time=%.3f calls=%.0f\n",
1020  1000.0 * instr->total, instr->ntuples);
1021  else
1022  appendStringInfo(es->str, ": calls=%.0f\n", instr->ntuples);
1023  }
1024  else
1025  {
1026  ExplainPropertyText("Trigger Name", trig->tgname, es);
1027  if (conname)
1028  ExplainPropertyText("Constraint Name", conname, es);
1029  ExplainPropertyText("Relation", relname, es);
1030  if (es->timing)
1031  ExplainPropertyFloat("Time", "ms", 1000.0 * instr->total, 3,
1032  es);
1033  ExplainPropertyFloat("Calls", NULL, instr->ntuples, 0, es);
1034  }
1035 
1036  if (conname)
1037  pfree(conname);
1038 
1039  ExplainCloseGroup("Trigger", NULL, true, es);
1040  }
1041 }
#define OidIsValid(objectId)
Definition: c.h:710
char * get_constraint_name(Oid conoid)
Definition: lsyscache.c:1106
NameData relname
Definition: pg_class.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:512
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:452
Relation ri_RelationDesc
Definition: execnodes.h:416
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:443
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 2373 of file explain.c.

2375 {
2376  Agg *plan = (Agg *) astate->ss.ps.plan;
2377 
2378  if (plan->numCols > 0 || plan->groupingSets)
2379  {
2380  /* The key columns refer to the tlist of the child plan */
2381  ancestors = lcons(plan, ancestors);
2382 
2383  if (plan->groupingSets)
2384  show_grouping_sets(outerPlanState(astate), plan, ancestors, es);
2385  else
2386  show_sort_group_keys(outerPlanState(astate), "Group Key",
2387  plan->numCols, 0, plan->grpColIdx,
2388  NULL, NULL, NULL,
2389  ancestors, es);
2390 
2391  ancestors = list_delete_first(ancestors);
2392  }
2393 }
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:2525
static void show_grouping_sets(PlanState *planstate, Agg *agg, List *ancestors, ExplainState *es)
Definition: explain.c:2396
ScanState ss
Definition: execnodes.h:2285
List * groupingSets
Definition: plannodes.h:891
AttrNumber * grpColIdx
Definition: plannodes.h:884
int numCols
Definition: plannodes.h:883
PlanState ps
Definition: execnodes.h:1382

References Agg::groupingSets, Agg::grpColIdx, 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 3491 of file explain.c.

3492 {
3493  if (es->format == EXPLAIN_FORMAT_TEXT)
3494  {
3495  bool has_shared = (usage->shared_blks_hit > 0 ||
3496  usage->shared_blks_read > 0 ||
3497  usage->shared_blks_dirtied > 0 ||
3498  usage->shared_blks_written > 0);
3499  bool has_local = (usage->local_blks_hit > 0 ||
3500  usage->local_blks_read > 0 ||
3501  usage->local_blks_dirtied > 0 ||
3502  usage->local_blks_written > 0);
3503  bool has_temp = (usage->temp_blks_read > 0 ||
3504  usage->temp_blks_written > 0);
3505  bool has_timing = (!INSTR_TIME_IS_ZERO(usage->blk_read_time) ||
3506  !INSTR_TIME_IS_ZERO(usage->blk_write_time));
3507  bool show_planning = (planning && (has_shared ||
3508  has_local || has_temp || has_timing));
3509 
3510  if (show_planning)
3511  {
3512  ExplainIndentText(es);
3513  appendStringInfoString(es->str, "Planning:\n");
3514  es->indent++;
3515  }
3516 
3517  /* Show only positive counter values. */
3518  if (has_shared || has_local || has_temp)
3519  {
3520  ExplainIndentText(es);
3521  appendStringInfoString(es->str, "Buffers:");
3522 
3523  if (has_shared)
3524  {
3525  appendStringInfoString(es->str, " shared");
3526  if (usage->shared_blks_hit > 0)
3527  appendStringInfo(es->str, " hit=%lld",
3528  (long long) usage->shared_blks_hit);
3529  if (usage->shared_blks_read > 0)
3530  appendStringInfo(es->str, " read=%lld",
3531  (long long) usage->shared_blks_read);
3532  if (usage->shared_blks_dirtied > 0)
3533  appendStringInfo(es->str, " dirtied=%lld",
3534  (long long) usage->shared_blks_dirtied);
3535  if (usage->shared_blks_written > 0)
3536  appendStringInfo(es->str, " written=%lld",
3537  (long long) usage->shared_blks_written);
3538  if (has_local || has_temp)
3539  appendStringInfoChar(es->str, ',');
3540  }
3541  if (has_local)
3542  {
3543  appendStringInfoString(es->str, " local");
3544  if (usage->local_blks_hit > 0)
3545  appendStringInfo(es->str, " hit=%lld",
3546  (long long) usage->local_blks_hit);
3547  if (usage->local_blks_read > 0)
3548  appendStringInfo(es->str, " read=%lld",
3549  (long long) usage->local_blks_read);
3550  if (usage->local_blks_dirtied > 0)
3551  appendStringInfo(es->str, " dirtied=%lld",
3552  (long long) usage->local_blks_dirtied);
3553  if (usage->local_blks_written > 0)
3554  appendStringInfo(es->str, " written=%lld",
3555  (long long) usage->local_blks_written);
3556  if (has_temp)
3557  appendStringInfoChar(es->str, ',');
3558  }
3559  if (has_temp)
3560  {
3561  appendStringInfoString(es->str, " temp");
3562  if (usage->temp_blks_read > 0)
3563  appendStringInfo(es->str, " read=%lld",
3564  (long long) usage->temp_blks_read);
3565  if (usage->temp_blks_written > 0)
3566  appendStringInfo(es->str, " written=%lld",
3567  (long long) usage->temp_blks_written);
3568  }
3569  appendStringInfoChar(es->str, '\n');
3570  }
3571 
3572  /* As above, show only positive counter values. */
3573  if (has_timing)
3574  {
3575  ExplainIndentText(es);
3576  appendStringInfoString(es->str, "I/O Timings:");
3577  if (!INSTR_TIME_IS_ZERO(usage->blk_read_time))
3578  appendStringInfo(es->str, " read=%0.3f",
3579  INSTR_TIME_GET_MILLISEC(usage->blk_read_time));
3580  if (!INSTR_TIME_IS_ZERO(usage->blk_write_time))
3581  appendStringInfo(es->str, " write=%0.3f",
3582  INSTR_TIME_GET_MILLISEC(usage->blk_write_time));
3583  appendStringInfoChar(es->str, '\n');
3584  }
3585 
3586  if (show_planning)
3587  es->indent--;
3588  }
3589  else
3590  {
3591  ExplainPropertyInteger("Shared Hit Blocks", NULL,
3592  usage->shared_blks_hit, es);
3593  ExplainPropertyInteger("Shared Read Blocks", NULL,
3594  usage->shared_blks_read, es);
3595  ExplainPropertyInteger("Shared Dirtied Blocks", NULL,
3596  usage->shared_blks_dirtied, es);
3597  ExplainPropertyInteger("Shared Written Blocks", NULL,
3598  usage->shared_blks_written, es);
3599  ExplainPropertyInteger("Local Hit Blocks", NULL,
3600  usage->local_blks_hit, es);
3601  ExplainPropertyInteger("Local Read Blocks", NULL,
3602  usage->local_blks_read, es);
3603  ExplainPropertyInteger("Local Dirtied Blocks", NULL,
3604  usage->local_blks_dirtied, es);
3605  ExplainPropertyInteger("Local Written Blocks", NULL,
3606  usage->local_blks_written, es);
3607  ExplainPropertyInteger("Temp Read Blocks", NULL,
3608  usage->temp_blks_read, es);
3609  ExplainPropertyInteger("Temp Written Blocks", NULL,
3610  usage->temp_blks_written, es);
3611  if (track_io_timing)
3612  {
3613  ExplainPropertyFloat("I/O Read Time", "ms",
3614  INSTR_TIME_GET_MILLISEC(usage->blk_read_time),
3615  3, es);
3616  ExplainPropertyFloat("I/O Write Time", "ms",
3617  INSTR_TIME_GET_MILLISEC(usage->blk_write_time),
3618  3, es);
3619  }
3620  }
3621 }
bool track_io_timing
Definition: bufmgr.c:135
#define INSTR_TIME_IS_ZERO(t)
Definition: instr_time.h:152
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:202
static void usage(const char *progname)
Definition: vacuumlo.c:417

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 3439 of file explain.c.

3440 {
3441  int paramid = -1;
3442  List *params = NIL;
3443 
3444  Assert(bms_params);
3445 
3446  while ((paramid = bms_next_member(bms_params, paramid)) >= 0)
3447  {
3448  char param[32];
3449 
3450  snprintf(param, sizeof(param), "$%d", paramid);
3451  params = lappend(params, pstrdup(param));
3452  }
3453 
3454  if (params)
3455  ExplainPropertyList("Params Evaluated", params, es);
3456 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1045
char * pstrdup(const char *in)
Definition: mcxt.c:1299

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 2253 of file explain.c.

2256 {
2257  List *context;
2258  char *exprstr;
2259 
2260  /* Set up deparsing context */
2261  context = set_deparse_context_plan(es->deparse_cxt,
2262  planstate->plan,
2263  ancestors);
2264 
2265  /* Deparse the expression */
2266  exprstr = deparse_expression(node, context, useprefix, false);
2267 
2268  /* And add to es->str */
2269  ExplainPropertyText(qlabel, exprstr, es);
2270 }
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition: ruleutils.c:3555
List * set_deparse_context_plan(List *dpcontext, Plan *plan, List *ancestors)
Definition: ruleutils.c:3729

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 3418 of file explain.c.

3419 {
3420  FdwRoutine *fdwroutine = fsstate->fdwroutine;
3421 
3422  /* Let the FDW emit whatever fields it wants */
3423  if (((ForeignScan *) fsstate->ss.ps.plan)->operation != CMD_SELECT)
3424  {
3425  if (fdwroutine->ExplainDirectModify != NULL)
3426  fdwroutine->ExplainDirectModify(fsstate, es);
3427  }
3428  else
3429  {
3430  if (fdwroutine->ExplainForeignScan != NULL)
3431  fdwroutine->ExplainForeignScan(fsstate, es);
3432  }
3433 }
ExplainForeignScan_function ExplainForeignScan
Definition: fdwapi.h:252
ExplainDirectModify_function ExplainDirectModify
Definition: fdwapi.h:254
struct FdwRoutine * fdwroutine
Definition: execnodes.h:1867
ScanState ss
Definition: execnodes.h:1862

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 2505 of file explain.c.

2507 {
2508  Group *plan = (Group *) gstate->ss.ps.plan;
2509 
2510  /* The key columns refer to the tlist of the child plan */
2511  ancestors = lcons(plan, ancestors);
2512  show_sort_group_keys(outerPlanState(gstate), "Group Key",
2513  plan->numCols, 0, plan->grpColIdx,
2514  NULL, NULL, NULL,
2515  ancestors, es);
2516  ancestors = list_delete_first(ancestors);
2517 }
ScanState ss
Definition: execnodes.h:2238
int numCols
Definition: plannodes.h:858
AttrNumber * grpColIdx
Definition: plannodes.h:859

References Group::grpColIdx, 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 2427 of file explain.c.

2431 {
2432  Plan *plan = planstate->plan;
2433  char *exprstr;
2434  ListCell *lc;
2435  List *gsets = aggnode->groupingSets;
2436  AttrNumber *keycols = aggnode->grpColIdx;
2437  const char *keyname;
2438  const char *keysetname;
2439 
2440  if (aggnode->aggstrategy == AGG_HASHED || aggnode->aggstrategy == AGG_MIXED)
2441  {
2442  keyname = "Hash Key";
2443  keysetname = "Hash Keys";
2444  }
2445  else
2446  {
2447  keyname = "Group Key";
2448  keysetname = "Group Keys";
2449  }
2450 
2451  ExplainOpenGroup("Grouping Set", NULL, true, es);
2452 
2453  if (sortnode)
2454  {
2455  show_sort_group_keys(planstate, "Sort Key",
2456  sortnode->numCols, 0, sortnode->sortColIdx,
2457  sortnode->sortOperators, sortnode->collations,
2458  sortnode->nullsFirst,
2459  ancestors, es);
2460  if (es->format == EXPLAIN_FORMAT_TEXT)
2461  es->indent++;
2462  }
2463 
2464  ExplainOpenGroup(keysetname, keysetname, false, es);
2465 
2466  foreach(lc, gsets)
2467  {
2468  List *result = NIL;
2469  ListCell *lc2;
2470 
2471  foreach(lc2, (List *) lfirst(lc))
2472  {
2473  Index i = lfirst_int(lc2);
2474  AttrNumber keyresno = keycols[i];
2475  TargetEntry *target = get_tle_by_resno(plan->targetlist,
2476  keyresno);
2477 
2478  if (!target)
2479  elog(ERROR, "no tlist entry for key %d", keyresno);
2480  /* Deparse the expression, showing any top-level cast */
2481  exprstr = deparse_expression((Node *) target->expr, context,
2482  useprefix, true);
2483 
2484  result = lappend(result, exprstr);
2485  }
2486 
2487  if (!result && es->format == EXPLAIN_FORMAT_TEXT)
2488  ExplainPropertyText(keyname, "()", es);
2489  else
2490  ExplainPropertyListNested(keyname, result, es);
2491  }
2492 
2493  ExplainCloseGroup(keysetname, keysetname, false, es);
2494 
2495  if (sortnode && es->format == EXPLAIN_FORMAT_TEXT)
2496  es->indent--;
2497 
2498  ExplainCloseGroup("Grouping Set", NULL, true, es);
2499 }
unsigned int Index
Definition: c.h:549
void ExplainPropertyListNested(const char *qlabel, List *data, ExplainState *es)
Definition: explain.c:4321
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
#define lfirst_int(lc)
Definition: pg_list.h:170
List * targetlist
Definition: plannodes.h:141
Oid * sortOperators
Definition: plannodes.h:834
int numCols
Definition: plannodes.h:832
bool * nullsFirst
Definition: plannodes.h:836
AttrNumber * sortColIdx
Definition: plannodes.h:833
Oid * collations
Definition: plannodes.h:835
Expr * expr
Definition: primnodes.h:1455

References AGG_HASHED, AGG_MIXED, Agg::aggstrategy, Sort::collations, config_generic::context, deparse_expression(), elog, ERROR, EXPLAIN_FORMAT_TEXT, ExplainCloseGroup(), ExplainOpenGroup(), ExplainPropertyListNested(), ExplainPropertyText(), TargetEntry::expr, ExplainState::format, get_tle_by_resno(), Agg::groupingSets, Agg::grpColIdx, i, ExplainState::indent, lappend(), lfirst, lfirst_int, NIL, Sort::nullsFirst, Sort::numCols, PlanState::plan, show_sort_group_keys(), Sort::sortColIdx, Sort::sortOperators, 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 2396 of file explain.c.

2398 {
2399  List *context;
2400  bool useprefix;
2401  ListCell *lc;
2402 
2403  /* Set up deparsing context */
2404  context = set_deparse_context_plan(es->deparse_cxt,
2405  planstate->plan,
2406  ancestors);
2407  useprefix = (list_length(es->rtable) > 1 || es->verbose);
2408 
2409  ExplainOpenGroup("Grouping Sets", "Grouping Sets", false, es);
2410 
2411  show_grouping_set_keys(planstate, agg, NULL,
2412  context, useprefix, ancestors, es);
2413 
2414  foreach(lc, agg->chain)
2415  {
2416  Agg *aggnode = lfirst(lc);
2417  Sort *sortnode = (Sort *) aggnode->plan.lefttree;
2418 
2419  show_grouping_set_keys(planstate, aggnode, sortnode,
2420  context, useprefix, ancestors, es);
2421  }
2422 
2423  ExplainCloseGroup("Grouping Sets", "Grouping Sets", false, es);
2424 }
static void show_grouping_set_keys(PlanState *planstate, Agg *aggnode, Sort *sortnode, List *context, bool useprefix, List *ancestors, ExplainState *es)
Definition: explain.c:2427
List * chain
Definition: plannodes.h:892
Plan plan
Definition: plannodes.h:880
struct Plan * lefttree
Definition: plannodes.h:143

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 3002 of file explain.c.

3003 {
3004  HashInstrumentation hinstrument = {0};
3005 
3006  /*
3007  * Collect stats from the local process, even when it's a parallel query.
3008  * In a parallel query, the leader process may or may not have run the
3009  * hash join, and even if it did it may not have built a hash table due to
3010  * timing (if it started late it might have seen no tuples in the outer
3011  * relation and skipped building the hash table). Therefore we have to be
3012  * prepared to get instrumentation data from all participants.
3013  */
3014  if (hashstate->hinstrument)
3015  memcpy(&hinstrument, hashstate->hinstrument,
3016  sizeof(HashInstrumentation));
3017 
3018  /*
3019  * Merge results from workers. In the parallel-oblivious case, the
3020  * results from all participants should be identical, except where
3021  * participants didn't run the join at all so have no data. In the
3022  * parallel-aware case, we need to consider all the results. Each worker
3023  * may have seen a different subset of batches and we want to report the
3024  * highest memory usage across all batches. We take the maxima of other
3025  * values too, for the same reasons as in ExecHashAccumInstrumentation.
3026  */
3027  if (hashstate->shared_info)
3028  {
3029  SharedHashInfo *shared_info = hashstate->shared_info;
3030  int i;
3031 
3032  for (i = 0; i < shared_info->num_workers; ++i)
3033  {
3034  HashInstrumentation *worker_hi = &shared_info->hinstrument[i];
3035 
3036  hinstrument.nbuckets = Max(hinstrument.nbuckets,
3037  worker_hi->nbuckets);
3038  hinstrument.nbuckets_original = Max(hinstrument.nbuckets_original,
3039  worker_hi->nbuckets_original);
3040  hinstrument.nbatch = Max(hinstrument.nbatch,
3041  worker_hi->nbatch);
3042  hinstrument.nbatch_original = Max(hinstrument.nbatch_original,
3043  worker_hi->nbatch_original);
3044  hinstrument.space_peak = Max(hinstrument.space_peak,
3045  worker_hi->space_peak);
3046  }
3047  }
3048 
3049  if (hinstrument.nbatch > 0)
3050  {
3051  long spacePeakKb = (hinstrument.space_peak + 1023) / 1024;
3052 
3053  if (es->format != EXPLAIN_FORMAT_TEXT)
3054  {
3055  ExplainPropertyInteger("Hash Buckets", NULL,
3056  hinstrument.nbuckets, es);
3057  ExplainPropertyInteger("Original Hash Buckets", NULL,
3058  hinstrument.nbuckets_original, es);
3059  ExplainPropertyInteger("Hash Batches", NULL,
3060  hinstrument.nbatch, es);
3061  ExplainPropertyInteger("Original Hash Batches", NULL,
3062  hinstrument.nbatch_original, es);
3063  ExplainPropertyInteger("Peak Memory Usage", "kB",
3064  spacePeakKb, es);
3065  }
3066  else if (hinstrument.nbatch_original != hinstrument.nbatch ||
3067  hinstrument.nbuckets_original != hinstrument.nbuckets)
3068  {
3069  ExplainIndentText(es);
3070  appendStringInfo(es->str,
3071  "Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: %ldkB\n",
3072  hinstrument.nbuckets,
3073  hinstrument.nbuckets_original,
3074  hinstrument.nbatch,
3075  hinstrument.nbatch_original,
3076  spacePeakKb);
3077  }
3078  else
3079  {
3080  ExplainIndentText(es);
3081  appendStringInfo(es->str,
3082  "Buckets: %d Batches: %d Memory Usage: %ldkB\n",
3083  hinstrument.nbuckets, hinstrument.nbatch,
3084  spacePeakKb);
3085  }
3086  }
3087 }
#define Max(x, y)
Definition: c.h:980
SharedHashInfo * shared_info
Definition: execnodes.h:2555
HashInstrumentation * hinstrument
Definition: execnodes.h:2562
HashInstrumentation hinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2536

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 hashstate,
ExplainState es 
)
static

Definition at line 3237 of file explain.c.

3238 {
3239  Agg *agg = (Agg *) aggstate->ss.ps.plan;
3240  int64 memPeakKb = (aggstate->hash_mem_peak + 1023) / 1024;
3241 
3242  if (agg->aggstrategy != AGG_HASHED &&
3243  agg->aggstrategy != AGG_MIXED)
3244  return;
3245 
3246  if (es->format != EXPLAIN_FORMAT_TEXT)
3247  {
3248 
3249  if (es->costs)
3250  ExplainPropertyInteger("Planned Partitions", NULL,
3251  aggstate->hash_planned_partitions, es);
3252 
3253  /*
3254  * During parallel query the leader may have not helped out. We
3255  * detect this by checking how much memory it used. If we find it
3256  * didn't do any work then we don't show its properties.
3257  */
3258  if (es->analyze && aggstate->hash_mem_peak > 0)
3259  {
3260  ExplainPropertyInteger("HashAgg Batches", NULL,
3261  aggstate->hash_batches_used, es);
3262  ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb, es);
3263  ExplainPropertyInteger("Disk Usage", "kB",
3264  aggstate->hash_disk_used, es);
3265  }
3266  }
3267  else
3268  {
3269  bool gotone = false;
3270 
3271  if (es->costs && aggstate->hash_planned_partitions > 0)
3272  {
3273  ExplainIndentText(es);
3274  appendStringInfo(es->str, "Planned Partitions: %d",
3275  aggstate->hash_planned_partitions);
3276  gotone = true;
3277  }
3278 
3279  /*
3280  * During parallel query the leader may have not helped out. We
3281  * detect this by checking how much memory it used. If we find it
3282  * didn't do any work then we don't show its properties.
3283  */
3284  if (es->analyze && aggstate->hash_mem_peak > 0)
3285  {
3286  if (!gotone)
3287  ExplainIndentText(es);
3288  else
3289  appendStringInfoString(es->str, " ");
3290 
3291  appendStringInfo(es->str, "Batches: %d Memory Usage: " INT64_FORMAT "kB",
3292  aggstate->hash_batches_used, memPeakKb);
3293  gotone = true;
3294 
3295  /* Only display disk usage if we spilled to disk */
3296  if (aggstate->hash_batches_used > 1)
3297  {
3298  appendStringInfo(es->str, " Disk Usage: " UINT64_FORMAT "kB",
3299  aggstate->hash_disk_used);
3300  }
3301  }
3302 
3303  if (gotone)
3304  appendStringInfoChar(es->str, '\n');
3305  }
3306 
3307  /* Display stats for each parallel worker */
3308  if (es->analyze && aggstate->shared_info != NULL)
3309  {
3310  for (int n = 0; n < aggstate->shared_info->num_workers; n++)
3311  {
3312  AggregateInstrumentation *sinstrument;
3313  uint64 hash_disk_used;
3314  int hash_batches_used;
3315 
3316  sinstrument = &aggstate->shared_info->sinstrument[n];
3317  /* Skip workers that didn't do anything */
3318  if (sinstrument->hash_mem_peak == 0)
3319  continue;
3320