Debian Codegraph @

src/backend/commands/explain.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * explain.c
4 * Explain query execution plans
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994-5, Regents of the University of California
8 *
9 * IDENTIFICATION
10 * src/backend/commands/explain.c
11 *
12 *-------------------------------------------------------------------------
13 */
14 #include "postgres.h"
15
16 #include "access/xact.h"
17 #include "catalog/pg_type.h"
18 #include "commands/createas.h"
19 #include "commands/defrem.h"
20 #include "commands/explain.h"
21 #include "commands/explain_dr.h"
22 #include "commands/explain_format.h"
23 #include "commands/explain_state.h"
24 #include "commands/prepare.h"
25 #include "foreign/fdwapi.h"
26 #include "jit/jit.h"
27 #include "libpq/pqformat.h"
28 #include "libpq/protocol.h"
29 #include "nodes/extensible.h"
30 #include "nodes/makefuncs.h"
31 #include "nodes/nodeFuncs.h"
32 #include "parser/analyze.h"
33 #include "parser/parsetree.h"
34 #include "rewrite/rewriteHandler.h"
35 #include "storage/bufmgr.h"
36 #include "tcop/tcopprot.h"
37 #include "utils/builtins.h"
38 #include "utils/guc_tables.h"
39 #include "utils/json.h"
40 #include "utils/lsyscache.h"
41 #include "utils/rel.h"
42 #include "utils/ruleutils.h"
43 #include "utils/snapmgr.h"
44 #include "utils/tuplesort.h"
45 #include "utils/typcache.h"
46 #include "utils/xml.h"
47
48
49 /* Hook for plugins to get control in ExplainOneQuery() */
50 ExplainOneQuery_hook_type ExplainOneQuery_hook = NULL;
51
52 /* Hook for plugins to get control in explain_get_index_name() */
53 explain_get_index_name_hook_type explain_get_index_name_hook = NULL;
54
55 /* per-plan and per-node hooks for plugins to print additional info */
56 explain_per_plan_hook_type explain_per_plan_hook = NULL;
57 explain_per_node_hook_type explain_per_node_hook = NULL;
58
59 /*
60 * Various places within need to convert bytes to kilobytes. Round these up
61 * to the next whole kilobyte.
62 */
63 #define BYTES_TO_KILOBYTES(b) (((b) + 1023) / 1024)
64
65 static void ExplainOneQuery(Query *query, int cursorOptions,
66 IntoClause *into, ExplainState *es,
67 ParseState *pstate, ParamListInfo params);
68 static void ExplainPrintJIT(ExplainState *es, int jit_flags,
69 JitInstrumentation *ji);
70 static void ExplainPrintSerialize(ExplainState *es,
71 SerializeMetrics *metrics);
72 static void report_triggers(ResultRelInfo *rInfo, bool show_relname,
73 ExplainState *es);
74 static double elapsed_time(instr_time *starttime);
75 static bool ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used);
76 static void ExplainNode(PlanState *planstate, List *ancestors,
77 const char *relationship, const char *plan_name,
78 ExplainState *es);
79 static void show_plan_tlist(PlanState *planstate, List *ancestors,
80 ExplainState *es);
81 static void show_expression(Node *node, const char *qlabel,
82 PlanState *planstate, List *ancestors,
83 bool useprefix, ExplainState *es);
84 static void show_qual(List *qual, const char *qlabel,
85 PlanState *planstate, List *ancestors,
86 bool useprefix, ExplainState *es);
87 static void show_scan_qual(List *qual, const char *qlabel,
88 PlanState *planstate, List *ancestors,
89 ExplainState *es);
90 static void show_upper_qual(List *qual, const char *qlabel,
91 PlanState *planstate, List *ancestors,
92 ExplainState *es);
93 static void show_sort_keys(SortState *sortstate, List *ancestors,
94 ExplainState *es);
95 static void show_incremental_sort_keys(IncrementalSortState *incrsortstate,
96 List *ancestors, ExplainState *es);
97 static void show_merge_append_keys(MergeAppendState *mstate, List *ancestors,
98 ExplainState *es);
99 static void show_agg_keys(AggState *astate, List *ancestors,
100 ExplainState *es);
101 static void show_grouping_sets(PlanState *planstate, Agg *agg,
102 List *ancestors, ExplainState *es);
103 static void show_grouping_set_keys(PlanState *planstate,
104 Agg *aggnode, Sort *sortnode,
105 List *context, bool useprefix,
106 List *ancestors, ExplainState *es);
107 static void show_group_keys(GroupState *gstate, List *ancestors,
108 ExplainState *es);
109 static void show_sort_group_keys(PlanState *planstate, const char *qlabel,
110 int nkeys, int nPresortedKeys, AttrNumber *keycols,
111 Oid *sortOperators, Oid *collations, bool *nullsFirst,
112 List *ancestors, ExplainState *es);
113 static void show_sortorder_options(StringInfo buf, Node *sortexpr,
114 Oid sortOperator, Oid collation, bool nullsFirst);
115 static void show_window_def(WindowAggState *planstate,
116 List *ancestors, ExplainState *es);
117 static void show_window_keys(StringInfo buf, PlanState *planstate,
118 int nkeys, AttrNumber *keycols,
119 List *ancestors, ExplainState *es);
120 static void show_storage_info(char *maxStorageType, int64 maxSpaceUsed,
121 ExplainState *es);
122 static void show_tablesample(TableSampleClause *tsc, PlanState *planstate,
123 List *ancestors, ExplainState *es);
124 static void show_sort_info(SortState *sortstate, ExplainState *es);
125 static void show_incremental_sort_info(IncrementalSortState *incrsortstate,
126 ExplainState *es);
127 static void show_hash_info(HashState *hashstate, ExplainState *es);
128 static void show_material_info(MaterialState *mstate, ExplainState *es);
129 static void show_windowagg_info(WindowAggState *winstate, ExplainState *es);
130 static void show_ctescan_info(CteScanState *ctescanstate, ExplainState *es);
131 static void show_table_func_scan_info(TableFuncScanState *tscanstate,
132 ExplainState *es);
133 static void show_recursive_union_info(RecursiveUnionState *rstate,
134 ExplainState *es);
135 static void show_memoize_info(MemoizeState *mstate, List *ancestors,
136 ExplainState *es);
137 static void show_hashagg_info(AggState *aggstate, ExplainState *es);
138 static void show_indexsearches_info(PlanState *planstate, ExplainState *es);
139 static void show_tidbitmap_info(BitmapHeapScanState *planstate,
140 ExplainState *es);
141 static void show_instrumentation_count(const char *qlabel, int which,
142 PlanState *planstate, ExplainState *es);
143 static void show_foreignscan_info(ForeignScanState *fsstate, ExplainState *es);
144 static const char *explain_get_index_name(Oid indexId);
145 static bool peek_buffer_usage(ExplainState *es, const BufferUsage *usage);
146 static void show_buffer_usage(ExplainState *es, const BufferUsage *usage);
147 static void show_wal_usage(ExplainState *es, const WalUsage *usage);
148 static void show_memory_counters(ExplainState *es,
149 const MemoryContextCounters *mem_counters);
150 static void ExplainIndexScanDetails(Oid indexid, ScanDirection indexorderdir,
151 ExplainState *es);
152 static void ExplainScanTarget(Scan *plan, ExplainState *es);
153 static void ExplainModifyTarget(ModifyTable *plan, ExplainState *es);
154 static void ExplainTargetRel(Plan *plan, Index rti, ExplainState *es);
155 static void show_modifytable_info(ModifyTableState *mtstate, List *ancestors,
156 ExplainState *es);
157 static void ExplainMemberNodes(PlanState **planstates, int nplans,
158 List *ancestors, ExplainState *es);
159 static void ExplainMissingMembers(int nplans, int nchildren, ExplainState *es);
160 static void ExplainSubPlans(List *plans, List *ancestors,
161 const char *relationship, ExplainState *es);
162 static void ExplainCustomChildren(CustomScanState *css,
163 List *ancestors, ExplainState *es);
164 static ExplainWorkersState *ExplainCreateWorkersState(int num_workers);
165 static void ExplainOpenWorker(int n, ExplainState *es);
166 static void ExplainCloseWorker(int n, ExplainState *es);
167 static void ExplainFlushWorkersState(ExplainState *es);
168
169
170
171 /*
172 * ExplainQuery -
173 * execute an EXPLAIN command
174 */
175 void
176 ExplainQuery(ParseState *pstate, ExplainStmt *stmt,
177 ParamListInfo params, DestReceiver *dest)
178 {
179 ExplainState *es = NewExplainState();
180 TupOutputState *tstate;
181 JumbleState *jstate = NULL;
182 Query *query;
183 List *rewritten;
184
185 /* Configure the ExplainState based on the provided options */
186 ParseExplainOptionList(es, stmt->options, pstate);
187
188 /* Extract the query and, if enabled, jumble it */
189 query = castNode(Query, stmt->query);
190 if (IsQueryIdEnabled())
191 jstate = JumbleQuery(query);
192
193 if (post_parse_analyze_hook)
194 (*post_parse_analyze_hook) (pstate, query, jstate);
195
196 /*
197 * Parse analysis was done already, but we still have to run the rule
198 * rewriter. We do not do AcquireRewriteLocks: we assume the query either
199 * came straight from the parser, or suitable locks were acquired by
200 * plancache.c.
201 */
202 rewritten = QueryRewrite(castNode(Query, stmt->query));
203
204 /* emit opening boilerplate */
205 ExplainBeginOutput(es);
206
207 if (rewritten == NIL)
208 {
209 /*
210 * In the case of an INSTEAD NOTHING, tell at least that. But in
211 * non-text format, the output is delimited, so this isn't necessary.
212 */
213 if (es->format == EXPLAIN_FORMAT_TEXT)
214 appendStringInfoString(es->str, "Query rewrites to nothing\n");
215 }
216 else
217 {
218 ListCell *l;
219
220 /* Explain every plan */
221 foreach(l, rewritten)
222 {
223 ExplainOneQuery(lfirst_node(Query, l),
224 CURSOR_OPT_PARALLEL_OK, NULL, es,
225 pstate, params);
226
227 /* Separate plans with an appropriate separator */
228 if (lnext(rewritten, l) != NULL)
229 ExplainSeparatePlans(es);
230 }
231 }
232
233 /* emit closing boilerplate */
234 ExplainEndOutput(es);
235 Assert(es->indent == 0);
236
237 /* output tuples */
238 tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt),
239 &TTSOpsVirtual);
240 if (es->format == EXPLAIN_FORMAT_TEXT)
241 do_text_output_multiline(tstate, es->str->data);
242 else
243 do_text_output_oneline(tstate, es->str->data);
244 end_tup_output(tstate);
245
246 pfree(es->str->data);
247 }
248
249 /*
250 * ExplainResultDesc -
251 * construct the result tupledesc for an EXPLAIN
252 */
253 TupleDesc
254 ExplainResultDesc(ExplainStmt *stmt)
255 {
256 TupleDesc tupdesc;
257 ListCell *lc;
258 Oid result_type = TEXTOID;
259
260 /* Check for XML format option */
261 foreach(lc, stmt->options)
262 {
263 DefElem *opt = (DefElem *) lfirst(lc);
264
265 if (strcmp(opt->defname, "format") == 0)
266 {
267 char *p = defGetString(opt);
268
269 if (strcmp(p, "xml") == 0)
270 result_type = XMLOID;
271 else if (strcmp(p, "json") == 0)
272 result_type = JSONOID;
273 else
274 result_type = TEXTOID;
275 /* don't "break", as ExplainQuery will use the last value */
276 }
277 }
278
279 /* Need a tuple descriptor representing a single TEXT or XML column */
280 tupdesc = CreateTemplateTupleDesc(1);
281 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "QUERY PLAN",
282 result_type, -1, 0);
283 return tupdesc;
284 }
285
286 /*
287 * ExplainOneQuery -
288 * print out the execution plan for one Query
289 *
290 * "into" is NULL unless we are explaining the contents of a CreateTableAsStmt.
291 */
292 static void
293 ExplainOneQuery(Query *query, int cursorOptions,
294 IntoClause *into, ExplainState *es,
295 ParseState *pstate, ParamListInfo params)
296 {
297 /* planner will not cope with utility statements */
298 if (query->commandType == CMD_UTILITY)
299 {
300 ExplainOneUtility(query->utilityStmt, into, es, pstate, params);
301 return;
302 }
303
304 /* if an advisor plugin is present, let it manage things */
305 if (ExplainOneQuery_hook)
306 (*ExplainOneQuery_hook) (query, cursorOptions, into, es,
307 pstate->p_sourcetext, params, pstate->p_queryEnv);
308 else
309 standard_ExplainOneQuery(query, cursorOptions, into, es,
310 pstate->p_sourcetext, params, pstate->p_queryEnv);
311 }
312
313 /*
314 * standard_ExplainOneQuery -
315 * print out the execution plan for one Query, without calling a hook.
316 */
317 void
318 standard_ExplainOneQuery(Query *query, int cursorOptions,
319 IntoClause *into, ExplainState *es,
320 const char *queryString, ParamListInfo params,
321 QueryEnvironment *queryEnv)
322 {
323 PlannedStmt *plan;
324 instr_time planstart,
325 planduration;
326 BufferUsage bufusage_start,
327 bufusage;
328 MemoryContextCounters mem_counters;
329 MemoryContext planner_ctx = NULL;
330 MemoryContext saved_ctx = NULL;
331
332 if (es->memory)
333 {
334 /*
335 * Create a new memory context to measure planner's memory consumption
336 * accurately. Note that if the planner were to be modified to use a
337 * different memory context type, here we would be changing that to
338 * AllocSet, which might be undesirable. However, we don't have a way
339 * to create a context of the same type as another, so we pray and
340 * hope that this is OK.
341 */
342 planner_ctx = AllocSetContextCreate(CurrentMemoryContext,
343 "explain analyze planner context",
344 ALLOCSET_DEFAULT_SIZES);
345 saved_ctx = MemoryContextSwitchTo(planner_ctx);
346 }
347
348 if (es->buffers)
349 bufusage_start = pgBufferUsage;
350 INSTR_TIME_SET_CURRENT(planstart);
351
352 /* plan the query */
353 plan = pg_plan_query(query, queryString, cursorOptions, params);
354
355 INSTR_TIME_SET_CURRENT(planduration);
356 INSTR_TIME_SUBTRACT(planduration, planstart);
357
358 if (es->memory)
359 {
360 MemoryContextSwitchTo(saved_ctx);
361 MemoryContextMemConsumed(planner_ctx, &mem_counters);
362 }
363
364 /* calc differences of buffer counters. */
365 if (es->buffers)
366 {
367 memset(&bufusage, 0, sizeof(BufferUsage));
368 BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
369 }
370
371 /* run it (if needed) and produce output */
372 ExplainOnePlan(plan, into, es, queryString, params, queryEnv,
373 &planduration, (es->buffers ? &bufusage : NULL),
374 es->memory ? &mem_counters : NULL);
375 }
376
377 /*
378 * ExplainOneUtility -
379 * print out the execution plan for one utility statement
380 * (In general, utility statements don't have plans, but there are some
381 * we treat as special cases)
382 *
383 * "into" is NULL unless we are explaining the contents of a CreateTableAsStmt.
384 *
385 * This is exported because it's called back from prepare.c in the
386 * EXPLAIN EXECUTE case. In that case, we'll be dealing with a statement
387 * that's in the plan cache, so we have to ensure we don't modify it.
388 */
389 void
390 ExplainOneUtility(Node *utilityStmt, IntoClause *into, ExplainState *es,
391 ParseState *pstate, ParamListInfo params)
392 {
393 if (utilityStmt == NULL)
394 return;
395
396 if (IsA(utilityStmt, CreateTableAsStmt))
397 {
398 /*
399 * We have to rewrite the contained SELECT and then pass it back to
400 * ExplainOneQuery. Copy to be safe in the EXPLAIN EXECUTE case.
401 */
402 CreateTableAsStmt *ctas = (CreateTableAsStmt *) utilityStmt;
403 Query *ctas_query;
404 List *rewritten;
405 JumbleState *jstate = NULL;
406
407 /*
408 * Check if the relation exists or not. This is done at this stage to
409 * avoid query planning or execution.
410 */
411 if (CreateTableAsRelExists(ctas))
412 {
413 if (ctas->objtype == OBJECT_TABLE)
414 ExplainDummyGroup("CREATE TABLE AS", NULL, es);
415 else if (ctas->objtype == OBJECT_MATVIEW)
416 ExplainDummyGroup("CREATE MATERIALIZED VIEW", NULL, es);
417 else
418 elog(ERROR, "unexpected object type: %d",
419 (int) ctas->objtype);
420 return;
421 }
422
423 ctas_query = castNode(Query, copyObject(ctas->query));
424 if (IsQueryIdEnabled())
425 jstate = JumbleQuery(ctas_query);
426 if (post_parse_analyze_hook)
427 (*post_parse_analyze_hook) (pstate, ctas_query, jstate);
428 rewritten = QueryRewrite(ctas_query);
429 Assert(list_length(rewritten) == 1);
430 ExplainOneQuery(linitial_node(Query, rewritten),
431 CURSOR_OPT_PARALLEL_OK, ctas->into, es,
432 pstate, params);
433 }
434 else if (IsA(utilityStmt, DeclareCursorStmt))
435 {
436 /*
437 * Likewise for DECLARE CURSOR.
438 *
439 * Notice that if you say EXPLAIN ANALYZE DECLARE CURSOR then we'll
440 * actually run the query. This is different from pre-8.3 behavior
441 * but seems more useful than not running the query. No cursor will
442 * be created, however.
443 */
444 DeclareCursorStmt *dcs = (DeclareCursorStmt *) utilityStmt;
445 Query *dcs_query;
446 List *rewritten;
447 JumbleState *jstate = NULL;
448
449 dcs_query = castNode(Query, copyObject(dcs->query));
450 if (IsQueryIdEnabled())
451 jstate = JumbleQuery(dcs_query);
452 if (post_parse_analyze_hook)
453 (*post_parse_analyze_hook) (pstate, dcs_query, jstate);
454
455 rewritten = QueryRewrite(dcs_query);
456 Assert(list_length(rewritten) == 1);
457 ExplainOneQuery(linitial_node(Query, rewritten),
458 dcs->options, NULL, es,
459 pstate, params);
460 }
461 else if (IsA(utilityStmt, ExecuteStmt))
462 ExplainExecuteQuery((ExecuteStmt *) utilityStmt, into, es,
463 pstate, params);
464 else if (IsA(utilityStmt, NotifyStmt))
465 {
466 if (es->format == EXPLAIN_FORMAT_TEXT)
467 appendStringInfoString(es->str, "NOTIFY\n");
468 else
469 ExplainDummyGroup("Notify", NULL, es);
470 }
471 else
472 {
473 if (es->format == EXPLAIN_FORMAT_TEXT)
474 appendStringInfoString(es->str,
475 "Utility statements have no plan structure\n");
476 else
477 ExplainDummyGroup("Utility Statement", NULL, es);
478 }
479 }
480
481 /*
482 * ExplainOnePlan -
483 * given a planned query, execute it if needed, and then print
484 * EXPLAIN output
485 *
486 * "into" is NULL unless we are explaining the contents of a CreateTableAsStmt,
487 * in which case executing the query should result in creating that table.
488 *
489 * This is exported because it's called back from prepare.c in the
490 * EXPLAIN EXECUTE case, and because an index advisor plugin would need
491 * to call it.
492 */
493 void
494 ExplainOnePlan(PlannedStmt *plannedstmt, IntoClause *into, ExplainState *es,
495 const char *queryString, ParamListInfo params,
496 QueryEnvironment *queryEnv, const instr_time *planduration,
497 const BufferUsage *bufusage,
498 const MemoryContextCounters *mem_counters)
499 {
500 DestReceiver *dest;
501 QueryDesc *queryDesc;
502 instr_time starttime;
503 double totaltime = 0;
504 int eflags;
505 int instrument_option = 0;
506 SerializeMetrics serializeMetrics = {0};
507
508 Assert(plannedstmt->commandType != CMD_UTILITY);
509
510 if (es->analyze && es->timing)
511 instrument_option |= INSTRUMENT_TIMER;
512 else if (es->analyze)
513 instrument_option |= INSTRUMENT_ROWS;
514
515 if (es->buffers)
516 instrument_option |= INSTRUMENT_BUFFERS;
517 if (es->wal)
518 instrument_option |= INSTRUMENT_WAL;
519
520 /*
521 * We always collect timing for the entire statement, even when node-level
522 * timing is off, so we don't look at es->timing here. (We could skip
523 * this if !es->summary, but it's hardly worth the complication.)
524 */
525 INSTR_TIME_SET_CURRENT(starttime);
526
527 /*
528 * Use a snapshot with an updated command ID to ensure this query sees
529 * results of any previously executed queries.
530 */
531 PushCopiedSnapshot(GetActiveSnapshot());
532 UpdateActiveSnapshotCommandId();
533
534 /*
535 * We discard the output if we have no use for it. If we're explaining
536 * CREATE TABLE AS, we'd better use the appropriate tuple receiver, while
537 * the SERIALIZE option requires its own tuple receiver. (If you specify
538 * SERIALIZE while explaining CREATE TABLE AS, you'll see zeroes for the
539 * results, which is appropriate since no data would have gone to the
540 * client.)
541 */
542 if (into)
543 dest = CreateIntoRelDestReceiver(into);
544 else if (es->serialize != EXPLAIN_SERIALIZE_NONE)
545 dest = CreateExplainSerializeDestReceiver(es);
546 else
547 dest = None_Receiver;
548
549 /* Create a QueryDesc for the query */
550 queryDesc = CreateQueryDesc(plannedstmt, queryString,
551 GetActiveSnapshot(), InvalidSnapshot,
552 dest, params, queryEnv, instrument_option);
553
554 /* Select execution options */
555 if (es->analyze)
556 eflags = 0; /* default run-to-completion flags */
557 else
558 eflags = EXEC_FLAG_EXPLAIN_ONLY;
559 if (es->generic)
560 eflags |= EXEC_FLAG_EXPLAIN_GENERIC;
561 if (into)
562 eflags |= GetIntoRelEFlags(into);
563
564 /* call ExecutorStart to prepare the plan for execution */
565 ExecutorStart(queryDesc, eflags);
566
567 /* Execute the plan for statistics if asked for */
568 if (es->analyze)
569 {
570 ScanDirection dir;
571
572 /* EXPLAIN ANALYZE CREATE TABLE AS WITH NO DATA is weird */
573 if (into && into->skipData)
574 dir = NoMovementScanDirection;
575 else
576 dir = ForwardScanDirection;
577
578 /* run the plan */
579 ExecutorRun(queryDesc, dir, 0);
580
581 /* run cleanup too */
582 ExecutorFinish(queryDesc);
583
584 /* We can't run ExecutorEnd 'till we're done printing the stats... */
585 totaltime += elapsed_time(&starttime);
586 }
587
588 /* grab serialization metrics before we destroy the DestReceiver */
589 if (es->serialize != EXPLAIN_SERIALIZE_NONE)
590 serializeMetrics = GetSerializationMetrics(dest);
591
592 /* call the DestReceiver's destroy method even during explain */
593 dest->rDestroy(dest);
594
595 ExplainOpenGroup("Query", NULL, true, es);
596
597 /* Create textual dump of plan tree */
598 ExplainPrintPlan(es, queryDesc);
599
600 /* Show buffer and/or memory usage in planning */
601 if (peek_buffer_usage(es, bufusage) || mem_counters)
602 {
603 ExplainOpenGroup("Planning", "Planning", true, es);
604
605 if (es->format == EXPLAIN_FORMAT_TEXT)
606 {
607 ExplainIndentText(es);
608 appendStringInfoString(es->str, "Planning:\n");
609 es->indent++;
610 }
611
612 if (bufusage)
613 show_buffer_usage(es, bufusage);
614
615 if (mem_counters)
616 show_memory_counters(es, mem_counters);
617
618 if (es->format == EXPLAIN_FORMAT_TEXT)
619 es->indent--;
620
621 ExplainCloseGroup("Planning", "Planning", true, es);
622 }
623
624 if (es->summary && planduration)
625 {
626 double plantime = INSTR_TIME_GET_DOUBLE(*planduration);
627
628 ExplainPropertyFloat("Planning Time", "ms", 1000.0 * plantime, 3, es);
629 }
630
631 /* Print info about runtime of triggers */
632 if (es->analyze)
633 ExplainPrintTriggers(es, queryDesc);
634
635 /*
636 * Print info about JITing. Tied to es->costs because we don't want to
637 * display this in regression tests, as it'd cause output differences
638 * depending on build options. Might want to separate that out from COSTS
639 * at a later stage.
640 */
641 if (es->costs)
642 ExplainPrintJITSummary(es, queryDesc);
643
644 /* Print info about serialization of output */
645 if (es->serialize != EXPLAIN_SERIALIZE_NONE)
646 ExplainPrintSerialize(es, &serializeMetrics);
647
648 /* Allow plugins to print additional information */
649 if (explain_per_plan_hook)
650 (*explain_per_plan_hook) (plannedstmt, into, es, queryString,
651 params, queryEnv);
652
653 /*
654 * Close down the query and free resources. Include time for this in the
655 * total execution time (although it should be pretty minimal).
656 */
657 INSTR_TIME_SET_CURRENT(starttime);
658
659 ExecutorEnd(queryDesc);
660
661 FreeQueryDesc(queryDesc);
662
663 PopActiveSnapshot();
664
665 /* We need a CCI just in case query expanded to multiple plans */
666 if (es->analyze)
667 CommandCounterIncrement();
668
669 totaltime += elapsed_time(&starttime);
670
671 /*
672 * We only report execution time if we actually ran the query (that is,
673 * the user specified ANALYZE), and if summary reporting is enabled (the
674 * user can set SUMMARY OFF to not have the timing information included in
675 * the output). By default, ANALYZE sets SUMMARY to true.
676 */
677 if (es->summary && es->analyze)
678 ExplainPropertyFloat("Execution Time", "ms", 1000.0 * totaltime, 3,
679 es);
680
681 ExplainCloseGroup("Query", NULL, true, es);
682 }
683
684 /*
685 * ExplainPrintSettings -
686 * Print summary of modified settings affecting query planning.
687 */
688 static void
689 ExplainPrintSettings(ExplainState *es)
690 {
691 int num;
692 struct config_generic **gucs;
693
694 /* bail out if information about settings not requested */
695 if (!es->settings)
696 return;
697
698 /* request an array of relevant settings */
699 gucs = get_explain_guc_options(&num);
700
701 if (es->format != EXPLAIN_FORMAT_TEXT)
702 {
703 ExplainOpenGroup("Settings", "Settings", true, es);
704
705 for (int i = 0; i < num; i++)
706 {
707 char *setting;
708 struct config_generic *conf = gucs[i];
709
710 setting = GetConfigOptionByName(conf->name, NULL, true);
711
712 ExplainPropertyText(conf->name, setting, es);
713 }
714
715 ExplainCloseGroup("Settings", "Settings", true, es);
716 }
717 else
718 {
719 StringInfoData str;
720
721 /* In TEXT mode, print nothing if there are no options */
722 if (num <= 0)
723 return;
724
725 initStringInfo(&str);
726
727 for (int i = 0; i < num; i++)
728 {
729 char *setting;
730 struct config_generic *conf = gucs[i];
731
732 if (i > 0)
733 appendStringInfoString(&str, ", ");
734
735 setting = GetConfigOptionByName(conf->name, NULL, true);
736
737 if (setting)
738 appendStringInfo(&str, "%s = '%s'", conf->name, setting);
739 else
740 appendStringInfo(&str, "%s = NULL", conf->name);
741 }
742
743 ExplainPropertyText("Settings", str.data, es);
744 }
745 }
746
747 /*
748 * ExplainPrintPlan -
749 * convert a QueryDesc's plan tree to text and append it to es->str
750 *
751 * The caller should have set up the options fields of *es, as well as
752 * initializing the output buffer es->str. Also, output formatting state
753 * such as the indent level is assumed valid. Plan-tree-specific fields
754 * in *es are initialized here.
755 *
756 * NB: will not work on utility statements
757 */
758 void
759 ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
760 {
761 Bitmapset *rels_used = NULL;
762 PlanState *ps;
763 ListCell *lc;
764
765 /* Set up ExplainState fields associated with this plan tree */
766 Assert(queryDesc->plannedstmt != NULL);
767 es->pstmt = queryDesc->plannedstmt;
768 es->rtable = queryDesc->plannedstmt->rtable;
769 ExplainPreScanNode(queryDesc->planstate, &rels_used);
770 es->rtable_names = select_rtable_names_for_explain(es->rtable, rels_used);
771 es->deparse_cxt = deparse_context_for_plan_tree(queryDesc->plannedstmt,
772 es->rtable_names);
773 es->printed_subplans = NULL;
774 es->rtable_size = list_length(es->rtable);
775 foreach(lc, es->rtable)
776 {
777 RangeTblEntry *rte = lfirst_node(RangeTblEntry, lc);
778
779 if (rte->rtekind == RTE_GROUP)
780 {
781 es->rtable_size--;
782 break;
783 }
784 }
785
786 /*
787 * Sometimes we mark a Gather node as "invisible", which means that it's
788 * not to be displayed in EXPLAIN output. The purpose of this is to allow
789 * running regression tests with debug_parallel_query=regress to get the
790 * same results as running the same tests with debug_parallel_query=off.
791 * Such marking is currently only supported on a Gather at the top of the
792 * plan. We skip that node, and we must also hide per-worker detail data
793 * further down in the plan tree.
794 */
795 ps = queryDesc->planstate;
796 if (IsA(ps, GatherState) && ((Gather *) ps->plan)->invisible)
797 {
798 ps = outerPlanState(ps);
799 es->hide_workers = true;
800 }
801 ExplainNode(ps, NIL, NULL, NULL, es);
802
803 /*
804 * If requested, include information about GUC parameters with values that
805 * don't match the built-in defaults.
806 */
807 ExplainPrintSettings(es);
808
809 /*
810 * COMPUTE_QUERY_ID_REGRESS means COMPUTE_QUERY_ID_AUTO, but we don't show
811 * the queryid in any of the EXPLAIN plans to keep stable the results
812 * generated by regression test suites.
813 */
814 if (es->verbose && queryDesc->plannedstmt->queryId != INT64CONST(0) &&
815 compute_query_id != COMPUTE_QUERY_ID_REGRESS)
816 {
817 ExplainPropertyInteger("Query Identifier", NULL,
818 queryDesc->plannedstmt->queryId, es);
819 }
820 }
821
822 /*
823 * ExplainPrintTriggers -
824 * convert a QueryDesc's trigger statistics to text and append it to
825 * es->str
826 *
827 * The caller should have set up the options fields of *es, as well as
828 * initializing the output buffer es->str. Other fields in *es are
829 * initialized here.
830 */
831 void
832 ExplainPrintTriggers(ExplainState *es, QueryDesc *queryDesc)
833 {
834 ResultRelInfo *rInfo;
835 bool show_relname;
836 List *resultrels;
837 List *routerels;
838 List *targrels;
839 ListCell *l;
840
841 resultrels = queryDesc->estate->es_opened_result_relations;
842 routerels = queryDesc->estate->es_tuple_routing_result_relations;
843 targrels = queryDesc->estate->es_trig_target_relations;
844
845 ExplainOpenGroup("Triggers", "Triggers", false, es);
846
847 show_relname = (list_length(resultrels) > 1 ||
848 routerels != NIL || targrels != NIL);
849 foreach(l, resultrels)
850 {
851 rInfo = (ResultRelInfo *) lfirst(l);
852 report_triggers(rInfo, show_relname, es);
853 }
854
855 foreach(l, routerels)
856 {
857 rInfo = (ResultRelInfo *) lfirst(l);
858 report_triggers(rInfo, show_relname, es);
859 }
860
861 foreach(l, targrels)
862 {
863 rInfo = (ResultRelInfo *) lfirst(l);
864 report_triggers(rInfo, show_relname, es);
865 }
866
867 ExplainCloseGroup("Triggers", "Triggers", false, es);
868 }
869
870 /*
871 * ExplainPrintJITSummary -
872 * Print summarized JIT instrumentation from leader and workers
873 */
874 void
875 ExplainPrintJITSummary(ExplainState *es, QueryDesc *queryDesc)
876 {
877 JitInstrumentation ji = {0};
878
879 if (!(queryDesc->estate->es_jit_flags & PGJIT_PERFORM))
880 return;
881
882 /*
883 * Work with a copy instead of modifying the leader state, since this
884 * function may be called twice
885 */
886 if (queryDesc->estate->es_jit)
887 InstrJitAgg(&ji, &queryDesc->estate->es_jit->instr);
888
889 /* If this process has done JIT in parallel workers, merge stats */
890 if (queryDesc->estate->es_jit_worker_instr)
891 InstrJitAgg(&ji, queryDesc->estate->es_jit_worker_instr);
892
893 ExplainPrintJIT(es, queryDesc->estate->es_jit_flags, &ji);
894 }
895
896 /*
897 * ExplainPrintJIT -
898 * Append information about JITing to es->str.
899 */
900 static void
901 ExplainPrintJIT(ExplainState *es, int jit_flags, JitInstrumentation *ji)
902 {
903 instr_time total_time;
904
905 /* don't print information if no JITing happened */
906 if (!ji || ji->created_functions == 0)
907 return;
908
909 /* calculate total time */
910 INSTR_TIME_SET_ZERO(total_time);
911 /* don't add deform_counter, it's included in generation_counter */
912 INSTR_TIME_ADD(total_time, ji->generation_counter);
913 INSTR_TIME_ADD(total_time, ji->inlining_counter);
914 INSTR_TIME_ADD(total_time, ji->optimization_counter);
915 INSTR_TIME_ADD(total_time, ji->emission_counter);
916
917 ExplainOpenGroup("JIT", "JIT", true, es);
918
919 /* for higher density, open code the text output format */
920 if (es->format == EXPLAIN_FORMAT_TEXT)
921 {
922 ExplainIndentText(es);
923 appendStringInfoString(es->str, "JIT:\n");
924 es->indent++;
925
926 ExplainPropertyInteger("Functions", NULL, ji->created_functions, es);
927
928 ExplainIndentText(es);
929 appendStringInfo(es->str, "Options: %s %s, %s %s, %s %s, %s %s\n",
930 "Inlining", jit_flags & PGJIT_INLINE ? "true" : "false",
931 "Optimization", jit_flags & PGJIT_OPT3 ? "true" : "false",
932 "Expressions", jit_flags & PGJIT_EXPR ? "true" : "false",
933 "Deforming", jit_flags & PGJIT_DEFORM ? "true" : "false");
934
935 if (es->analyze && es->timing)
936 {
937 ExplainIndentText(es);
938 appendStringInfo(es->str,
939 "Timing: %s %.3f ms (%s %.3f ms), %s %.3f ms, %s %.3f ms, %s %.3f ms, %s %.3f ms\n",
940 "Generation", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->generation_counter),
941 "Deform", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->deform_counter),
942 "Inlining", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->inlining_counter),
943 "Optimization", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->optimization_counter),
944 "Emission", 1000.0 * INSTR_TIME_GET_DOUBLE(ji->emission_counter),
945 "Total", 1000.0 * INSTR_TIME_GET_DOUBLE(total_time));
946 }
947
948 es->indent--;
949 }
950 else
951 {
952 ExplainPropertyInteger("Functions", NULL, ji->created_functions, es);
953
954 ExplainOpenGroup("Options", "Options", true, es);
955 ExplainPropertyBool("Inlining", jit_flags & PGJIT_INLINE, es);
956 ExplainPropertyBool("Optimization", jit_flags & PGJIT_OPT3, es);
957 ExplainPropertyBool("Expressions", jit_flags & PGJIT_EXPR, es);
958 ExplainPropertyBool("Deforming", jit_flags & PGJIT_DEFORM, es);
959 ExplainCloseGroup("Options", "Options", true, es);
960
961 if (es->analyze && es->timing)
962 {
963 ExplainOpenGroup("Timing", "Timing", true, es);
964
965 ExplainOpenGroup("Generation", "Generation", true, es);
966 ExplainPropertyFloat("Deform", "ms",
967 1000.0 * INSTR_TIME_GET_DOUBLE(ji->deform_counter),
968 3, es);
969 ExplainPropertyFloat("Total", "ms",
970 1000.0 * INSTR_TIME_GET_DOUBLE(ji->generation_counter),
971 3, es);
972 ExplainCloseGroup("Generation", "Generation", true, es);
973
974 ExplainPropertyFloat("Inlining", "ms",
975 1000.0 * INSTR_TIME_GET_DOUBLE(ji->inlining_counter),
976 3, es);
977 ExplainPropertyFloat("Optimization", "ms",
978 1000.0 * INSTR_TIME_GET_DOUBLE(ji->optimization_counter),
979 3, es);
980 ExplainPropertyFloat("Emission", "ms",
981 1000.0 * INSTR_TIME_GET_DOUBLE(ji->emission_counter),
982 3, es);
983 ExplainPropertyFloat("Total", "ms",
984 1000.0 * INSTR_TIME_GET_DOUBLE(total_time),
985 3, es);
986
987 ExplainCloseGroup("Timing", "Timing", true, es);
988 }
989 }
990
991 ExplainCloseGroup("JIT", "JIT", true, es);
992 }
993
994 /*
995 * ExplainPrintSerialize -
996 * Append information about query output volume to es->str.
997 */
998 static void
999 ExplainPrintSerialize(ExplainState *es, SerializeMetrics *metrics)
1000 {
1001 const char *format;
1002
1003 /* We shouldn't get called for EXPLAIN_SERIALIZE_NONE */
1004 if (es->serialize == EXPLAIN_SERIALIZE_TEXT)
1005 format = "text";
1006 else
1007 {
1008 Assert(es->serialize == EXPLAIN_SERIALIZE_BINARY);
1009 format = "binary";
1010 }
1011
1012 ExplainOpenGroup("Serialization", "Serialization", true, es);
1013
1014 if (es->format == EXPLAIN_FORMAT_TEXT)
1015 {
1016 ExplainIndentText(es);
1017 if (es->timing)
1018 appendStringInfo(es->str, "Serialization: time=%.3f ms output=" UINT64_FORMAT "kB format=%s\n",
1019 1000.0 * INSTR_TIME_GET_DOUBLE(metrics->timeSpent),
1020 BYTES_TO_KILOBYTES(metrics->bytesSent),
1021 format);
1022 else
1023 appendStringInfo(es->str, "Serialization: output=" UINT64_FORMAT "kB format=%s\n",
1024 BYTES_TO_KILOBYTES(metrics->bytesSent),
1025 format);
1026
1027 if (es->buffers && peek_buffer_usage(es, &metrics->bufferUsage))
1028 {
1029 es->indent++;
1030 show_buffer_usage(es, &metrics->bufferUsage);
1031 es->indent--;
1032 }
1033 }
1034 else
1035 {
1036 if (es->timing)
1037 ExplainPropertyFloat("Time", "ms",
1038 1000.0 * INSTR_TIME_GET_DOUBLE(metrics->timeSpent),
1039 3, es);
1040 ExplainPropertyUInteger("Output Volume", "kB",
1041 BYTES_TO_KILOBYTES(metrics->bytesSent), es);
1042 ExplainPropertyText("Format", format, es);
1043 if (es->buffers)
1044 show_buffer_usage(es, &metrics->bufferUsage);
1045 }
1046
1047 ExplainCloseGroup("Serialization", "Serialization", true, es);
1048 }
1049
1050 /*
1051 * ExplainQueryText -
1052 * add a "Query Text" node that contains the actual text of the query
1053 *
1054 * The caller should have set up the options fields of *es, as well as
1055 * initializing the output buffer es->str.
1056 *
1057 */
1058 void
1059 ExplainQueryText(ExplainState *es, QueryDesc *queryDesc)
1060 {
1061 if (queryDesc->sourceText)
1062 ExplainPropertyText("Query Text", queryDesc->sourceText, es);
1063 }
1064
1065 /*
1066 * ExplainQueryParameters -
1067 * add a "Query Parameters" node that describes the parameters of the query
1068 *
1069 * The caller should have set up the options fields of *es, as well as
1070 * initializing the output buffer es->str.
1071 *
1072 */
1073 void
1074 ExplainQueryParameters(ExplainState *es, ParamListInfo params, int maxlen)
1075 {
1076 char *str;
1077
1078 /* This check is consistent with errdetail_params() */
1079 if (params == NULL || params->numParams <= 0 || maxlen == 0)
1080 return;
1081
1082 str = BuildParamLogString(params, NULL, maxlen);
1083 if (str && str[0] != '\0')
1084 ExplainPropertyText("Query Parameters", str, es);
1085 }
1086
1087 /*
1088 * report_triggers -
1089 * report execution stats for a single relation's triggers
1090 */
1091 static void
1092 report_triggers(ResultRelInfo *rInfo, bool show_relname, ExplainState *es)
1093 {
1094 int nt;
1095
1096 if (!rInfo->ri_TrigDesc || !rInfo->ri_TrigInstrument)
1097 return;
1098 for (nt = 0; nt < rInfo->ri_TrigDesc->numtriggers; nt++)
1099 {
1100 Trigger *trig = rInfo->ri_TrigDesc->triggers + nt;
1101 Instrumentation *instr = rInfo->ri_TrigInstrument + nt;
1102 char *relname;
1103 char *conname = NULL;
1104
1105 /* Must clean up instrumentation state */
1106 InstrEndLoop(instr);
1107
1108 /*
1109 * We ignore triggers that were never invoked; they likely aren't
1110 * relevant to the current query type.
1111 */
1112 if (instr->ntuples == 0)
1113 continue;
1114
1115 ExplainOpenGroup("Trigger", NULL, true, es);
1116
1117 relname = RelationGetRelationName(rInfo->ri_RelationDesc);
1118 if (OidIsValid(trig->tgconstraint))
1119 conname = get_constraint_name(trig->tgconstraint);
1120
1121 /*
1122 * In text format, we avoid printing both the trigger name and the
1123 * constraint name unless VERBOSE is specified. In non-text formats
1124 * we just print everything.
1125 */
1126 if (es->format == EXPLAIN_FORMAT_TEXT)
1127 {
1128 if (es->verbose || conname == NULL)
1129 appendStringInfo(es->str, "Trigger %s", trig->tgname);
1130 else
1131 appendStringInfoString(es->str, "Trigger");
1132 if (conname)
1133 appendStringInfo(es->str, " for constraint %s", conname);
1134 if (show_relname)
1135 appendStringInfo(es->str, " on %s", relname);
1136 if (es->timing)
1137 appendStringInfo(es->str, ": time=%.3f calls=%.0f\n",
1138 1000.0 * instr->total, instr->ntuples);
1139 else
1140 appendStringInfo(es->str, ": calls=%.0f\n", instr->ntuples);
1141 }
1142 else
1143 {
1144 ExplainPropertyText("Trigger Name", trig->tgname, es);
1145 if (conname)
1146 ExplainPropertyText("Constraint Name", conname, es);
1147 ExplainPropertyText("Relation", relname, es);
1148 if (es->timing)
1149 ExplainPropertyFloat("Time", "ms", 1000.0 * instr->total, 3,
1150 es);
1151 ExplainPropertyFloat("Calls", NULL, instr->ntuples, 0, es);
1152 }
1153
1154 if (conname)
1155 pfree(conname);
1156
1157 ExplainCloseGroup("Trigger", NULL, true, es);
1158 }
1159 }
1160
1161 /* Compute elapsed time in seconds since given timestamp */
1162 static double
1163 elapsed_time(instr_time *starttime)
1164 {
1165 instr_time endtime;
1166
1167 INSTR_TIME_SET_CURRENT(endtime);
1168 INSTR_TIME_SUBTRACT(endtime, *starttime);
1169 return INSTR_TIME_GET_DOUBLE(endtime);
1170 }
1171
1172 /*
1173 * ExplainPreScanNode -
1174 * Prescan the planstate tree to identify which RTEs are referenced
1175 *
1176 * Adds the relid of each referenced RTE to *rels_used. The result controls
1177 * which RTEs are assigned aliases by select_rtable_names_for_explain.
1178 * This ensures that we don't confusingly assign un-suffixed aliases to RTEs
1179 * that never appear in the EXPLAIN output (such as inheritance parents).
1180 */
1181 static bool
1182 ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used)
1183 {
1184 Plan *plan = planstate->plan;
1185
1186 switch (nodeTag(plan))
1187 {
1188 case T_SeqScan:
1189 case T_SampleScan:
1190 case T_IndexScan:
1191 case T_IndexOnlyScan:
1192 case T_BitmapHeapScan:
1193 case T_TidScan:
1194 case T_TidRangeScan:
1195 case T_SubqueryScan:
1196 case T_FunctionScan:
1197 case T_TableFuncScan:
1198 case T_ValuesScan:
1199 case T_CteScan:
1200 case T_NamedTuplestoreScan:
1201 case T_WorkTableScan:
1202 *rels_used = bms_add_member(*rels_used,
1203 ((Scan *) plan)->scanrelid);
1204 break;
1205 case T_ForeignScan:
1206 *rels_used = bms_add_members(*rels_used,
1207 ((ForeignScan *) plan)->fs_base_relids);
1208 break;
1209 case T_CustomScan:
1210 *rels_used = bms_add_members(*rels_used,
1211 ((CustomScan *) plan)->custom_relids);
1212 break;
1213 case T_ModifyTable:
1214 *rels_used = bms_add_member(*rels_used,
1215 ((ModifyTable *) plan)->nominalRelation);
1216 if (((ModifyTable *) plan)->exclRelRTI)
1217 *rels_used = bms_add_member(*rels_used,
1218 ((ModifyTable *) plan)->exclRelRTI);
1219 /* Ensure Vars used in RETURNING will have refnames */
1220 if (plan->targetlist)
1221 *rels_used = bms_add_member(*rels_used,
1222 linitial_int(((ModifyTable *) plan)->resultRelations));
1223 break;
1224 case T_Append:
1225 *rels_used = bms_add_members(*rels_used,
1226 ((Append *) plan)->apprelids);
1227 break;
1228 case T_MergeAppend:
1229 *rels_used = bms_add_members(*rels_used,
1230 ((MergeAppend *) plan)->apprelids);
1231 break;
1232 default:
1233 break;
1234 }
1235
1236 return planstate_tree_walker(planstate, ExplainPreScanNode, rels_used);
1237 }
1238
1239 /*
1240 * plan_is_disabled
1241 * Checks if the given plan node type was disabled during query planning.
1242 * This is evident by the disabled_nodes field being higher than the sum of
1243 * the disabled_nodes field from the plan's children.
1244 */
1245 static bool
1246 plan_is_disabled(Plan *plan)
1247 {
1248 int child_disabled_nodes;
1249
1250 /* The node is certainly not disabled if this is zero */
1251 if (plan->disabled_nodes == 0)
1252 return false;
1253
1254 child_disabled_nodes = 0;
1255
1256 /*
1257 * Handle special nodes first. Children of BitmapOrs and BitmapAnds can't
1258 * be disabled, so no need to handle those specifically.
1259 */
1260 if (IsA(plan, Append))
1261 {
1262 ListCell *lc;
1263 Append *aplan = (Append *) plan;
1264
1265 /*
1266 * Sum the Append childrens' disabled_nodes. This purposefully
1267 * includes any run-time pruned children. Ignoring those could give
1268 * us the incorrect number of disabled nodes.
1269 */
1270 foreach(lc, aplan->appendplans)
1271 {
1272 Plan *subplan = lfirst(lc);
1273
1274 child_disabled_nodes += subplan->disabled_nodes;
1275 }
1276 }
1277 else if (IsA(plan, MergeAppend))
1278 {
1279 ListCell *lc;
1280 MergeAppend *maplan = (MergeAppend *) plan;
1281
1282 /*
1283 * Sum the MergeAppend childrens' disabled_nodes. This purposefully
1284 * includes any run-time pruned children. Ignoring those could give
1285 * us the incorrect number of disabled nodes.
1286 */
1287 foreach(lc, maplan->mergeplans)
1288 {
1289 Plan *subplan = lfirst(lc);
1290
1291 child_disabled_nodes += subplan->disabled_nodes;
1292 }
1293 }
1294 else if (IsA(plan, SubqueryScan))
1295 child_disabled_nodes += ((SubqueryScan *) plan)->subplan->disabled_nodes;
1296 else if (IsA(plan, CustomScan))
1297 {
1298 ListCell *lc;
1299 CustomScan *cplan = (CustomScan *) plan;
1300
1301 foreach(lc, cplan->custom_plans)
1302 {
1303 Plan *subplan = lfirst(lc);
1304
1305 child_disabled_nodes += subplan->disabled_nodes;
1306 }
1307 }
1308 else
1309 {
1310 /*
1311 * Else, sum up disabled_nodes from the plan's inner and outer side.
1312 */
1313 if (outerPlan(plan))
1314 child_disabled_nodes += outerPlan(plan)->disabled_nodes;
1315 if (innerPlan(plan))
1316 child_disabled_nodes += innerPlan(plan)->disabled_nodes;
1317 }
1318
1319 /*
1320 * It's disabled if the plan's disabled_nodes is higher than the sum of
1321 * its child's plan disabled_nodes.
1322 */
1323 if (plan->disabled_nodes > child_disabled_nodes)
1324 return true;
1325
1326 return false;
1327 }
1328
1329 /*
1330 * ExplainNode -
1331 * Appends a description of a plan tree to es->str
1332 *
1333 * planstate points to the executor state node for the current plan node.
1334 * We need to work from a PlanState node, not just a Plan node, in order to
1335 * get at the instrumentation data (if any) as well as the list of subplans.
1336 *
1337 * ancestors is a list of parent Plan and SubPlan nodes, most-closely-nested
1338 * first. These are needed in order to interpret PARAM_EXEC Params.
1339 *
1340 * relationship describes the relationship of this plan node to its parent
1341 * (eg, "Outer", "Inner"); it can be null at top level. plan_name is an
1342 * optional name to be attached to the node.
1343 *
1344 * In text format, es->indent is controlled in this function since we only
1345 * want it to change at plan-node boundaries (but a few subroutines will
1346 * transiently increment it). In non-text formats, es->indent corresponds
1347 * to the nesting depth of logical output groups, and therefore is controlled
1348 * by ExplainOpenGroup/ExplainCloseGroup.
1349 */
1350 static void
1351 ExplainNode(PlanState *planstate, List *ancestors,
1352 const char *relationship, const char *plan_name,
1353 ExplainState *es)
1354 {
1355 Plan *plan = planstate->plan;
1356 const char *pname; /* node type name for text output */
1357 const char *sname; /* node type name for non-text output */
1358 const char *strategy = NULL;
1359 const char *partialmode = NULL;
1360 const char *operation = NULL;
1361 const char *custom_name = NULL;
1362 ExplainWorkersState *save_workers_state = es->workers_state;
1363 int save_indent = es->indent;
1364 bool haschildren;
1365 bool isdisabled;
1366
1367 /*
1368 * Prepare per-worker output buffers, if needed. We'll append the data in
1369 * these to the main output string further down.
1370 */
1371 if (planstate->worker_instrument && es->analyze && !es->hide_workers)
1372 es->workers_state = ExplainCreateWorkersState(planstate->worker_instrument->num_workers);
1373 else
1374 es->workers_state = NULL;
1375
1376 /* Identify plan node type, and print generic details */
1377 switch (nodeTag(plan))
1378 {
1379 case T_Result:
1380 pname = sname = "Result";
1381 break;
1382 case T_ProjectSet:
1383 pname = sname = "ProjectSet";
1384 break;
1385 case T_ModifyTable:
1386 sname = "ModifyTable";
1387 switch (((ModifyTable *) plan)->operation)
1388 {
1389 case CMD_INSERT:
1390 pname = operation = "Insert";
1391 break;
1392 case CMD_UPDATE:
1393 pname = operation = "Update";
1394 break;
1395 case CMD_DELETE:
1396 pname = operation = "Delete";
1397 break;
1398 case CMD_MERGE:
1399 pname = operation = "Merge";
1400 break;
1401 default:
1402 pname = "???";
1403 break;
1404 }
1405 break;
1406 case T_Append:
1407 pname = sname = "Append";
1408 break;
1409 case T_MergeAppend:
1410 pname = sname = "Merge Append";
1411 break;
1412 case T_RecursiveUnion:
1413 pname = sname = "Recursive Union";
1414 break;
1415 case T_BitmapAnd:
1416 pname = sname = "BitmapAnd";
1417 break;
1418 case T_BitmapOr:
1419 pname = sname = "BitmapOr";
1420 break;
1421 case T_NestLoop:
1422 pname = sname = "Nested Loop";
1423 break;
1424 case T_MergeJoin:
1425 pname = "Merge"; /* "Join" gets added by jointype switch */
1426 sname = "Merge Join";
1427 break;
1428 case T_HashJoin:
1429 pname = "Hash"; /* "Join" gets added by jointype switch */
1430 sname = "Hash Join";
1431 break;
1432 case T_SeqScan:
1433 pname = sname = "Seq Scan";
1434 break;
1435 case T_SampleScan:
1436 pname = sname = "Sample Scan";
1437 break;
1438 case T_Gather:
1439 pname = sname = "Gather";
1440 break;
1441 case T_GatherMerge:
1442 pname = sname = "Gather Merge";
1443 break;
1444 case T_IndexScan:
1445 pname = sname = "Index Scan";
1446 break;
1447 case T_IndexOnlyScan:
1448 pname = sname = "Index Only Scan";
1449 break;
1450 case T_BitmapIndexScan:
1451 pname = sname = "Bitmap Index Scan";
1452 break;
1453 case T_BitmapHeapScan:
1454 pname = sname = "Bitmap Heap Scan";
1455 break;
1456 case T_TidScan:
1457 pname = sname = "Tid Scan";
1458 break;
1459 case T_TidRangeScan:
1460 pname = sname = "Tid Range Scan";
1461 break;
1462 case T_SubqueryScan:
1463 pname = sname = "Subquery Scan";
1464 break;
1465 case T_FunctionScan:
1466 pname = sname = "Function Scan";
1467 break;
1468 case T_TableFuncScan:
1469 pname = sname = "Table Function Scan";
1470 break;
1471 case T_ValuesScan:
1472 pname = sname = "Values Scan";
1473 break;
1474 case T_CteScan:
1475 pname = sname = "CTE Scan";
1476 break;
1477 case T_NamedTuplestoreScan:
1478 pname = sname = "Named Tuplestore Scan";
1479 break;
1480 case T_WorkTableScan:
1481 pname = sname = "WorkTable Scan";
1482 break;
1483 case T_ForeignScan:
1484 sname = "Foreign Scan";
1485 switch (((ForeignScan *) plan)->operation)
1486 {
1487 case CMD_SELECT:
1488 pname = "Foreign Scan";
1489 operation = "Select";
1490 break;
1491 case CMD_INSERT:
1492 pname = "Foreign Insert";
1493 operation = "Insert";
1494 break;
1495 case CMD_UPDATE:
1496 pname = "Foreign Update";
1497 operation = "Update";
1498 break;
1499 case CMD_DELETE:
1500 pname = "Foreign Delete";
1501 operation = "Delete";
1502 break;
1503 default:
1504 pname = "???";
1505 break;
1506 }
1507 break;
1508 case T_CustomScan:
1509 sname = "Custom Scan";
1510 custom_name = ((CustomScan *) plan)->methods->CustomName;
1511 if (custom_name)
1512 pname = psprintf("Custom Scan (%s)", custom_name);
1513 else
1514 pname = sname;
1515 break;
1516 case T_Material:
1517 pname = sname = "Materialize";
1518 break;
1519 case T_Memoize:
1520 pname = sname = "Memoize";
1521 break;
1522 case T_Sort:
1523 pname = sname = "Sort";
1524 break;
1525 case T_IncrementalSort:
1526 pname = sname = "Incremental Sort";
1527 break;
1528 case T_Group:
1529 pname = sname = "Group";
1530 break;
1531 case T_Agg:
1532 {
1533 Agg *agg = (Agg *) plan;
1534
1535 sname = "Aggregate";
1536 switch (agg->aggstrategy)
1537 {
1538 case AGG_PLAIN:
1539 pname = "Aggregate";
1540 strategy = "Plain";
1541 break;
1542 case AGG_SORTED:
1543 pname = "GroupAggregate";
1544 strategy = "Sorted";
1545 break;
1546 case AGG_HASHED:
1547 pname = "HashAggregate";
1548 strategy = "Hashed";
1549 break;
1550 case AGG_MIXED:
1551 pname = "MixedAggregate";
1552 strategy = "Mixed";
1553 break;
1554 default:
1555 pname = "Aggregate ???";
1556 strategy = "???";
1557 break;
1558 }
1559
1560 if (DO_AGGSPLIT_SKIPFINAL(agg->aggsplit))
1561 {
1562 partialmode = "Partial";
1563 pname = psprintf("%s %s", partialmode, pname);
1564 }
1565 else if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
1566 {
1567 partialmode = "Finalize";
1568 pname = psprintf("%s %s", partialmode, pname);
1569 }
1570 else
1571 partialmode = "Simple";
1572 }
1573 break;
1574 case T_WindowAgg:
1575 pname = sname = "WindowAgg";
1576 break;
1577 case T_Unique:
1578 pname = sname = "Unique";
1579 break;
1580 case T_SetOp:
1581 sname = "SetOp";
1582 switch (((SetOp *) plan)->strategy)
1583 {
1584 case SETOP_SORTED:
1585 pname = "SetOp";
1586 strategy = "Sorted";
1587 break;
1588 case SETOP_HASHED:
1589 pname = "HashSetOp";
1590 strategy = "Hashed";
1591 break;
1592 default:
1593 pname = "SetOp ???";
1594 strategy = "???";
1595 break;
1596 }
1597 break;
1598 case T_LockRows:
1599 pname = sname = "LockRows";
1600 break;
1601 case T_Limit:
1602 pname = sname = "Limit";
1603 break;
1604 case T_Hash:
1605 pname = sname = "Hash";
1606 break;
1607 default:
1608 pname = sname = "???";
1609 break;
1610 }
1611
1612 ExplainOpenGroup("Plan",
1613 relationship ? NULL : "Plan",
1614 true, es);
1615
1616 if (es->format == EXPLAIN_FORMAT_TEXT)
1617 {
1618 if (plan_name)
1619 {
1620 ExplainIndentText(es);
1621 appendStringInfo(es->str, "%s\n", plan_name);
1622 es->indent++;
1623 }
1624 if (es->indent)
1625 {
1626 ExplainIndentText(es);
1627 appendStringInfoString(es->str, "-> ");
1628 es->indent += 2;
1629 }
1630 if (plan->parallel_aware)
1631 appendStringInfoString(es->str, "Parallel ");
1632 if (plan->async_capable)
1633 appendStringInfoString(es->str, "Async ");
1634 appendStringInfoString(es->str, pname);
1635 es->indent++;
1636 }
1637 else
1638 {
1639 ExplainPropertyText("Node Type", sname, es);
1640 if (strategy)
1641 ExplainPropertyText("Strategy", strategy, es);
1642 if (partialmode)
1643 ExplainPropertyText("Partial Mode", partialmode, es);
1644 if (operation)
1645 ExplainPropertyText("Operation", operation, es);
1646 if (relationship)
1647 ExplainPropertyText("Parent Relationship", relationship, es);
1648 if (plan_name)
1649 ExplainPropertyText("Subplan Name", plan_name, es);
1650 if (custom_name)
1651 ExplainPropertyText("Custom Plan Provider", custom_name, es);
1652 ExplainPropertyBool("Parallel Aware", plan->parallel_aware, es);
1653 ExplainPropertyBool("Async Capable", plan->async_capable, es);
1654 }
1655
1656 switch (nodeTag(plan))
1657 {
1658 case T_SeqScan:
1659 case T_SampleScan:
1660 case T_BitmapHeapScan:
1661 case T_TidScan:
1662 case T_TidRangeScan:
1663 case T_SubqueryScan:
1664 case T_FunctionScan:
1665 case T_TableFuncScan:
1666 case T_ValuesScan:
1667 case T_CteScan:
1668 case T_WorkTableScan:
1669 ExplainScanTarget((Scan *) plan, es);
1670 break;
1671 case T_ForeignScan:
1672 case T_CustomScan:
1673 if (((Scan *) plan)->scanrelid > 0)
1674 ExplainScanTarget((Scan *) plan, es);
1675 break;
1676 case T_IndexScan:
1677 {
1678 IndexScan *indexscan = (IndexScan *) plan;
1679
1680 ExplainIndexScanDetails(indexscan->indexid,
1681 indexscan->indexorderdir,
1682 es);
1683 ExplainScanTarget((Scan *) indexscan, es);
1684 }
1685 break;
1686 case T_IndexOnlyScan:
1687 {
1688 IndexOnlyScan *indexonlyscan = (IndexOnlyScan *) plan;
1689
1690 ExplainIndexScanDetails(indexonlyscan->indexid,
1691 indexonlyscan->indexorderdir,
1692 es);
1693 ExplainScanTarget((Scan *) indexonlyscan, es);
1694 }
1695 break;
1696 case T_BitmapIndexScan:
1697 {
1698 BitmapIndexScan *bitmapindexscan = (BitmapIndexScan *) plan;
1699 const char *indexname =
1700 explain_get_index_name(bitmapindexscan->indexid);
1701
1702 if (es->format == EXPLAIN_FORMAT_TEXT)
1703 appendStringInfo(es->str, " on %s",
1704 quote_identifier(indexname));
1705 else
1706 ExplainPropertyText("Index Name", indexname, es);
1707 }
1708 break;
1709 case T_ModifyTable:
1710 ExplainModifyTarget((ModifyTable *) plan, es);
1711 break;
1712 case T_NestLoop:
1713 case T_MergeJoin:
1714 case T_HashJoin:
1715 {
1716 const char *jointype;
1717
1718 switch (((Join *) plan)->jointype)
1719 {
1720 case JOIN_INNER:
1721 jointype = "Inner";
1722 break;
1723 case JOIN_LEFT:
1724 jointype = "Left";
1725 break;
1726 case JOIN_FULL:
1727 jointype = "Full";
1728 break;
1729 case JOIN_RIGHT:
1730 jointype = "Right";
1731 break;
1732 case JOIN_SEMI:
1733 jointype = "Semi";
1734 break;
1735 case JOIN_ANTI:
1736 jointype = "Anti";
1737 break;
1738 case JOIN_RIGHT_SEMI:
1739 jointype = "Right Semi";
1740 break;
1741 case JOIN_RIGHT_ANTI:
1742 jointype = "Right Anti";
1743 break;
1744 default:
1745 jointype = "???";
1746 break;
1747 }
1748 if (es->format == EXPLAIN_FORMAT_TEXT)
1749 {
1750 /*
1751 * For historical reasons, the join type is interpolated
1752 * into the node type name...
1753 */
1754 if (((Join *) plan)->jointype != JOIN_INNER)
1755 appendStringInfo(es->str, " %s Join", jointype);
1756 else if (!IsA(plan, NestLoop))
1757 appendStringInfoString(es->str, " Join");
1758 }
1759 else
1760 ExplainPropertyText("Join Type", jointype, es);
1761 }
1762 break;
1763 case T_SetOp:
1764 {
1765 const char *setopcmd;
1766
1767 switch (((SetOp *) plan)->cmd)
1768 {
1769 case SETOPCMD_INTERSECT:
1770 setopcmd = "Intersect";
1771 break;
1772 case SETOPCMD_INTERSECT_ALL:
1773 setopcmd = "Intersect All";
1774 break;
1775 case SETOPCMD_EXCEPT:
1776 setopcmd = "Except";
1777 break;
1778 case SETOPCMD_EXCEPT_ALL:
1779 setopcmd = "Except All";
1780 break;
1781 default:
1782 setopcmd = "???";
1783 break;
1784 }
1785 if (es->format == EXPLAIN_FORMAT_TEXT)
1786 appendStringInfo(es->str, " %s", setopcmd);
1787 else
1788 ExplainPropertyText("Command", setopcmd, es);
1789 }
1790 break;
1791 default:
1792 break;
1793 }
1794
1795 if (es->costs)
1796 {
1797 if (es->format == EXPLAIN_FORMAT_TEXT)
1798 {
1799 appendStringInfo(es->str, " (cost=%.2f..%.2f rows=%.0f width=%d)",
1800 plan->startup_cost, plan->total_cost,
1801 plan->plan_rows, plan->plan_width);
1802 }
1803 else
1804 {
1805 ExplainPropertyFloat("Startup Cost", NULL, plan->startup_cost,
1806 2, es);
1807 ExplainPropertyFloat("Total Cost", NULL, plan->total_cost,
1808 2, es);
1809 ExplainPropertyFloat("Plan Rows", NULL, plan->plan_rows,
1810 0, es);
1811 ExplainPropertyInteger("Plan Width", NULL, plan->plan_width,
1812 es);
1813 }
1814 }
1815
1816 /*
1817 * We have to forcibly clean up the instrumentation state because we
1818 * haven't done ExecutorEnd yet. This is pretty grotty ...
1819 *
1820 * Note: contrib/auto_explain could cause instrumentation to be set up
1821 * even though we didn't ask for it here. Be careful not to print any
1822 * instrumentation results the user didn't ask for. But we do the
1823 * InstrEndLoop call anyway, if possible, to reduce the number of cases
1824 * auto_explain has to contend with.
1825 */
1826 if (planstate->instrument)
1827 InstrEndLoop(planstate->instrument);
1828
1829 if (es->analyze &&
1830 planstate->instrument && planstate->instrument->nloops > 0)
1831 {
1832 double nloops = planstate->instrument->nloops;
1833 double startup_ms = 1000.0 * planstate->instrument->startup / nloops;
1834 double total_ms = 1000.0 * planstate->instrument->total / nloops;
1835 double rows = planstate->instrument->ntuples / nloops;
1836
1837 if (es->format == EXPLAIN_FORMAT_TEXT)
1838 {
1839 appendStringInfoString(es->str, " (actual ");
1840
1841 if (es->timing)
1842 appendStringInfo(es->str, "time=%.3f..%.3f ", startup_ms, total_ms);
1843
1844 appendStringInfo(es->str, "rows=%.2f loops=%.0f)", rows, nloops);
1845 }
1846 else
1847 {
1848 if (es->timing)
1849 {
1850 ExplainPropertyFloat("Actual Startup Time", "ms", startup_ms,
1851 3, es);
1852 ExplainPropertyFloat("Actual Total Time", "ms", total_ms,
1853 3, es);
1854 }
1855 ExplainPropertyFloat("Actual Rows", NULL, rows, 2, es);
1856 ExplainPropertyFloat("Actual Loops", NULL, nloops, 0, es);
1857 }
1858 }
1859 else if (es->analyze)
1860 {
1861 if (es->format == EXPLAIN_FORMAT_TEXT)
1862 appendStringInfoString(es->str, " (never executed)");
1863 else
1864 {
1865 if (es->timing)
1866 {
1867 ExplainPropertyFloat("Actual Startup Time", "ms", 0.0, 3, es);
1868 ExplainPropertyFloat("Actual Total Time", "ms", 0.0, 3, es);
1869 }
1870 ExplainPropertyFloat("Actual Rows", NULL, 0.0, 0, es);
1871 ExplainPropertyFloat("Actual Loops", NULL, 0.0, 0, es);
1872 }
1873 }
1874
1875 /* in text format, first line ends here */
1876 if (es->format == EXPLAIN_FORMAT_TEXT)
1877 appendStringInfoChar(es->str, '\n');
1878
1879
1880 isdisabled = plan_is_disabled(plan);
1881 if (es->format != EXPLAIN_FORMAT_TEXT || isdisabled)
1882 ExplainPropertyBool("Disabled", isdisabled, es);
1883
1884 /* prepare per-worker general execution details */
1885 if (es->workers_state && es->verbose)
1886 {
1887 WorkerInstrumentation *w = planstate->worker_instrument;
1888
1889 for (int n = 0; n < w->num_workers; n++)
1890 {
1891 Instrumentation *instrument = &w->instrument[n];
1892 double nloops = instrument->nloops;
1893 double startup_ms;
1894 double total_ms;
1895 double rows;
1896
1897 if (nloops <= 0)
1898 continue;
1899 startup_ms = 1000.0 * instrument->startup / nloops;
1900 total_ms = 1000.0 * instrument->total / nloops;
1901 rows = instrument->ntuples / nloops;
1902
1903 ExplainOpenWorker(n, es);
1904
1905 if (es->format == EXPLAIN_FORMAT_TEXT)
1906 {
1907 ExplainIndentText(es);
1908 appendStringInfoString(es->str, "actual ");
1909 if (es->timing)
1910 appendStringInfo(es->str, "time=%.3f..%.3f ", startup_ms, total_ms);
1911
1912 appendStringInfo(es->str, "rows=%.2f loops=%.0f\n", rows, nloops);
1913 }
1914 else
1915 {
1916 if (es->timing)
1917 {
1918 ExplainPropertyFloat("Actual Startup Time", "ms",
1919 startup_ms, 3, es);
1920 ExplainPropertyFloat("Actual Total Time", "ms",
1921 total_ms, 3, es);
1922 }
1923
1924 ExplainPropertyFloat("Actual Rows", NULL, rows, 2, es);
1925 ExplainPropertyFloat("Actual Loops", NULL, nloops, 0, es);
1926 }
1927
1928 ExplainCloseWorker(n, es);
1929 }
1930 }
1931
1932 /* target list */
1933 if (es->verbose)
1934 show_plan_tlist(planstate, ancestors, es);
1935
1936 /* unique join */
1937 switch (nodeTag(plan))
1938 {
1939 case T_NestLoop:
1940 case T_MergeJoin:
1941 case T_HashJoin:
1942 /* try not to be too chatty about this in text mode */
1943 if (es->format != EXPLAIN_FORMAT_TEXT ||
1944 (es->verbose && ((Join *) plan)->inner_unique))
1945 ExplainPropertyBool("Inner Unique",
1946 ((Join *) plan)->inner_unique,
1947 es);
1948 break;
1949 default:
1950 break;
1951 }
1952
1953 /* quals, sort keys, etc */
1954 switch (nodeTag(plan))
1955 {
1956 case T_IndexScan:
1957 show_scan_qual(((IndexScan *) plan)->indexqualorig,
1958 "Index Cond", planstate, ancestors, es);
1959 if (((IndexScan *) plan)->indexqualorig)
1960 show_instrumentation_count("Rows Removed by Index Recheck", 2,
1961 planstate, es);
1962 show_scan_qual(((IndexScan *) plan)->indexorderbyorig,
1963 "Order By", planstate, ancestors, es);
1964 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1965 if (plan->qual)
1966 show_instrumentation_count("Rows Removed by Filter", 1,
1967 planstate, es);
1968 show_indexsearches_info(planstate, es);
1969 break;
1970 case T_IndexOnlyScan:
1971 show_scan_qual(((IndexOnlyScan *) plan)->indexqual,
1972 "Index Cond", planstate, ancestors, es);
1973 if (((IndexOnlyScan *) plan)->recheckqual)
1974 show_instrumentation_count("Rows Removed by Index Recheck", 2,
1975 planstate, es);
1976 show_scan_qual(((IndexOnlyScan *) plan)->indexorderby,
1977 "Order By", planstate, ancestors, es);
1978 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1979 if (plan->qual)
1980 show_instrumentation_count("Rows Removed by Filter", 1,
1981 planstate, es);
1982 if (es->analyze)
1983 ExplainPropertyFloat("Heap Fetches", NULL,
1984 planstate->instrument->ntuples2, 0, es);
1985 show_indexsearches_info(planstate, es);
1986 break;
1987 case T_BitmapIndexScan:
1988 show_scan_qual(((BitmapIndexScan *) plan)->indexqualorig,
1989 "Index Cond", planstate, ancestors, es);
1990 show_indexsearches_info(planstate, es);
1991 break;
1992 case T_BitmapHeapScan:
1993 show_scan_qual(((BitmapHeapScan *) plan)->bitmapqualorig,
1994 "Recheck Cond", planstate, ancestors, es);
1995 if (((BitmapHeapScan *) plan)->bitmapqualorig)
1996 show_instrumentation_count("Rows Removed by Index Recheck", 2,
1997 planstate, es);
1998 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
1999 if (plan->qual)
2000 show_instrumentation_count("Rows Removed by Filter", 1,
2001 planstate, es);
2002 show_tidbitmap_info((BitmapHeapScanState *) planstate, es);
2003 break;
2004 case T_SampleScan:
2005 show_tablesample(((SampleScan *) plan)->tablesample,
2006 planstate, ancestors, es);
2007 /* fall through to print additional fields the same as SeqScan */
2008 /* FALLTHROUGH */
2009 case T_SeqScan:
2010 case T_ValuesScan:
2011 case T_CteScan:
2012 case T_NamedTuplestoreScan:
2013 case T_WorkTableScan:
2014 case T_SubqueryScan:
2015 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2016 if (plan->qual)
2017 show_instrumentation_count("Rows Removed by Filter", 1,
2018 planstate, es);
2019 if (IsA(plan, CteScan))
2020 show_ctescan_info(castNode(CteScanState, planstate), es);
2021 break;
2022 case T_Gather:
2023 {
2024 Gather *gather = (Gather *) plan;
2025
2026 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2027 if (plan->qual)
2028 show_instrumentation_count("Rows Removed by Filter", 1,
2029 planstate, es);
2030 ExplainPropertyInteger("Workers Planned", NULL,
2031 gather->num_workers, es);
2032
2033 if (es->analyze)
2034 {
2035 int nworkers;
2036
2037 nworkers = ((GatherState *) planstate)->nworkers_launched;
2038 ExplainPropertyInteger("Workers Launched", NULL,
2039 nworkers, es);
2040 }
2041
2042 if (gather->single_copy || es->format != EXPLAIN_FORMAT_TEXT)
2043 ExplainPropertyBool("Single Copy", gather->single_copy, es);
2044 }
2045 break;
2046 case T_GatherMerge:
2047 {
2048 GatherMerge *gm = (GatherMerge *) plan;
2049
2050 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2051 if (plan->qual)
2052 show_instrumentation_count("Rows Removed by Filter", 1,
2053 planstate, es);
2054 ExplainPropertyInteger("Workers Planned", NULL,
2055 gm->num_workers, es);
2056
2057 if (es->analyze)
2058 {
2059 int nworkers;
2060
2061 nworkers = ((GatherMergeState *) planstate)->nworkers_launched;
2062 ExplainPropertyInteger("Workers Launched", NULL,
2063 nworkers, es);
2064 }
2065 }
2066 break;
2067 case T_FunctionScan:
2068 if (es->verbose)
2069 {
2070 List *fexprs = NIL;
2071 ListCell *lc;
2072
2073 foreach(lc, ((FunctionScan *) plan)->functions)
2074 {
2075 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2076
2077 fexprs = lappend(fexprs, rtfunc->funcexpr);
2078 }
2079 /* We rely on show_expression to insert commas as needed */
2080 show_expression((Node *) fexprs,
2081 "Function Call", planstate, ancestors,
2082 es->verbose, es);
2083 }
2084 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2085 if (plan->qual)
2086 show_instrumentation_count("Rows Removed by Filter", 1,
2087 planstate, es);
2088 break;
2089 case T_TableFuncScan:
2090 if (es->verbose)
2091 {
2092 TableFunc *tablefunc = ((TableFuncScan *) plan)->tablefunc;
2093
2094 show_expression((Node *) tablefunc,
2095 "Table Function Call", planstate, ancestors,
2096 es->verbose, es);
2097 }
2098 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2099 if (plan->qual)
2100 show_instrumentation_count("Rows Removed by Filter", 1,
2101 planstate, es);
2102 show_table_func_scan_info(castNode(TableFuncScanState,
2103 planstate), es);
2104 break;
2105 case T_TidScan:
2106 {
2107 /*
2108 * The tidquals list has OR semantics, so be sure to show it
2109 * as an OR condition.
2110 */
2111 List *tidquals = ((TidScan *) plan)->tidquals;
2112
2113 if (list_length(tidquals) > 1)
2114 tidquals = list_make1(make_orclause(tidquals));
2115 show_scan_qual(tidquals, "TID Cond", planstate, ancestors, es);
2116 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2117 if (plan->qual)
2118 show_instrumentation_count("Rows Removed by Filter", 1,
2119 planstate, es);
2120 }
2121 break;
2122 case T_TidRangeScan:
2123 {
2124 /*
2125 * The tidrangequals list has AND semantics, so be sure to
2126 * show it as an AND condition.
2127 */
2128 List *tidquals = ((TidRangeScan *) plan)->tidrangequals;
2129
2130 if (list_length(tidquals) > 1)
2131 tidquals = list_make1(make_andclause(tidquals));
2132 show_scan_qual(tidquals, "TID Cond", planstate, ancestors, es);
2133 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2134 if (plan->qual)
2135 show_instrumentation_count("Rows Removed by Filter", 1,
2136 planstate, es);
2137 }
2138 break;
2139 case T_ForeignScan:
2140 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2141 if (plan->qual)
2142 show_instrumentation_count("Rows Removed by Filter", 1,
2143 planstate, es);
2144 show_foreignscan_info((ForeignScanState *) planstate, es);
2145 break;
2146 case T_CustomScan:
2147 {
2148 CustomScanState *css = (CustomScanState *) planstate;
2149
2150 show_scan_qual(plan->qual, "Filter", planstate, ancestors, es);
2151 if (plan->qual)
2152 show_instrumentation_count("Rows Removed by Filter", 1,
2153 planstate, es);
2154 if (css->methods->ExplainCustomScan)
2155 css->methods->ExplainCustomScan(css, ancestors, es);
2156 }
2157 break;
2158 case T_NestLoop:
2159 show_upper_qual(((NestLoop *) plan)->join.joinqual,
2160 "Join Filter", planstate, ancestors, es);
2161 if (((NestLoop *) plan)->join.joinqual)
2162 show_instrumentation_count("Rows Removed by Join Filter", 1,
2163 planstate, es);
2164 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2165 if (plan->qual)
2166 show_instrumentation_count("Rows Removed by Filter", 2,
2167 planstate, es);
2168 break;
2169 case T_MergeJoin:
2170 show_upper_qual(((MergeJoin *) plan)->mergeclauses,
2171 "Merge Cond", planstate, ancestors, es);
2172 show_upper_qual(((MergeJoin *) plan)->join.joinqual,
2173 "Join Filter", planstate, ancestors, es);
2174 if (((MergeJoin *) plan)->join.joinqual)
2175 show_instrumentation_count("Rows Removed by Join Filter", 1,
2176 planstate, es);
2177 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2178 if (plan->qual)
2179 show_instrumentation_count("Rows Removed by Filter", 2,
2180 planstate, es);
2181 break;
2182 case T_HashJoin:
2183 show_upper_qual(((HashJoin *) plan)->hashclauses,
2184 "Hash Cond", planstate, ancestors, es);
2185 show_upper_qual(((HashJoin *) plan)->join.joinqual,
2186 "Join Filter", planstate, ancestors, es);
2187 if (((HashJoin *) plan)->join.joinqual)
2188 show_instrumentation_count("Rows Removed by Join Filter", 1,
2189 planstate, es);
2190 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2191 if (plan->qual)
2192 show_instrumentation_count("Rows Removed by Filter", 2,
2193 planstate, es);
2194 break;
2195 case T_Agg:
2196 show_agg_keys(castNode(AggState, planstate), ancestors, es);
2197 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2198 show_hashagg_info((AggState *) planstate, es);
2199 if (plan->qual)
2200 show_instrumentation_count("Rows Removed by Filter", 1,
2201 planstate, es);
2202 break;
2203 case T_WindowAgg:
2204 show_window_def(castNode(WindowAggState, planstate), ancestors, es);
2205 show_upper_qual(((WindowAgg *) plan)->runConditionOrig,
2206 "Run Condition", planstate, ancestors, es);
2207 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2208 if (plan->qual)
2209 show_instrumentation_count("Rows Removed by Filter", 1,
2210 planstate, es);
2211 show_windowagg_info(castNode(WindowAggState, planstate), es);
2212 break;
2213 case T_Group:
2214 show_group_keys(castNode(GroupState, planstate), ancestors, es);
2215 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2216 if (plan->qual)
2217 show_instrumentation_count("Rows Removed by Filter", 1,
2218 planstate, es);
2219 break;
2220 case T_Sort:
2221 show_sort_keys(castNode(SortState, planstate), ancestors, es);
2222 show_sort_info(castNode(SortState, planstate), es);
2223 break;
2224 case T_IncrementalSort:
2225 show_incremental_sort_keys(castNode(IncrementalSortState, planstate),
2226 ancestors, es);
2227 show_incremental_sort_info(castNode(IncrementalSortState, planstate),
2228 es);
2229 break;
2230 case T_MergeAppend:
2231 show_merge_append_keys(castNode(MergeAppendState, planstate),
2232 ancestors, es);
2233 break;
2234 case T_Result:
2235 show_upper_qual((List *) ((Result *) plan)->resconstantqual,
2236 "One-Time Filter", planstate, ancestors, es);
2237 show_upper_qual(plan->qual, "Filter", planstate, ancestors, es);
2238 if (plan->qual)
2239 show_instrumentation_count("Rows Removed by Filter", 1,
2240 planstate, es);
2241 break;
2242 case T_ModifyTable:
2243 show_modifytable_info(castNode(ModifyTableState, planstate), ancestors,
2244 es);
2245 break;
2246 case T_Hash:
2247 show_hash_info(castNode(HashState, planstate), es);
2248 break;
2249 case T_Material:
2250 show_material_info(castNode(MaterialState, planstate), es);
2251 break;
2252 case T_Memoize:
2253 show_memoize_info(castNode(MemoizeState, planstate), ancestors,
2254 es);
2255 break;
2256 case T_RecursiveUnion:
2257 show_recursive_union_info(castNode(RecursiveUnionState,
2258 planstate), es);
2259 break;
2260 default:
2261 break;
2262 }
2263
2264 /*
2265 * Prepare per-worker JIT instrumentation. As with the overall JIT
2266 * summary, this is printed only if printing costs is enabled.
2267 */
2268 if (es->workers_state && es->costs && es->verbose)
2269 {
2270 SharedJitInstrumentation *w = planstate->worker_jit_instrument;
2271
2272 if (w)
2273 {
2274 for (int n = 0; n < w->num_workers; n++)
2275 {
2276 ExplainOpenWorker(n, es);
2277 ExplainPrintJIT(es, planstate->state->es_jit_flags,
2278 &w->jit_instr[n]);
2279 ExplainCloseWorker(n, es);
2280 }
2281 }
2282 }
2283
2284 /* Show buffer/WAL usage */
2285 if (es->buffers && planstate->instrument)
2286 show_buffer_usage(es, &planstate->instrument->bufusage);
2287 if (es->wal && planstate->instrument)
2288 show_wal_usage(es, &planstate->instrument->walusage);
2289
2290 /* Prepare per-worker buffer/WAL usage */
2291 if (es->workers_state && (es->buffers || es->wal) && es->verbose)
2292 {
2293 WorkerInstrumentation *w = planstate->worker_instrument;
2294
2295 for (int n = 0; n < w->num_workers; n++)
2296 {
2297 Instrumentation *instrument = &w->instrument[n];
2298 double nloops = instrument->nloops;
2299
2300 if (nloops <= 0)
2301 continue;
2302
2303 ExplainOpenWorker(n, es);
2304 if (es->buffers)
2305 show_buffer_usage(es, &instrument->bufusage);
2306 if (es->wal)
2307 show_wal_usage(es, &instrument->walusage);
2308 ExplainCloseWorker(n, es);
2309 }
2310 }
2311
2312 /* Show per-worker details for this plan node, then pop that stack */
2313 if (es->workers_state)
2314 ExplainFlushWorkersState(es);
2315 es->workers_state = save_workers_state;
2316
2317 /* Allow plugins to print additional information */
2318 if (explain_per_node_hook)
2319 (*explain_per_node_hook) (planstate, ancestors, relationship,
2320 plan_name, es);
2321
2322 /*
2323 * If partition pruning was done during executor initialization, the
2324 * number of child plans we'll display below will be less than the number
2325 * of subplans that was specified in the plan. To make this a bit less
2326 * mysterious, emit an indication that this happened. Note that this
2327 * field is emitted now because we want it to be a property of the parent
2328 * node; it *cannot* be emitted within the Plans sub-node we'll open next.
2329 */
2330 switch (nodeTag(plan))
2331 {
2332 case T_Append:
2333 ExplainMissingMembers(((AppendState *) planstate)->as_nplans,
2334 list_length(((Append *) plan)->appendplans),
2335 es);
2336 break;
2337 case T_MergeAppend:
2338 ExplainMissingMembers(((MergeAppendState *) planstate)->ms_nplans,
2339 list_length(((MergeAppend *) plan)->mergeplans),
2340 es);
2341 break;
2342 default:
2343 break;
2344 }
2345
2346 /* Get ready to display the child plans */
2347 haschildren = planstate->initPlan ||
2348 outerPlanState(planstate) ||
2349 innerPlanState(planstate) ||
2350 IsA(plan, Append) ||
2351 IsA(plan, MergeAppend) ||
2352 IsA(plan, BitmapAnd) ||
2353 IsA(plan, BitmapOr) ||
2354 IsA(plan, SubqueryScan) ||
2355 (IsA(planstate, CustomScanState) &&
2356 ((CustomScanState *) planstate)->custom_ps != NIL) ||
2357 planstate->subPlan;
2358 if (haschildren)
2359 {
2360 ExplainOpenGroup("Plans", "Plans", false, es);
2361 /* Pass current Plan as head of ancestors list for children */
2362 ancestors = lcons(plan, ancestors);
2363 }
2364
2365 /* initPlan-s */
2366 if (planstate->initPlan)
2367 ExplainSubPlans(planstate->initPlan, ancestors, "InitPlan", es);
2368
2369 /* lefttree */
2370 if (outerPlanState(planstate))
2371 ExplainNode(outerPlanState(planstate), ancestors,
2372 "Outer", NULL, es);
2373
2374 /* righttree */
2375 if (innerPlanState(planstate))
2376 ExplainNode(innerPlanState(planstate), ancestors,
2377 "Inner", NULL, es);
2378
2379 /* special child plans */
2380 switch (nodeTag(plan))
2381 {
2382 case T_Append:
2383 ExplainMemberNodes(((AppendState *) planstate)->appendplans,
2384 ((AppendState *) planstate)->as_nplans,
2385 ancestors, es);
2386 break;
2387 case T_MergeAppend:
2388 ExplainMemberNodes(((MergeAppendState *) planstate)->mergeplans,
2389 ((MergeAppendState *) planstate)->ms_nplans,
2390 ancestors, es);
2391 break;
2392 case T_BitmapAnd:
2393 ExplainMemberNodes(((BitmapAndState *) planstate)->bitmapplans,
2394 ((BitmapAndState *) planstate)->nplans,
2395 ancestors, es);
2396 break;
2397 case T_BitmapOr:
2398 ExplainMemberNodes(((BitmapOrState *) planstate)->bitmapplans,
2399 ((BitmapOrState *) planstate)->nplans,
2400 ancestors, es);
2401 break;
2402 case T_SubqueryScan:
2403 ExplainNode(((SubqueryScanState *) planstate)->subplan, ancestors,
2404 "Subquery", NULL, es);
2405 break;
2406 case T_CustomScan:
2407 ExplainCustomChildren((CustomScanState *) planstate,
2408 ancestors, es);
2409 break;
2410 default:
2411 break;
2412 }
2413
2414 /* subPlan-s */
2415 if (planstate->subPlan)
2416 ExplainSubPlans(planstate->subPlan, ancestors, "SubPlan", es);
2417
2418 /* end of child plans */
2419 if (haschildren)
2420 {
2421 ancestors = list_delete_first(ancestors);
2422 ExplainCloseGroup("Plans", "Plans", false, es);
2423 }
2424
2425 /* in text format, undo whatever indentation we added */
2426 if (es->format == EXPLAIN_FORMAT_TEXT)
2427 es->indent = save_indent;
2428
2429 ExplainCloseGroup("Plan",
2430 relationship ? NULL : "Plan",
2431 true, es);
2432 }
2433
2434 /*
2435 * Show the targetlist of a plan node
2436 */
2437 static void
2438 show_plan_tlist(PlanState *planstate, List *ancestors, ExplainState *es)
2439 {
2440 Plan *plan = planstate->plan;
2441 List *context;
2442 List *result = NIL;
2443 bool useprefix;
2444 ListCell *lc;
2445
2446 /* No work if empty tlist (this occurs eg in bitmap indexscans) */
2447 if (plan->targetlist == NIL)
2448 return;
2449 /* The tlist of an Append isn't real helpful, so suppress it */
2450 if (IsA(plan, Append))
2451 return;
2452 /* Likewise for MergeAppend and RecursiveUnion */
2453 if (IsA(plan, MergeAppend))
2454 return;
2455 if (IsA(plan, RecursiveUnion))
2456 return;
2457
2458 /*
2459 * Likewise for ForeignScan that executes a direct INSERT/UPDATE/DELETE
2460 *
2461 * Note: the tlist for a ForeignScan that executes a direct INSERT/UPDATE
2462 * might contain subplan output expressions that are confusing in this
2463 * context. The tlist for a ForeignScan that executes a direct UPDATE/
2464 * DELETE always contains "junk" target columns to identify the exact row
2465 * to update or delete, which would be confusing in this context. So, we
2466 * suppress it in all the cases.
2467 */
2468 if (IsA(plan, ForeignScan) &&
2469 ((ForeignScan *) plan)->operation != CMD_SELECT)
2470 return;
2471
2472 /* Set up deparsing context */
2473 context = set_deparse_context_plan(es->deparse_cxt,
2474 plan,
2475 ancestors);
2476 useprefix = es->rtable_size > 1;
2477
2478 /* Deparse each result column (we now include resjunk ones) */
2479 foreach(lc, plan->targetlist)
2480 {
2481 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2482
2483 result = lappend(result,
2484 deparse_expression((Node *) tle->expr, context,
2485 useprefix, false));
2486 }
2487
2488 /* Print results */
2489 ExplainPropertyList("Output", result, es);
2490 }
2491
2492 /*
2493 * Show a generic expression
2494 */
2495 static void
2496 show_expression(Node *node, const char *qlabel,
2497 PlanState *planstate, List *ancestors,
2498 bool useprefix, ExplainState *es)
2499 {
2500 List *context;
2501 char *exprstr;
2502
2503 /* Set up deparsing context */
2504 context = set_deparse_context_plan(es->deparse_cxt,
2505 planstate->plan,
2506 ancestors);
2507
2508 /* Deparse the expression */
2509 exprstr = deparse_expression(node, context, useprefix, false);
2510
2511 /* And add to es->str */
2512 ExplainPropertyText(qlabel, exprstr, es);
2513 }
2514
2515 /*
2516 * Show a qualifier expression (which is a List with implicit AND semantics)
2517 */
2518 static void
2519 show_qual(List *qual, const char *qlabel,
2520 PlanState *planstate, List *ancestors,
2521 bool useprefix, ExplainState *es)
2522 {
2523 Node *node;
2524
2525 /* No work if empty qual */
2526 if (qual == NIL)
2527 return;
2528
2529 /* Convert AND list to explicit AND */
2530 node = (Node *) make_ands_explicit(qual);
2531
2532 /* And show it */
2533 show_expression(node, qlabel, planstate, ancestors, useprefix, es);
2534 }
2535
2536 /*
2537 * Show a qualifier expression for a scan plan node
2538 */
2539 static void
2540 show_scan_qual(List *qual, const char *qlabel,
2541 PlanState *planstate, List *ancestors,
2542 ExplainState *es)
2543 {
2544 bool useprefix;
2545
2546 useprefix = (IsA(planstate->plan, SubqueryScan) || es->verbose);
2547 show_qual(qual, qlabel, planstate, ancestors, useprefix, es);
2548 }
2549
2550 /*
2551 * Show a qualifier expression for an upper-level plan node
2552 */
2553 static void
2554 show_upper_qual(List *qual, const char *qlabel,
2555 PlanState *planstate, List *ancestors,
2556 ExplainState *es)
2557 {
2558 bool useprefix;
2559
2560 useprefix = (es->rtable_size > 1 || es->verbose);
2561 show_qual(qual, qlabel, planstate, ancestors, useprefix, es);
2562 }
2563
2564 /*
2565 * Show the sort keys for a Sort node.
2566 */
2567 static void
2568 show_sort_keys(SortState *sortstate, List *ancestors, ExplainState *es)
2569 {
2570 Sort *plan = (Sort *) sortstate->ss.ps.plan;
2571
2572 show_sort_group_keys((PlanState *) sortstate, "Sort Key",
2573 plan->numCols, 0, plan->sortColIdx,
2574 plan->sortOperators, plan->collations,
2575 plan->nullsFirst,
2576 ancestors, es);
2577 }
2578
2579 /*
2580 * Show the sort keys for an IncrementalSort node.
2581 */
2582 static void
2583 show_incremental_sort_keys(IncrementalSortState *incrsortstate,
2584 List *ancestors, ExplainState *es)
2585 {
2586 IncrementalSort *plan = (IncrementalSort *) incrsortstate->ss.ps.plan;
2587
2588 show_sort_group_keys((PlanState *) incrsortstate, "Sort Key",
2589 plan->sort.numCols, plan->nPresortedCols,
2590 plan->sort.sortColIdx,
2591 plan->sort.sortOperators, plan->sort.collations,
2592 plan->sort.nullsFirst,
2593 ancestors, es);
2594 }
2595
2596 /*
2597 * Likewise, for a MergeAppend node.
2598 */
2599 static void
2600 show_merge_append_keys(MergeAppendState *mstate, List *ancestors,
2601 ExplainState *es)
2602 {
2603 MergeAppend *plan = (MergeAppend *) mstate->ps.plan;
2604
2605 show_sort_group_keys((PlanState *) mstate, "Sort Key",
2606 plan->numCols, 0, plan->sortColIdx,
2607 plan->sortOperators, plan->collations,
2608 plan->nullsFirst,
2609 ancestors, es);
2610 }
2611
2612 /*
2613 * Show the grouping keys for an Agg node.
2614 */
2615 static void
2616 show_agg_keys(AggState *astate, List *ancestors,
2617 ExplainState *es)
2618 {
2619 Agg *plan = (Agg *) astate->ss.ps.plan;
2620
2621 if (plan->numCols > 0 || plan->groupingSets)
2622 {
2623 /* The key columns refer to the tlist of the child plan */
2624 ancestors = lcons(plan, ancestors);
2625
2626 if (plan->groupingSets)
2627 show_grouping_sets(outerPlanState(astate), plan, ancestors, es);
2628 else
2629 show_sort_group_keys(outerPlanState(astate), "Group Key",
2630 plan->numCols, 0, plan->grpColIdx,
2631 NULL, NULL, NULL,
2632 ancestors, es);
2633
2634 ancestors = list_delete_first(ancestors);
2635 }
2636 }
2637
2638 static void
2639 show_grouping_sets(PlanState *planstate, Agg *agg,
2640 List *ancestors, ExplainState *es)
2641 {
2642 List *context;
2643 bool useprefix;
2644 ListCell *lc;
2645
2646 /* Set up deparsing context */
2647 context = set_deparse_context_plan(es->deparse_cxt,
2648 planstate->plan,
2649 ancestors);
2650 useprefix = (es->rtable_size > 1 || es->verbose);
2651
2652 ExplainOpenGroup("Grouping Sets", "Grouping Sets", false, es);
2653
2654 show_grouping_set_keys(planstate, agg, NULL,
2655 context, useprefix, ancestors, es);
2656
2657 foreach(lc, agg->chain)
2658 {
2659 Agg *aggnode = lfirst(lc);
2660 Sort *sortnode = (Sort *) aggnode->plan.lefttree;
2661
2662 show_grouping_set_keys(planstate, aggnode, sortnode,
2663 context, useprefix, ancestors, es);
2664 }
2665
2666 ExplainCloseGroup("Grouping Sets", "Grouping Sets", false, es);
2667 }
2668
2669 static void
2670 show_grouping_set_keys(PlanState *planstate,
2671 Agg *aggnode, Sort *sortnode,
2672 List *context, bool useprefix,
2673 List *ancestors, ExplainState *es)
2674 {
2675 Plan *plan = planstate->plan;
2676 char *exprstr;
2677 ListCell *lc;
2678 List *gsets = aggnode->groupingSets;
2679 AttrNumber *keycols = aggnode->grpColIdx;
2680 const char *keyname;
2681 const char *keysetname;
2682
2683 if (aggnode->aggstrategy == AGG_HASHED || aggnode->aggstrategy == AGG_MIXED)
2684 {
2685 keyname = "Hash Key";
2686 keysetname = "Hash Keys";
2687 }
2688 else
2689 {
2690 keyname = "Group Key";
2691 keysetname = "Group Keys";
2692 }
2693
2694 ExplainOpenGroup("Grouping Set", NULL, true, es);
2695
2696 if (sortnode)
2697 {
2698 show_sort_group_keys(planstate, "Sort Key",
2699 sortnode->numCols, 0, sortnode->sortColIdx,
2700 sortnode->sortOperators, sortnode->collations,
2701 sortnode->nullsFirst,
2702 ancestors, es);
2703 if (es->format == EXPLAIN_FORMAT_TEXT)
2704 es->indent++;
2705 }
2706
2707 ExplainOpenGroup(keysetname, keysetname, false, es);
2708
2709 foreach(lc, gsets)
2710 {
2711 List *result = NIL;
2712 ListCell *lc2;
2713
2714 foreach(lc2, (List *) lfirst(lc))
2715 {
2716 Index i = lfirst_int(lc2);
2717 AttrNumber keyresno = keycols[i];
2718 TargetEntry *target = get_tle_by_resno(plan->targetlist,
2719 keyresno);
2720
2721 if (!target)
2722 elog(ERROR, "no tlist entry for key %d", keyresno);
2723 /* Deparse the expression, showing any top-level cast */
2724 exprstr = deparse_expression((Node *) target->expr, context,
2725 useprefix, true);
2726
2727 result = lappend(result, exprstr);
2728 }
2729
2730 if (!result && es->format == EXPLAIN_FORMAT_TEXT)
2731 ExplainPropertyText(keyname, "()", es);
2732 else
2733 ExplainPropertyListNested(keyname, result, es);
2734 }
2735
2736 ExplainCloseGroup(keysetname, keysetname, false, es);
2737
2738 if (sortnode && es->format == EXPLAIN_FORMAT_TEXT)
2739 es->indent--;
2740
2741 ExplainCloseGroup("Grouping Set", NULL, true, es);
2742 }
2743
2744 /*
2745 * Show the grouping keys for a Group node.
2746 */
2747 static void
2748 show_group_keys(GroupState *gstate, List *ancestors,
2749 ExplainState *es)
2750 {
2751 Group *plan = (Group *) gstate->ss.ps.plan;
2752
2753 /* The key columns refer to the tlist of the child plan */
2754 ancestors = lcons(plan, ancestors);
2755 show_sort_group_keys(outerPlanState(gstate), "Group Key",
2756 plan->numCols, 0, plan->grpColIdx,
2757 NULL, NULL, NULL,
2758 ancestors, es);
2759 ancestors = list_delete_first(ancestors);
2760 }
2761
2762 /*
2763 * Common code to show sort/group keys, which are represented in plan nodes
2764 * as arrays of targetlist indexes. If it's a sort key rather than a group
2765 * key, also pass sort operators/collations/nullsFirst arrays.
2766 */
2767 static void
2768 show_sort_group_keys(PlanState *planstate, const char *qlabel,
2769 int nkeys, int nPresortedKeys, AttrNumber *keycols,
2770 Oid *sortOperators, Oid *collations, bool *nullsFirst,
2771 List *ancestors, ExplainState *es)
2772 {
2773 Plan *plan = planstate->plan;
2774 List *context;
2775 List *result = NIL;
2776 List *resultPresorted = NIL;
2777 StringInfoData sortkeybuf;
2778 bool useprefix;
2779 int keyno;
2780
2781 if (nkeys <= 0)
2782 return;
2783
2784 initStringInfo(&sortkeybuf);
2785
2786 /* Set up deparsing context */
2787 context = set_deparse_context_plan(es->deparse_cxt,
2788 plan,
2789 ancestors);
2790 useprefix = (es->rtable_size > 1 || es->verbose);
2791
2792 for (keyno = 0; keyno < nkeys; keyno++)
2793 {
2794 /* find key expression in tlist */
2795 AttrNumber keyresno = keycols[keyno];
2796 TargetEntry *target = get_tle_by_resno(plan->targetlist,
2797 keyresno);
2798 char *exprstr;
2799
2800 if (!target)
2801 elog(ERROR, "no tlist entry for key %d", keyresno);
2802 /* Deparse the expression, showing any top-level cast */
2803 exprstr = deparse_expression((Node *) target->expr, context,
2804 useprefix, true);
2805 resetStringInfo(&sortkeybuf);
2806 appendStringInfoString(&sortkeybuf, exprstr);
2807 /* Append sort order information, if relevant */
2808 if (sortOperators != NULL)
2809 show_sortorder_options(&sortkeybuf,
2810 (Node *) target->expr,
2811 sortOperators[keyno],
2812 collations[keyno],
2813 nullsFirst[keyno]);
2814 /* Emit one property-list item per sort key */
2815 result = lappend(result, pstrdup(sortkeybuf.data));
2816 if (keyno < nPresortedKeys)
2817 resultPresorted = lappend(resultPresorted, exprstr);
2818 }
2819
2820 ExplainPropertyList(qlabel, result, es);
2821 if (nPresortedKeys > 0)
2822 ExplainPropertyList("Presorted Key", resultPresorted, es);
2823 }
2824
2825 /*
2826 * Append nondefault characteristics of the sort ordering of a column to buf
2827 * (collation, direction, NULLS FIRST/LAST)
2828 */
2829 static void
2830 show_sortorder_options(StringInfo buf, Node *sortexpr,
2831 Oid sortOperator, Oid collation, bool nullsFirst)
2832 {
2833 Oid sortcoltype = exprType(sortexpr);
2834 bool reverse = false;
2835 TypeCacheEntry *typentry;
2836
2837 typentry = lookup_type_cache(sortcoltype,
2838 TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
2839
2840 /*
2841 * Print COLLATE if it's not default for the column's type. There are
2842 * some cases where this is redundant, eg if expression is a column whose
2843 * declared collation is that collation, but it's hard to distinguish that
2844 * here (and arguably, printing COLLATE explicitly is a good idea anyway
2845 * in such cases).
2846 */
2847 if (OidIsValid(collation) && collation != get_typcollation(sortcoltype))
2848 {
2849 char *collname = get_collation_name(collation);
2850
2851 if (collname == NULL)
2852 elog(ERROR, "cache lookup failed for collation %u", collation);
2853 appendStringInfo(buf, " COLLATE %s", quote_identifier(collname));
2854 }
2855
2856 /* Print direction if not ASC, or USING if non-default sort operator */
2857 if (sortOperator == typentry->gt_opr)
2858 {
2859 appendStringInfoString(buf, " DESC");
2860 reverse = true;
2861 }
2862 else if (sortOperator != typentry->lt_opr)
2863 {
2864 char *opname = get_opname(sortOperator);
2865
2866 if (opname == NULL)
2867 elog(ERROR, "cache lookup failed for operator %u", sortOperator);
2868 appendStringInfo(buf, " USING %s", opname);
2869 /* Determine whether operator would be considered ASC or DESC */
2870 (void) get_equality_op_for_ordering_op(sortOperator, &reverse);
2871 }
2872
2873 /* Add NULLS FIRST/LAST only if it wouldn't be default */
2874 if (nullsFirst && !reverse)
2875 {
2876 appendStringInfoString(buf, " NULLS FIRST");
2877 }
2878 else if (!nullsFirst && reverse)
2879 {
2880 appendStringInfoString(buf, " NULLS LAST");
2881 }
2882 }
2883
2884 /*
2885 * Show the window definition for a WindowAgg node.
2886 */
2887 static void
2888 show_window_def(WindowAggState *planstate, List *ancestors, ExplainState *es)
2889 {
2890 WindowAgg *wagg = (WindowAgg *) planstate->ss.ps.plan;
2891 StringInfoData wbuf;
2892 bool needspace = false;
2893
2894 initStringInfo(&wbuf);
2895 appendStringInfo(&wbuf, "%s AS (", quote_identifier(wagg->winname));
2896
2897 /* The key columns refer to the tlist of the child plan */
2898 ancestors = lcons(wagg, ancestors);
2899 if (wagg->partNumCols > 0)
2900 {
2901 appendStringInfoString(&wbuf, "PARTITION BY ");
2902 show_window_keys(&wbuf, outerPlanState(planstate),
2903 wagg->partNumCols, wagg->partColIdx,
2904 ancestors, es);
2905 needspace = true;
2906 }
2907 if (wagg->ordNumCols > 0)
2908 {
2909 if (needspace)
2910 appendStringInfoChar(&wbuf, ' ');
2911 appendStringInfoString(&wbuf, "ORDER BY ");
2912 show_window_keys(&wbuf, outerPlanState(planstate),
2913 wagg->ordNumCols, wagg->ordColIdx,
2914 ancestors, es);
2915 needspace = true;
2916 }
2917 ancestors = list_delete_first(ancestors);
2918 if (wagg->frameOptions & FRAMEOPTION_NONDEFAULT)
2919 {
2920 List *context;
2921 bool useprefix;
2922 char *framestr;
2923
2924 /* Set up deparsing context for possible frame expressions */
2925 context = set_deparse_context_plan(es->deparse_cxt,
2926 (Plan *) wagg,
2927 ancestors);
2928 useprefix = (es->rtable_size > 1 || es->verbose);
2929 framestr = get_window_frame_options_for_explain(wagg->frameOptions,
2930 wagg->startOffset,
2931 wagg->endOffset,
2932 context,
2933 useprefix);
2934 if (needspace)
2935 appendStringInfoChar(&wbuf, ' ');
2936 appendStringInfoString(&wbuf, framestr);
2937 pfree(framestr);
2938 }
2939 appendStringInfoChar(&wbuf, ')');
2940 ExplainPropertyText("Window", wbuf.data, es);
2941 pfree(wbuf.data);
2942 }
2943
2944 /*
2945 * Append the keys of a window's PARTITION BY or ORDER BY clause to buf.
2946 * We can't use show_sort_group_keys for this because that's too opinionated
2947 * about how the result will be displayed.
2948 * Note that the "planstate" node should be the WindowAgg's child.
2949 */
2950 static void
2951 show_window_keys(StringInfo buf, PlanState *planstate,
2952 int nkeys, AttrNumber *keycols,
2953 List *ancestors, ExplainState *es)
2954 {
2955 Plan *plan = planstate->plan;
2956 List *context;
2957 bool useprefix;
2958
2959 /* Set up deparsing context */
2960 context = set_deparse_context_plan(es->deparse_cxt,
2961 plan,
2962 ancestors);
2963 useprefix = (es->rtable_size > 1 || es->verbose);
2964
2965 for (int keyno = 0; keyno < nkeys; keyno++)
2966 {
2967 /* find key expression in tlist */
2968 AttrNumber keyresno = keycols[keyno];
2969 TargetEntry *target = get_tle_by_resno(plan->targetlist,
2970 keyresno);
2971 char *exprstr;
2972
2973 if (!target)
2974 elog(ERROR, "no tlist entry for key %d", keyresno);
2975 /* Deparse the expression, showing any top-level cast */
2976 exprstr = deparse_expression((Node *) target->expr, context,
2977 useprefix, true);
2978 if (keyno > 0)
2979 appendStringInfoString(buf, ", ");
2980 appendStringInfoString(buf, exprstr);
2981 pfree(exprstr);
2982
2983 /*
2984 * We don't attempt to provide sort order information because
2985 * WindowAgg carries equality operators not comparison operators;
2986 * compare show_agg_keys.
2987 */
2988 }
2989 }
2990
2991 /*
2992 * Show information on storage method and maximum memory/disk space used.
2993 */
2994 static void
2995 show_storage_info(char *maxStorageType, int64 maxSpaceUsed, ExplainState *es)
2996 {
2997 int64 maxSpaceUsedKB = BYTES_TO_KILOBYTES(maxSpaceUsed);
2998
2999 if (es->format != EXPLAIN_FORMAT_TEXT)
3000 {
3001 ExplainPropertyText("Storage", maxStorageType, es);
3002 ExplainPropertyInteger("Maximum Storage", "kB", maxSpaceUsedKB, es);
3003 }
3004 else
3005 {
3006 ExplainIndentText(es);
3007 appendStringInfo(es->str,
3008 "Storage: %s Maximum Storage: " INT64_FORMAT "kB\n",
3009 maxStorageType,
3010 maxSpaceUsedKB);
3011 }
3012 }
3013
3014 /*
3015 * Show TABLESAMPLE properties
3016 */
3017 static void
3018 show_tablesample(TableSampleClause *tsc, PlanState *planstate,
3019 List *ancestors, ExplainState *es)
3020 {
3021 List *context;
3022 bool useprefix;
3023 char *method_name;
3024 List *params = NIL;
3025 char *repeatable;
3026 ListCell *lc;
3027
3028 /* Set up deparsing context */
3029 context = set_deparse_context_plan(es->deparse_cxt,
3030 planstate->plan,
3031 ancestors);
3032 useprefix = es->rtable_size > 1;
3033
3034 /* Get the tablesample method name */
3035 method_name = get_func_name(tsc->tsmhandler);
3036
3037 /* Deparse parameter expressions */
3038 foreach(lc, tsc->args)
3039 {
3040 Node *arg = (Node *) lfirst(lc);
3041
3042 params = lappend(params,
3043 deparse_expression(arg, context,
3044 useprefix, false));
3045 }
3046 if (tsc->repeatable)
3047 repeatable = deparse_expression((Node *) tsc->repeatable, context,
3048 useprefix, false);
3049 else
3050 repeatable = NULL;
3051
3052 /* Print results */
3053 if (es->format == EXPLAIN_FORMAT_TEXT)
3054 {
3055 bool first = true;
3056
3057 ExplainIndentText(es);
3058 appendStringInfo(es->str, "Sampling: %s (", method_name);
3059 foreach(lc, params)
3060 {
3061 if (!first)
3062 appendStringInfoString(es->str, ", ");
3063 appendStringInfoString(es->str, (const char *) lfirst(lc));
3064 first = false;
3065 }
3066 appendStringInfoChar(es->str, ')');
3067 if (repeatable)
3068 appendStringInfo(es->str, " REPEATABLE (%s)", repeatable);
3069 appendStringInfoChar(es->str, '\n');
3070 }
3071 else
3072 {
3073 ExplainPropertyText("Sampling Method", method_name, es);
3074 ExplainPropertyList("Sampling Parameters", params, es);
3075 if (repeatable)
3076 ExplainPropertyText("Repeatable Seed", repeatable, es);
3077 }
3078 }
3079
3080 /*
3081 * If it's EXPLAIN ANALYZE, show tuplesort stats for a sort node
3082 */
3083 static void
3084 show_sort_info(SortState *sortstate, ExplainState *es)
3085 {
3086 if (!es->analyze)
3087 return;
3088
3089 if (sortstate->sort_Done && sortstate->tuplesortstate != NULL)
3090 {
3091 Tuplesortstate *state = (Tuplesortstate *) sortstate->tuplesortstate;
3092 TuplesortInstrumentation stats;
3093 const char *sortMethod;
3094 const char *spaceType;
3095 int64 spaceUsed;
3096
3097 tuplesort_get_stats(state, &stats);
3098 sortMethod = tuplesort_method_name(stats.sortMethod);
3099 spaceType = tuplesort_space_type_name(stats.spaceType);
3100 spaceUsed = stats.spaceUsed;
3101
3102 if (es->format == EXPLAIN_FORMAT_TEXT)
3103 {
3104 ExplainIndentText(es);
3105 appendStringInfo(es->str, "Sort Method: %s %s: " INT64_FORMAT "kB\n",
3106 sortMethod, spaceType, spaceUsed);
3107 }
3108 else
3109 {
3110 ExplainPropertyText("Sort Method", sortMethod, es);
3111 ExplainPropertyInteger("Sort Space Used", "kB", spaceUsed, es);
3112 ExplainPropertyText("Sort Space Type", spaceType, es);
3113 }
3114 }
3115
3116 /*
3117 * You might think we should just skip this stanza entirely when
3118 * es->hide_workers is true, but then we'd get no sort-method output at
3119 * all. We have to make it look like worker 0's data is top-level data.
3120 * This is easily done by just skipping the OpenWorker/CloseWorker calls.
3121 * Currently, we don't worry about the possibility that there are multiple
3122 * workers in such a case; if there are, duplicate output fields will be
3123 * emitted.
3124 */
3125 if (sortstate->shared_info != NULL)
3126 {
3127 int n;
3128
3129 for (n = 0; n < sortstate->shared_info->num_workers; n++)
3130 {
3131 TuplesortInstrumentation *sinstrument;
3132 const char *sortMethod;
3133 const char *spaceType;
3134 int64 spaceUsed;
3135
3136 sinstrument = &sortstate->shared_info->sinstrument[n];
3137 if (sinstrument->sortMethod == SORT_TYPE_STILL_IN_PROGRESS)
3138 continue; /* ignore any unfilled slots */
3139 sortMethod = tuplesort_method_name(sinstrument->sortMethod);
3140 spaceType = tuplesort_space_type_name(sinstrument->spaceType);
3141 spaceUsed = sinstrument->spaceUsed;
3142
3143 if (es->workers_state)
3144 ExplainOpenWorker(n, es);
3145
3146 if (es->format == EXPLAIN_FORMAT_TEXT)
3147 {
3148 ExplainIndentText(es);
3149 appendStringInfo(es->str,
3150 "Sort Method: %s %s: " INT64_FORMAT "kB\n",
3151 sortMethod, spaceType, spaceUsed);
3152 }
3153 else
3154 {
3155 ExplainPropertyText("Sort Method", sortMethod, es);
3156 ExplainPropertyInteger("Sort Space Used", "kB", spaceUsed, es);
3157 ExplainPropertyText("Sort Space Type", spaceType, es);
3158 }
3159
3160 if (es->workers_state)
3161 ExplainCloseWorker(n, es);
3162 }
3163 }
3164 }
3165
3166 /*
3167 * Incremental sort nodes sort in (a potentially very large number of) batches,
3168 * so EXPLAIN ANALYZE needs to roll up the tuplesort stats from each batch into
3169 * an intelligible summary.
3170 *
3171 * This function is used for both a non-parallel node and each worker in a
3172 * parallel incremental sort node.
3173 */
3174 static void
3175 show_incremental_sort_group_info(IncrementalSortGroupInfo *groupInfo,
3176 const char *groupLabel, bool indent, ExplainState *es)
3177 {
3178 ListCell *methodCell;
3179 List *methodNames = NIL;
3180
3181 /* Generate a list of sort methods used across all groups. */
3182 for (int bit = 0; bit < NUM_TUPLESORTMETHODS; bit++)
3183 {
3184 TuplesortMethod sortMethod = (1 << bit);
3185
3186 if (groupInfo->sortMethods & sortMethod)
3187 {
3188 const char *methodName = tuplesort_method_name(sortMethod);
3189
3190 methodNames = lappend(methodNames, unconstify(char *, methodName));
3191 }
3192 }
3193
3194 if (es->format == EXPLAIN_FORMAT_TEXT)
3195 {
3196 if (indent)
3197 appendStringInfoSpaces(es->str, es->indent * 2);
3198 appendStringInfo(es->str, "%s Groups: " INT64_FORMAT " Sort Method", groupLabel,
3199 groupInfo->groupCount);
3200 /* plural/singular based on methodNames size */
3201 if (list_length(methodNames) > 1)
3202 appendStringInfoString(es->str, "s: ");
3203 else
3204 appendStringInfoString(es->str, ": ");
3205 foreach(methodCell, methodNames)
3206 {
3207 appendStringInfoString(es->str, (char *) methodCell->ptr_value);
3208 if (foreach_current_index(methodCell) < list_length(methodNames) - 1)
3209 appendStringInfoString(es->str, ", ");
3210 }
3211
3212 if (groupInfo->maxMemorySpaceUsed > 0)
3213 {
3214 int64 avgSpace = groupInfo->totalMemorySpaceUsed / groupInfo->groupCount;
3215 const char *spaceTypeName;
3216
3217 spaceTypeName = tuplesort_space_type_name(SORT_SPACE_TYPE_MEMORY);
3218 appendStringInfo(es->str, " Average %s: " INT64_FORMAT "kB Peak %s: " INT64_FORMAT "kB",
3219 spaceTypeName, avgSpace,
3220 spaceTypeName, groupInfo->maxMemorySpaceUsed);
3221 }
3222
3223 if (groupInfo->maxDiskSpaceUsed > 0)
3224 {
3225 int64 avgSpace = groupInfo->totalDiskSpaceUsed / groupInfo->groupCount;
3226
3227 const char *spaceTypeName;
3228
3229 spaceTypeName = tuplesort_space_type_name(SORT_SPACE_TYPE_DISK);
3230 appendStringInfo(es->str, " Average %s: " INT64_FORMAT "kB Peak %s: " INT64_FORMAT "kB",
3231 spaceTypeName, avgSpace,
3232 spaceTypeName, groupInfo->maxDiskSpaceUsed);
3233 }
3234 }
3235 else
3236 {
3237 StringInfoData groupName;
3238
3239 initStringInfo(&groupName);
3240 appendStringInfo(&groupName, "%s Groups", groupLabel);
3241 ExplainOpenGroup("Incremental Sort Groups", groupName.data, true, es);
3242 ExplainPropertyInteger("Group Count", NULL, groupInfo->groupCount, es);
3243
3244 ExplainPropertyList("Sort Methods Used", methodNames, es);
3245
3246 if (groupInfo->maxMemorySpaceUsed > 0)
3247 {
3248 int64 avgSpace = groupInfo->totalMemorySpaceUsed / groupInfo->groupCount;
3249 const char *spaceTypeName;
3250 StringInfoData memoryName;
3251
3252 spaceTypeName = tuplesort_space_type_name(SORT_SPACE_TYPE_MEMORY);
3253 initStringInfo(&memoryName);
3254 appendStringInfo(&memoryName, "Sort Space %s", spaceTypeName);
3255 ExplainOpenGroup("Sort Space", memoryName.data, true, es);
3256
3257 ExplainPropertyInteger("Average Sort Space Used", "kB", avgSpace, es);
3258 ExplainPropertyInteger("Peak Sort Space Used", "kB",
3259 groupInfo->maxMemorySpaceUsed, es);
3260
3261 ExplainCloseGroup("Sort Space", memoryName.data, true, es);
3262 }
3263 if (groupInfo->maxDiskSpaceUsed > 0)
3264 {
3265 int64 avgSpace = groupInfo->totalDiskSpaceUsed / groupInfo->groupCount;
3266 const char *spaceTypeName;
3267 StringInfoData diskName;
3268
3269 spaceTypeName = tuplesort_space_type_name(SORT_SPACE_TYPE_DISK);
3270 initStringInfo(&diskName);
3271 appendStringInfo(&diskName, "Sort Space %s", spaceTypeName);
3272 ExplainOpenGroup("Sort Space", diskName.data, true, es);
3273
3274 ExplainPropertyInteger("Average Sort Space Used", "kB", avgSpace, es);
3275 ExplainPropertyInteger("Peak Sort Space Used", "kB",
3276 groupInfo->maxDiskSpaceUsed, es);
3277
3278 ExplainCloseGroup("Sort Space", diskName.data, true, es);
3279 }
3280
3281 ExplainCloseGroup("Incremental Sort Groups", groupName.data, true, es);
3282 }
3283 }
3284
3285 /*
3286 * If it's EXPLAIN ANALYZE, show tuplesort stats for an incremental sort node
3287 */
3288 static void
3289 show_incremental_sort_info(IncrementalSortState *incrsortstate,
3290 ExplainState *es)
3291 {
3292 IncrementalSortGroupInfo *fullsortGroupInfo;
3293 IncrementalSortGroupInfo *prefixsortGroupInfo;
3294
3295 fullsortGroupInfo = &incrsortstate->incsort_info.fullsortGroupInfo;
3296
3297 if (!es->analyze)
3298 return;
3299
3300 /*
3301 * Since we never have any prefix groups unless we've first sorted a full
3302 * groups and transitioned modes (copying the tuples into a prefix group),
3303 * we don't need to do anything if there were 0 full groups.
3304 *
3305 * We still have to continue after this block if there are no full groups,
3306 * though, since it's possible that we have workers that did real work
3307 * even if the leader didn't participate.
3308 */
3309 if (fullsortGroupInfo->groupCount > 0)
3310 {
3311 show_incremental_sort_group_info(fullsortGroupInfo, "Full-sort", true, es);
3312 prefixsortGroupInfo = &incrsortstate->incsort_info.prefixsortGroupInfo;
3313 if (prefixsortGroupInfo->groupCount > 0)
3314 {
3315 if (es->format == EXPLAIN_FORMAT_TEXT)
3316 appendStringInfoChar(es->str, '\n');
3317 show_incremental_sort_group_info(prefixsortGroupInfo, "Pre-sorted", true, es);
3318 }
3319 if (es->format == EXPLAIN_FORMAT_TEXT)
3320 appendStringInfoChar(es->str, '\n');
3321 }
3322
3323 if (incrsortstate->shared_info != NULL)
3324 {
3325 int n;
3326 bool indent_first_line;
3327
3328 for (n = 0; n < incrsortstate->shared_info->num_workers; n++)
3329 {
3330 IncrementalSortInfo *incsort_info =
3331 &incrsortstate->shared_info->sinfo[n];
3332
3333 /*
3334 * If a worker hasn't processed any sort groups at all, then
3335 * exclude it from output since it either didn't launch or didn't
3336 * contribute anything meaningful.
3337 */
3338 fullsortGroupInfo = &incsort_info->fullsortGroupInfo;
3339
3340 /*
3341 * Since we never have any prefix groups unless we've first sorted
3342 * a full groups and transitioned modes (copying the tuples into a
3343 * prefix group), we don't need to do anything if there were 0
3344 * full groups.
3345 */
3346 if (fullsortGroupInfo->groupCount == 0)
3347 continue;
3348
3349 if (es->workers_state)
3350 ExplainOpenWorker(n, es);
3351
3352 indent_first_line = es->workers_state == NULL || es->verbose;
3353 show_incremental_sort_group_info(fullsortGroupInfo, "Full-sort",
3354 indent_first_line, es);
3355 prefixsortGroupInfo = &incsort_info->prefixsortGroupInfo;
3356 if (prefixsortGroupInfo->groupCount > 0)
3357 {
3358 if (es->format == EXPLAIN_FORMAT_TEXT)
3359 appendStringInfoChar(es->str, '\n');
3360 show_incremental_sort_group_info(prefixsortGroupInfo, "Pre-sorted", true, es);
3361 }
3362 if (es->format == EXPLAIN_FORMAT_TEXT)
3363 appendStringInfoChar(es->str, '\n');
3364
3365 if (es->workers_state)
3366 ExplainCloseWorker(n, es);
3367 }
3368 }
3369 }
3370
3371 /*
3372 * Show information on hash buckets/batches.
3373 */
3374 static void
3375 show_hash_info(HashState *hashstate, ExplainState *es)
3376 {
3377 HashInstrumentation hinstrument = {0};
3378
3379 /*
3380 * Collect stats from the local process, even when it's a parallel query.
3381 * In a parallel query, the leader process may or may not have run the
3382 * hash join, and even if it did it may not have built a hash table due to
3383 * timing (if it started late it might have seen no tuples in the outer
3384 * relation and skipped building the hash table). Therefore we have to be
3385 * prepared to get instrumentation data from all participants.
3386 */
3387 if (hashstate->hinstrument)
3388 memcpy(&hinstrument, hashstate->hinstrument,
3389 sizeof(HashInstrumentation));
3390
3391 /*
3392 * Merge results from workers. In the parallel-oblivious case, the
3393 * results from all participants should be identical, except where
3394 * participants didn't run the join at all so have no data. In the
3395 * parallel-aware case, we need to consider all the results. Each worker
3396 * may have seen a different subset of batches and we want to report the
3397 * highest memory usage across all batches. We take the maxima of other
3398 * values too, for the same reasons as in ExecHashAccumInstrumentation.
3399 */
3400 if (hashstate->shared_info)
3401 {
3402 SharedHashInfo *shared_info = hashstate->shared_info;
3403 int i;
3404
3405 for (i = 0; i < shared_info->num_workers; ++i)
3406 {
3407 HashInstrumentation *worker_hi = &shared_info->hinstrument[i];
3408
3409 hinstrument.nbuckets = Max(hinstrument.nbuckets,
3410 worker_hi->nbuckets);
3411 hinstrument.nbuckets_original = Max(hinstrument.nbuckets_original,
3412 worker_hi->nbuckets_original);
3413 hinstrument.nbatch = Max(hinstrument.nbatch,
3414 worker_hi->nbatch);
3415 hinstrument.nbatch_original = Max(hinstrument.nbatch_original,
3416 worker_hi->nbatch_original);
3417 hinstrument.space_peak = Max(hinstrument.space_peak,
3418 worker_hi->space_peak);
3419 }
3420 }
3421
3422 if (hinstrument.nbatch > 0)
3423 {
3424 uint64 spacePeakKb = BYTES_TO_KILOBYTES(hinstrument.space_peak);
3425
3426 if (es->format != EXPLAIN_FORMAT_TEXT)
3427 {
3428 ExplainPropertyInteger("Hash Buckets", NULL,
3429 hinstrument.nbuckets, es);
3430 ExplainPropertyInteger("Original Hash Buckets", NULL,
3431 hinstrument.nbuckets_original, es);
3432 ExplainPropertyInteger("Hash Batches", NULL,
3433 hinstrument.nbatch, es);
3434 ExplainPropertyInteger("Original Hash Batches", NULL,
3435 hinstrument.nbatch_original, es);
3436 ExplainPropertyUInteger("Peak Memory Usage", "kB",
3437 spacePeakKb, es);
3438 }
3439 else if (hinstrument.nbatch_original != hinstrument.nbatch ||
3440 hinstrument.nbuckets_original != hinstrument.nbuckets)
3441 {
3442 ExplainIndentText(es);
3443 appendStringInfo(es->str,
3444 "Buckets: %d (originally %d) Batches: %d (originally %d) Memory Usage: " UINT64_FORMAT "kB\n",
3445 hinstrument.nbuckets,
3446 hinstrument.nbuckets_original,
3447 hinstrument.nbatch,
3448 hinstrument.nbatch_original,
3449 spacePeakKb);
3450 }
3451 else
3452 {
3453 ExplainIndentText(es);
3454 appendStringInfo(es->str,
3455 "Buckets: %d Batches: %d Memory Usage: " UINT64_FORMAT "kB\n",
3456 hinstrument.nbuckets, hinstrument.nbatch,
3457 spacePeakKb);
3458 }
3459 }
3460 }
3461
3462 /*
3463 * Show information on material node, storage method and maximum memory/disk
3464 * space used.
3465 */
3466 static void
3467 show_material_info(MaterialState *mstate, ExplainState *es)
3468 {
3469 char *maxStorageType;
3470 int64 maxSpaceUsed;
3471
3472 Tuplestorestate *tupstore = mstate->tuplestorestate;
3473
3474 /*
3475 * Nothing to show if ANALYZE option wasn't used or if execution didn't
3476 * get as far as creating the tuplestore.
3477 */
3478 if (!es->analyze || tupstore == NULL)
3479 return;
3480
3481 tuplestore_get_stats(tupstore, &maxStorageType, &maxSpaceUsed);
3482 show_storage_info(maxStorageType, maxSpaceUsed, es);
3483 }
3484
3485 /*
3486 * Show information on WindowAgg node, storage method and maximum memory/disk
3487 * space used.
3488 */
3489 static void
3490 show_windowagg_info(WindowAggState *winstate, ExplainState *es)
3491 {
3492 char *maxStorageType;
3493 int64 maxSpaceUsed;
3494
3495 Tuplestorestate *tupstore = winstate->buffer;
3496
3497 /*
3498 * Nothing to show if ANALYZE option wasn't used or if execution didn't
3499 * get as far as creating the tuplestore.
3500 */
3501 if (!es->analyze || tupstore == NULL)
3502 return;
3503
3504 tuplestore_get_stats(tupstore, &maxStorageType, &maxSpaceUsed);
3505 show_storage_info(maxStorageType, maxSpaceUsed, es);
3506 }
3507
3508 /*
3509 * Show information on CTE Scan node, storage method and maximum memory/disk
3510 * space used.
3511 */
3512 static void
3513 show_ctescan_info(CteScanState *ctescanstate, ExplainState *es)
3514 {
3515 char *maxStorageType;
3516 int64 maxSpaceUsed;
3517
3518 Tuplestorestate *tupstore = ctescanstate->leader->cte_table;
3519
3520 if (!es->analyze || tupstore == NULL)
3521 return;
3522
3523 tuplestore_get_stats(tupstore, &maxStorageType, &maxSpaceUsed);
3524 show_storage_info(maxStorageType, maxSpaceUsed, es);
3525 }
3526
3527 /*
3528 * Show information on Table Function Scan node, storage method and maximum
3529 * memory/disk space used.
3530 */
3531 static void
3532 show_table_func_scan_info(TableFuncScanState *tscanstate, ExplainState *es)
3533 {
3534 char *maxStorageType;
3535 int64 maxSpaceUsed;
3536
3537 Tuplestorestate *tupstore = tscanstate->tupstore;
3538
3539 if (!es->analyze || tupstore == NULL)
3540 return;
3541
3542 tuplestore_get_stats(tupstore, &maxStorageType, &maxSpaceUsed);
3543 show_storage_info(maxStorageType, maxSpaceUsed, es);
3544 }
3545
3546 /*
3547 * Show information on Recursive Union node, storage method and maximum
3548 * memory/disk space used.
3549 */
3550 static void
3551 show_recursive_union_info(RecursiveUnionState *rstate, ExplainState *es)
3552 {
3553 char *maxStorageType,
3554 *tempStorageType;
3555 int64 maxSpaceUsed,
3556 tempSpaceUsed;
3557
3558 if (!es->analyze)
3559 return;
3560
3561 /*
3562 * Recursive union node uses two tuplestores. We employ the storage type
3563 * from one of them which consumed more memory/disk than the other. The
3564 * storage size is sum of the two.
3565 */
3566 tuplestore_get_stats(rstate->working_table, &tempStorageType,
3567 &tempSpaceUsed);
3568 tuplestore_get_stats(rstate->intermediate_table, &maxStorageType,
3569 &maxSpaceUsed);
3570
3571 if (tempSpaceUsed > maxSpaceUsed)
3572 maxStorageType = tempStorageType;
3573
3574 maxSpaceUsed += tempSpaceUsed;
3575 show_storage_info(maxStorageType, maxSpaceUsed, es);
3576 }
3577
3578 /*
3579 * Show information on memoize hits/misses/evictions and memory usage.
3580 */
3581 static void
3582 show_memoize_info(MemoizeState *mstate, List *ancestors, ExplainState *es)
3583 {
3584 Plan *plan = ((PlanState *) mstate)->plan;
3585 ListCell *lc;
3586 List *context;
3587 StringInfoData keystr;
3588 char *separator = "";
3589 bool useprefix;
3590 int64 memPeakKb;
3591
3592 initStringInfo(&keystr);
3593
3594 /*
3595 * It's hard to imagine having a memoize node with fewer than 2 RTEs, but
3596 * let's just keep the same useprefix logic as elsewhere in this file.
3597 */
3598 useprefix = es->rtable_size > 1 || es->verbose;
3599
3600 /* Set up deparsing context */
3601 context = set_deparse_context_plan(es->deparse_cxt,
3602 plan,
3603 ancestors);
3604
3605 foreach(lc, ((Memoize *) plan)->param_exprs)
3606 {
3607 Node *expr = (Node *) lfirst(lc);
3608
3609 appendStringInfoString(&keystr, separator);
3610
3611 appendStringInfoString(&keystr, deparse_expression(expr, context,
3612 useprefix, false));
3613 separator = ", ";
3614 }
3615
3616 ExplainPropertyText("Cache Key", keystr.data, es);
3617 ExplainPropertyText("Cache Mode", mstate->binary_mode ? "binary" : "logical", es);
3618
3619 pfree(keystr.data);
3620
3621 if (!es->analyze)
3622 return;
3623
3624 if (mstate->stats.cache_misses > 0)
3625 {
3626 /*
3627 * mem_peak is only set when we freed memory, so we must use mem_used
3628 * when mem_peak is 0.
3629 */
3630 if (mstate->stats.mem_peak > 0)
3631 memPeakKb = BYTES_TO_KILOBYTES(mstate->stats.mem_peak);
3632 else
3633 memPeakKb = BYTES_TO_KILOBYTES(mstate->mem_used);
3634
3635 if (es->format != EXPLAIN_FORMAT_TEXT)
3636 {
3637 ExplainPropertyInteger("Cache Hits", NULL, mstate->stats.cache_hits, es);
3638 ExplainPropertyInteger("Cache Misses", NULL, mstate->stats.cache_misses, es);
3639 ExplainPropertyInteger("Cache Evictions", NULL, mstate->stats.cache_evictions, es);
3640 ExplainPropertyInteger("Cache Overflows", NULL, mstate->stats.cache_overflows, es);
3641 ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb, es);
3642 }
3643 else
3644 {
3645 ExplainIndentText(es);
3646 appendStringInfo(es->str,
3647 "Hits: " UINT64_FORMAT " Misses: " UINT64_FORMAT " Evictions: " UINT64_FORMAT " Overflows: " UINT64_FORMAT " Memory Usage: " INT64_FORMAT "kB\n",
3648 mstate->stats.cache_hits,
3649 mstate->stats.cache_misses,
3650 mstate->stats.cache_evictions,
3651 mstate->stats.cache_overflows,
3652 memPeakKb);
3653 }
3654 }
3655
3656 if (mstate->shared_info == NULL)
3657 return;
3658
3659 /* Show details from parallel workers */
3660 for (int n = 0; n < mstate->shared_info->num_workers; n++)
3661 {
3662 MemoizeInstrumentation *si;
3663
3664 si = &mstate->shared_info->sinstrument[n];
3665
3666 /*
3667 * Skip workers that didn't do any work. We needn't bother checking
3668 * for cache hits as a miss will always occur before a cache hit.
3669 */
3670 if (si->cache_misses == 0)
3671 continue;
3672
3673 if (es->workers_state)
3674 ExplainOpenWorker(n, es);
3675
3676 /*
3677 * Since the worker's MemoizeState.mem_used field is unavailable to
3678 * us, ExecEndMemoize will have set the
3679 * MemoizeInstrumentation.mem_peak field for us. No need to do the
3680 * zero checks like we did for the serial case above.
3681 */
3682 memPeakKb = BYTES_TO_KILOBYTES(si->mem_peak);
3683
3684 if (es->format == EXPLAIN_FORMAT_TEXT)
3685 {
3686 ExplainIndentText(es);
3687 appendStringInfo(es->str,
3688 "Hits: " UINT64_FORMAT " Misses: " UINT64_FORMAT " Evictions: " UINT64_FORMAT " Overflows: " UINT64_FORMAT " Memory Usage: " INT64_FORMAT "kB\n",
3689 si->cache_hits, si->cache_misses,
3690 si->cache_evictions, si->cache_overflows,
3691 memPeakKb);
3692 }
3693 else
3694 {
3695 ExplainPropertyInteger("Cache Hits", NULL,
3696 si->cache_hits, es);
3697 ExplainPropertyInteger("Cache Misses", NULL,
3698 si->cache_misses, es);
3699 ExplainPropertyInteger("Cache Evictions", NULL,
3700 si->cache_evictions, es);
3701 ExplainPropertyInteger("Cache Overflows", NULL,
3702 si->cache_overflows, es);
3703 ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb,
3704 es);
3705 }
3706
3707 if (es->workers_state)
3708 ExplainCloseWorker(n, es);
3709 }
3710 }
3711
3712 /*
3713 * Show information on hash aggregate memory usage and batches.
3714 */
3715 static void
3716 show_hashagg_info(AggState *aggstate, ExplainState *es)
3717 {
3718 Agg *agg = (Agg *) aggstate->ss.ps.plan;
3719 int64 memPeakKb = BYTES_TO_KILOBYTES(aggstate->hash_mem_peak);
3720
3721 if (agg->aggstrategy != AGG_HASHED &&
3722 agg->aggstrategy != AGG_MIXED)
3723 return;
3724
3725 if (es->format != EXPLAIN_FORMAT_TEXT)
3726 {
3727 if (es->costs)
3728 ExplainPropertyInteger("Planned Partitions", NULL,
3729 aggstate->hash_planned_partitions, es);
3730
3731 /*
3732 * During parallel query the leader may have not helped out. We
3733 * detect this by checking how much memory it used. If we find it
3734 * didn't do any work then we don't show its properties.
3735 */
3736 if (es->analyze && aggstate->hash_mem_peak > 0)
3737 {
3738 ExplainPropertyInteger("HashAgg Batches", NULL,
3739 aggstate->hash_batches_used, es);
3740 ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb, es);
3741 ExplainPropertyInteger("Disk Usage", "kB",
3742 aggstate->hash_disk_used, es);
3743 }
3744 }
3745 else
3746 {
3747 bool gotone = false;
3748
3749 if (es->costs && aggstate->hash_planned_partitions > 0)
3750 {
3751 ExplainIndentText(es);
3752 appendStringInfo(es->str, "Planned Partitions: %d",
3753 aggstate->hash_planned_partitions);
3754 gotone = true;
3755 }
3756
3757 /*
3758 * During parallel query the leader may have not helped out. We
3759 * detect this by checking how much memory it used. If we find it
3760 * didn't do any work then we don't show its properties.
3761 */
3762 if (es->analyze && aggstate->hash_mem_peak > 0)
3763 {
3764 if (!gotone)
3765 ExplainIndentText(es);
3766 else
3767 appendStringInfoSpaces(es->str, 2);
3768
3769 appendStringInfo(es->str, "Batches: %d Memory Usage: " INT64_FORMAT "kB",
3770 aggstate->hash_batches_used, memPeakKb);
3771 gotone = true;
3772
3773 /* Only display disk usage if we spilled to disk */
3774 if (aggstate->hash_batches_used > 1)
3775 {
3776 appendStringInfo(es->str, " Disk Usage: " UINT64_FORMAT "kB",
3777 aggstate->hash_disk_used);
3778 }
3779 }
3780
3781 if (gotone)
3782 appendStringInfoChar(es->str, '\n');
3783 }
3784
3785 /* Display stats for each parallel worker */
3786 if (es->analyze && aggstate->shared_info != NULL)
3787 {
3788 for (int n = 0; n < aggstate->shared_info->num_workers; n++)
3789 {
3790 AggregateInstrumentation *sinstrument;
3791 uint64 hash_disk_used;
3792 int hash_batches_used;
3793
3794 sinstrument = &aggstate->shared_info->sinstrument[n];
3795 /* Skip workers that didn't do anything */
3796 if (sinstrument->hash_mem_peak == 0)
3797 continue;
3798 hash_disk_used = sinstrument->hash_disk_used;
3799 hash_batches_used = sinstrument->hash_batches_used;
3800 memPeakKb = BYTES_TO_KILOBYTES(sinstrument->hash_mem_peak);
3801
3802 if (es->workers_state)
3803 ExplainOpenWorker(n, es);
3804
3805 if (es->format == EXPLAIN_FORMAT_TEXT)
3806 {
3807 ExplainIndentText(es);
3808
3809 appendStringInfo(es->str, "Batches: %d Memory Usage: " INT64_FORMAT "kB",
3810 hash_batches_used, memPeakKb);
3811
3812 /* Only display disk usage if we spilled to disk */
3813 if (hash_batches_used > 1)
3814 appendStringInfo(es->str, " Disk Usage: " UINT64_FORMAT "kB",
3815 hash_disk_used);
3816 appendStringInfoChar(es->str, '\n');
3817 }
3818 else
3819 {
3820 ExplainPropertyInteger("HashAgg Batches", NULL,
3821 hash_batches_used, es);
3822 ExplainPropertyInteger("Peak Memory Usage", "kB", memPeakKb,
3823 es);
3824 ExplainPropertyInteger("Disk Usage", "kB", hash_disk_used, es);
3825 }
3826
3827 if (es->workers_state)
3828 ExplainCloseWorker(n, es);
3829 }
3830 }
3831 }
3832
3833 /*
3834 * Show the total number of index searches for a
3835 * IndexScan/IndexOnlyScan/BitmapIndexScan node
3836 */
3837 static void
3838 show_indexsearches_info(PlanState *planstate, ExplainState *es)
3839 {
3840 Plan *plan = planstate->plan;
3841 SharedIndexScanInstrumentation *SharedInfo = NULL;
3842 uint64 nsearches = 0;
3843
3844 if (!es->analyze)
3845 return;
3846
3847 /* Initialize counters with stats from the local process first */
3848 switch (nodeTag(plan))
3849 {
3850 case T_IndexScan:
3851 {
3852 IndexScanState *indexstate = ((IndexScanState *) planstate);
3853
3854 nsearches = indexstate->iss_Instrument.nsearches;
3855 SharedInfo = indexstate->iss_SharedInfo;
3856 break;
3857 }
3858 case T_IndexOnlyScan:
3859 {
3860 IndexOnlyScanState *indexstate = ((IndexOnlyScanState *) planstate);
3861
3862 nsearches = indexstate->ioss_Instrument.nsearches;
3863 SharedInfo = indexstate->ioss_SharedInfo;
3864 break;
3865 }
3866 case T_BitmapIndexScan:
3867 {
3868 BitmapIndexScanState *indexstate = ((BitmapIndexScanState *) planstate);
3869
3870 nsearches = indexstate->biss_Instrument.nsearches;
3871 SharedInfo = indexstate->biss_SharedInfo;
3872 break;
3873 }
3874 default:
3875 break;
3876 }
3877
3878 /* Next get the sum of the counters set within each and every process */
3879 if (SharedInfo)
3880 {
3881 for (int i = 0; i < SharedInfo->num_workers; ++i)
3882 {
3883 IndexScanInstrumentation *winstrument = &SharedInfo->winstrument[i];
3884
3885 nsearches += winstrument->nsearches;
3886 }
3887 }
3888
3889 ExplainPropertyUInteger("Index Searches", NULL, nsearches, es);
3890 }
3891
3892 /*
3893 * Show exact/lossy pages for a BitmapHeapScan node
3894 */
3895 static void
3896 show_tidbitmap_info(BitmapHeapScanState *planstate, ExplainState *es)
3897 {
3898 if (!es->analyze)
3899 return;
3900
3901 if (es->format != EXPLAIN_FORMAT_TEXT)
3902 {
3903 ExplainPropertyUInteger("Exact Heap Blocks", NULL,
3904 planstate->stats.exact_pages, es);
3905 ExplainPropertyUInteger("Lossy Heap Blocks", NULL,
3906 planstate->stats.lossy_pages, es);
3907 }
3908 else
3909 {
3910 if (planstate->stats.exact_pages > 0 || planstate->stats.lossy_pages > 0)
3911 {
3912 ExplainIndentText(es);
3913 appendStringInfoString(es->str, "Heap Blocks:");
3914 if (planstate->stats.exact_pages > 0)
3915 appendStringInfo(es->str, " exact=" UINT64_FORMAT, planstate->stats.exact_pages);
3916 if (planstate->stats.lossy_pages > 0)
3917 appendStringInfo(es->str, " lossy=" UINT64_FORMAT, planstate->stats.lossy_pages);
3918 appendStringInfoChar(es->str, '\n');
3919 }
3920 }
3921
3922 /* Display stats for each parallel worker */
3923 if (planstate->pstate != NULL)
3924 {
3925 for (int n = 0; n < planstate->sinstrument->num_workers; n++)
3926 {
3927 BitmapHeapScanInstrumentation *si = &planstate->sinstrument->sinstrument[n];
3928
3929 if (si->exact_pages == 0 && si->lossy_pages == 0)
3930 continue;
3931
3932 if (es->workers_state)
3933 ExplainOpenWorker(n, es);
3934
3935 if (es->format == EXPLAIN_FORMAT_TEXT)
3936 {
3937 ExplainIndentText(es);
3938 appendStringInfoString(es->str, "Heap Blocks:");
3939 if (si->exact_pages > 0)
3940 appendStringInfo(es->str, " exact=" UINT64_FORMAT, si->exact_pages);
3941 if (si->lossy_pages > 0)
3942 appendStringInfo(es->str, " lossy=" UINT64_FORMAT, si->lossy_pages);
3943 appendStringInfoChar(es->str, '\n');
3944 }
3945 else
3946 {
3947 ExplainPropertyUInteger("Exact Heap Blocks", NULL,
3948 si->exact_pages, es);
3949 ExplainPropertyUInteger("Lossy Heap Blocks", NULL,
3950 si->lossy_pages, es);
3951 }
3952
3953 if (es->workers_state)
3954 ExplainCloseWorker(n, es);
3955 }
3956 }
3957 }
3958
3959 /*
3960 * If it's EXPLAIN ANALYZE, show instrumentation information for a plan node
3961 *
3962 * "which" identifies which instrumentation counter to print
3963 */
3964 static void
3965 show_instrumentation_count(const char *qlabel, int which,
3966 PlanState *planstate, ExplainState *es)
3967 {
3968 double nfiltered;
3969 double nloops;
3970
3971 if (!es->analyze || !planstate->instrument)
3972 return;
3973
3974 if (which == 2)
3975 nfiltered = planstate->instrument->nfiltered2;
3976 else
3977 nfiltered = planstate->instrument->nfiltered1;
3978 nloops = planstate->instrument->nloops;
3979
3980 /* In text mode, suppress zero counts; they're not interesting enough */
3981 if (nfiltered > 0 || es->format != EXPLAIN_FORMAT_TEXT)
3982 {
3983 if (nloops > 0)
3984 ExplainPropertyFloat(qlabel, NULL, nfiltered / nloops, 0, es);
3985 else
3986 ExplainPropertyFloat(qlabel, NULL, 0.0, 0, es);
3987 }
3988 }
3989
3990 /*
3991 * Show extra information for a ForeignScan node.
3992 */
3993 static void
3994 show_foreignscan_info(ForeignScanState *fsstate, ExplainState *es)
3995 {
3996 FdwRoutine *fdwroutine = fsstate->fdwroutine;
3997
3998 /* Let the FDW emit whatever fields it wants */
3999 if (((ForeignScan *) fsstate->ss.ps.plan)->operation != CMD_SELECT)
4000 {
4001 if (fdwroutine->ExplainDirectModify != NULL)
4002 fdwroutine->ExplainDirectModify(fsstate, es);
4003 }
4004 else
4005 {
4006 if (fdwroutine->ExplainForeignScan != NULL)
4007 fdwroutine->ExplainForeignScan(fsstate, es);
4008 }
4009 }
4010
4011 /*
4012 * Fetch the name of an index in an EXPLAIN
4013 *
4014 * We allow plugins to get control here so that plans involving hypothetical
4015 * indexes can be explained.
4016 *
4017 * Note: names returned by this function should be "raw"; the caller will
4018 * apply quoting if needed. Formerly the convention was to do quoting here,
4019 * but we don't want that in non-text output formats.
4020 */
4021 static const char *
4022 explain_get_index_name(Oid indexId)
4023 {
4024 const char *result;
4025
4026 if (explain_get_index_name_hook)
4027 result = (*explain_get_index_name_hook) (indexId);
4028 else
4029 result = NULL;
4030 if (result == NULL)
4031 {
4032 /* default behavior: look it up in the catalogs */
4033 result = get_rel_name(indexId);
4034 if (result == NULL)
4035 elog(ERROR, "cache lookup failed for index %u", indexId);
4036 }
4037 return result;
4038 }
4039
4040 /*
4041 * Return whether show_buffer_usage would have anything to print, if given
4042 * the same 'usage' data. Note that when the format is anything other than
4043 * text, we print even if the counters are all zeroes.
4044 */
4045 static bool
4046 peek_buffer_usage(ExplainState *es, const BufferUsage *usage)
4047 {
4048 bool has_shared;
4049 bool has_local;
4050 bool has_temp;
4051 bool has_shared_timing;
4052 bool has_local_timing;
4053 bool has_temp_timing;
4054
4055 if (usage == NULL)
4056 return false;
4057
4058 if (es->format != EXPLAIN_FORMAT_TEXT)
4059 return true;
4060
4061 has_shared = (usage->shared_blks_hit > 0 ||
4062 usage->shared_blks_read > 0 ||
4063 usage->shared_blks_dirtied > 0 ||
4064 usage->shared_blks_written > 0);
4065 has_local = (usage->local_blks_hit > 0 ||
4066 usage->local_blks_read > 0 ||
4067 usage->local_blks_dirtied > 0 ||
4068 usage->local_blks_written > 0);
4069 has_temp = (usage->temp_blks_read > 0 ||
4070 usage->temp_blks_written > 0);
4071 has_shared_timing = (!INSTR_TIME_IS_ZERO(usage->shared_blk_read_time) ||
4072 !INSTR_TIME_IS_ZERO(usage->shared_blk_write_time));
4073 has_local_timing = (!INSTR_TIME_IS_ZERO(usage->local_blk_read_time) ||
4074 !INSTR_TIME_IS_ZERO(usage->local_blk_write_time));
4075 has_temp_timing = (!INSTR_TIME_IS_ZERO(usage->temp_blk_read_time) ||
4076 !INSTR_TIME_IS_ZERO(usage->temp_blk_write_time));
4077
4078 return has_shared || has_local || has_temp || has_shared_timing ||
4079 has_local_timing || has_temp_timing;
4080 }
4081
4082 /*
4083 * Show buffer usage details. This better be sync with peek_buffer_usage.
4084 */
4085 static void
4086 show_buffer_usage(ExplainState *es, const BufferUsage *usage)
4087 {
4088 if (es->format == EXPLAIN_FORMAT_TEXT)
4089 {
4090 bool has_shared = (usage->shared_blks_hit > 0 ||
4091 usage->shared_blks_read > 0 ||
4092 usage->shared_blks_dirtied > 0 ||
4093 usage->shared_blks_written > 0);
4094 bool has_local = (usage->local_blks_hit > 0 ||
4095 usage->local_blks_read > 0 ||
4096 usage->local_blks_dirtied > 0 ||
4097 usage->local_blks_written > 0);
4098 bool has_temp = (usage->temp_blks_read > 0 ||
4099 usage->temp_blks_written > 0);
4100 bool has_shared_timing = (!INSTR_TIME_IS_ZERO(usage->shared_blk_read_time) ||
4101 !INSTR_TIME_IS_ZERO(usage->shared_blk_write_time));
4102 bool has_local_timing = (!INSTR_TIME_IS_ZERO(usage->local_blk_read_time) ||
4103 !INSTR_TIME_IS_ZERO(usage->local_blk_write_time));
4104 bool has_temp_timing = (!INSTR_TIME_IS_ZERO(usage->temp_blk_read_time) ||
4105 !INSTR_TIME_IS_ZERO(usage->temp_blk_write_time));
4106
4107 /* Show only positive counter values. */
4108 if (has_shared || has_local || has_temp)
4109 {
4110 ExplainIndentText(es);
4111 appendStringInfoString(es->str, "Buffers:");
4112
4113 if (has_shared)
4114 {
4115 appendStringInfoString(es->str, " shared");
4116 if (usage->shared_blks_hit > 0)
4117 appendStringInfo(es->str, " hit=%" PRId64,
4118 usage->shared_blks_hit);
4119 if (usage->shared_blks_read > 0)
4120 appendStringInfo(es->str, " read=%" PRId64,
4121 usage->shared_blks_read);
4122 if (usage->shared_blks_dirtied > 0)
4123 appendStringInfo(es->str, " dirtied=%" PRId64,
4124 usage->shared_blks_dirtied);
4125 if (usage->shared_blks_written > 0)
4126 appendStringInfo(es->str, " written=%" PRId64,
4127 usage->shared_blks_written);
4128 if (has_local || has_temp)
4129 appendStringInfoChar(es->str, ',');
4130 }
4131 if (has_local)
4132 {
4133 appendStringInfoString(es->str, " local");
4134 if (usage->local_blks_hit > 0)
4135 appendStringInfo(es->str, " hit=%" PRId64,
4136 usage->local_blks_hit);
4137 if (usage->local_blks_read > 0)
4138 appendStringInfo(es->str, " read=%" PRId64,
4139 usage->local_blks_read);
4140 if (usage->local_blks_dirtied > 0)
4141 appendStringInfo(es->str, " dirtied=%" PRId64,
4142 usage->local_blks_dirtied);
4143 if (usage->local_blks_written > 0)
4144 appendStringInfo(es->str, " written=%" PRId64,
4145 usage->local_blks_written);
4146 if (has_temp)
4147 appendStringInfoChar(es->str, ',');
4148 }
4149 if (has_temp)
4150 {
4151 appendStringInfoString(es->str, " temp");
4152 if (usage->temp_blks_read > 0)
4153 appendStringInfo(es->str, " read=%" PRId64,
4154 usage->temp_blks_read);
4155 if (usage->temp_blks_written > 0)
4156 appendStringInfo(es->str, " written=%" PRId64,
4157 usage->temp_blks_written);
4158 }
4159 appendStringInfoChar(es->str, '\n');
4160 }
4161
4162 /* As above, show only positive counter values. */
4163 if (has_shared_timing || has_local_timing || has_temp_timing)
4164 {
4165 ExplainIndentText(es);
4166 appendStringInfoString(es->str, "I/O Timings:");
4167
4168 if (has_shared_timing)
4169 {
4170 appendStringInfoString(es->str, " shared");
4171 if (!INSTR_TIME_IS_ZERO(usage->shared_blk_read_time))
4172 appendStringInfo(es->str, " read=%0.3f",
4173 INSTR_TIME_GET_MILLISEC(usage->shared_blk_read_time));
4174 if (!INSTR_TIME_IS_ZERO(usage->shared_blk_write_time))
4175 appendStringInfo(es->str, " write=%0.3f",
4176 INSTR_TIME_GET_MILLISEC(usage->shared_blk_write_time));
4177 if (has_local_timing || has_temp_timing)
4178 appendStringInfoChar(es->str, ',');
4179 }
4180 if (has_local_timing)
4181 {
4182 appendStringInfoString(es->str, " local");
4183 if (!INSTR_TIME_IS_ZERO(usage->local_blk_read_time))
4184 appendStringInfo(es->str, " read=%0.3f",
4185 INSTR_TIME_GET_MILLISEC(usage->local_blk_read_time));
4186 if (!INSTR_TIME_IS_ZERO(usage->local_blk_write_time))
4187 appendStringInfo(es->str, " write=%0.3f",
4188 INSTR_TIME_GET_MILLISEC(usage->local_blk_write_time));
4189 if (has_temp_timing)
4190 appendStringInfoChar(es->str, ',');
4191 }
4192 if (has_temp_timing)
4193 {
4194 appendStringInfoString(es->str, " temp");
4195 if (!INSTR_TIME_IS_ZERO(usage->temp_blk_read_time))
4196 appendStringInfo(es->str, " read=%0.3f",
4197 INSTR_TIME_GET_MILLISEC(usage->temp_blk_read_time));
4198 if (!INSTR_TIME_IS_ZERO(usage->temp_blk_write_time))
4199 appendStringInfo(es->str, " write=%0.3f",
4200 INSTR_TIME_GET_MILLISEC(usage->temp_blk_write_time));
4201 }
4202 appendStringInfoChar(es->str, '\n');
4203 }
4204 }
4205 else
4206 {
4207 ExplainPropertyInteger("Shared Hit Blocks", NULL,
4208 usage->shared_blks_hit, es);
4209 ExplainPropertyInteger("Shared Read Blocks", NULL,
4210 usage->shared_blks_read, es);
4211 ExplainPropertyInteger("Shared Dirtied Blocks", NULL,
4212 usage->shared_blks_dirtied, es);
4213 ExplainPropertyInteger("Shared Written Blocks", NULL,
4214 usage->shared_blks_written, es);
4215 ExplainPropertyInteger("Local Hit Blocks", NULL,
4216 usage->local_blks_hit, es);
4217 ExplainPropertyInteger("Local Read Blocks", NULL,
4218 usage->local_blks_read, es);
4219 ExplainPropertyInteger("Local Dirtied Blocks", NULL,
4220 usage->local_blks_dirtied, es);
4221 ExplainPropertyInteger("Local Written Blocks", NULL,
4222 usage->local_blks_written, es);
4223 ExplainPropertyInteger("Temp Read Blocks", NULL,
4224 usage->temp_blks_read, es);
4225 ExplainPropertyInteger("Temp Written Blocks", NULL,
4226 usage->temp_blks_written, es);
4227 if (track_io_timing)
4228 {
4229 ExplainPropertyFloat("Shared I/O Read Time", "ms",
4230 INSTR_TIME_GET_MILLISEC(usage->shared_blk_read_time),
4231 3, es);
4232 ExplainPropertyFloat("Shared I/O Write Time", "ms",
4233 INSTR_TIME_GET_MILLISEC(usage->shared_blk_write_time),
4234 3, es);
4235 ExplainPropertyFloat("Local I/O Read Time", "ms",
4236 INSTR_TIME_GET_MILLISEC(usage->local_blk_read_time),
4237 3, es);
4238 ExplainPropertyFloat("Local I/O Write Time", "ms",
4239 INSTR_TIME_GET_MILLISEC(usage->local_blk_write_time),
4240 3, es);
4241 ExplainPropertyFloat("Temp I/O Read Time", "ms",
4242 INSTR_TIME_GET_MILLISEC(usage->temp_blk_read_time),
4243 3, es);
4244 ExplainPropertyFloat("Temp I/O Write Time", "ms",
4245 INSTR_TIME_GET_MILLISEC(usage->temp_blk_write_time),
4246 3, es);
4247 }
4248 }
4249 }
4250
4251 /*
4252 * Show WAL usage details.
4253 */
4254 static void
4255 show_wal_usage(ExplainState *es, const WalUsage *usage)
4256 {
4257 if (es->format == EXPLAIN_FORMAT_TEXT)
4258 {
4259 /* Show only positive counter values. */
4260 if ((usage->wal_records > 0) || (usage->wal_fpi > 0) ||
4261 (usage->wal_bytes > 0) || (usage->wal_buffers_full > 0))
4262 {
4263 ExplainIndentText(es);
4264 appendStringInfoString(es->str, "WAL:");
4265
4266 if (usage->wal_records > 0)
4267 appendStringInfo(es->str, " records=%" PRId64,
4268 usage->wal_records);
4269 if (usage->wal_fpi > 0)
4270 appendStringInfo(es->str, " fpi=%" PRId64,
4271 usage->wal_fpi);
4272 if (usage->wal_bytes > 0)
4273 appendStringInfo(es->str, " bytes=%" PRIu64,
4274 usage->wal_bytes);
4275 if (usage->wal_buffers_full > 0)
4276 appendStringInfo(es->str, " buffers full=%" PRId64,
4277 usage->wal_buffers_full);
4278 appendStringInfoChar(es->str, '\n');
4279 }
4280 }
4281 else
4282 {
4283 ExplainPropertyInteger("WAL Records", NULL,
4284 usage->wal_records, es);
4285 ExplainPropertyInteger("WAL FPI", NULL,
4286 usage->wal_fpi, es);
4287 ExplainPropertyUInteger("WAL Bytes", NULL,
4288 usage->wal_bytes, es);
4289 ExplainPropertyInteger("WAL Buffers Full", NULL,
4290 usage->wal_buffers_full, es);
4291 }
4292 }
4293
4294 /*
4295 * Show memory usage details.
4296 */
4297 static void
4298 show_memory_counters(ExplainState *es, const MemoryContextCounters *mem_counters)
4299 {
4300 int64 memUsedkB = BYTES_TO_KILOBYTES(mem_counters->totalspace -
4301 mem_counters->freespace);
4302 int64 memAllocatedkB = BYTES_TO_KILOBYTES(mem_counters->totalspace);
4303
4304 if (es->format == EXPLAIN_FORMAT_TEXT)
4305 {
4306 ExplainIndentText(es);
4307 appendStringInfo(es->str,
4308 "Memory: used=" INT64_FORMAT "kB allocated=" INT64_FORMAT "kB",
4309 memUsedkB, memAllocatedkB);
4310 appendStringInfoChar(es->str, '\n');
4311 }
4312 else
4313 {
4314 ExplainPropertyInteger("Memory Used", "kB", memUsedkB, es);
4315 ExplainPropertyInteger("Memory Allocated", "kB", memAllocatedkB, es);
4316 }
4317 }
4318
4319
4320 /*
4321 * Add some additional details about an IndexScan or IndexOnlyScan
4322 */
4323 static void
4324 ExplainIndexScanDetails(Oid indexid, ScanDirection indexorderdir,
4325 ExplainState *es)
4326 {
4327 const char *indexname = explain_get_index_name(indexid);
4328
4329 if (es->format == EXPLAIN_FORMAT_TEXT)
4330 {
4331 if (ScanDirectionIsBackward(indexorderdir))
4332 appendStringInfoString(es->str, " Backward");
4333 appendStringInfo(es->str, " using %s", quote_identifier(indexname));
4334 }
4335 else
4336 {
4337 const char *scandir;
4338
4339 switch (indexorderdir)
4340 {
4341 case BackwardScanDirection:
4342 scandir = "Backward";
4343 break;
4344 case ForwardScanDirection:
4345 scandir = "Forward";
4346 break;
4347 default:
4348 scandir = "???";
4349 break;
4350 }
4351 ExplainPropertyText("Scan Direction", scandir, es);
4352 ExplainPropertyText("Index Name", indexname, es);
4353 }
4354 }
4355
4356 /*
4357 * Show the target of a Scan node
4358 */
4359 static void
4360 ExplainScanTarget(Scan *plan, ExplainState *es)
4361 {
4362 ExplainTargetRel((Plan *) plan, plan->scanrelid, es);
4363 }
4364
4365 /*
4366 * Show the target of a ModifyTable node
4367 *
4368 * Here we show the nominal target (ie, the relation that was named in the
4369 * original query). If the actual target(s) is/are different, we'll show them
4370 * in show_modifytable_info().
4371 */
4372 static void
4373 ExplainModifyTarget(ModifyTable *plan, ExplainState *es)
4374 {
4375 ExplainTargetRel((Plan *) plan, plan->nominalRelation, es);
4376 }
4377
4378 /*
4379 * Show the target relation of a scan or modify node
4380 */
4381 static void
4382 ExplainTargetRel(Plan *plan, Index rti, ExplainState *es)
4383 {
4384 char *objectname = NULL;
4385 char *namespace = NULL;
4386 const char *objecttag = NULL;
4387 RangeTblEntry *rte;
4388 char *refname;
4389
4390 rte = rt_fetch(rti, es->rtable);
4391 refname = (char *) list_nth(es->rtable_names, rti - 1);
4392 if (refname == NULL)
4393 refname = rte->eref->aliasname;
4394
4395 switch (nodeTag(plan))
4396 {
4397 case T_SeqScan:
4398 case T_SampleScan:
4399 case T_IndexScan:
4400 case T_IndexOnlyScan:
4401 case T_BitmapHeapScan:
4402 case T_TidScan:
4403 case T_TidRangeScan:
4404 case T_ForeignScan:
4405 case T_CustomScan:
4406 case T_ModifyTable:
4407 /* Assert it's on a real relation */
4408 Assert(rte->rtekind == RTE_RELATION);
4409 objectname = get_rel_name(rte->relid);
4410 if (es->verbose)
4411 namespace = get_namespace_name_or_temp(get_rel_namespace(rte->relid));
4412 objecttag = "Relation Name";
4413 break;
4414 case T_FunctionScan:
4415 {
4416 FunctionScan *fscan = (FunctionScan *) plan;
4417
4418 /* Assert it's on a RangeFunction */
4419 Assert(rte->rtekind == RTE_FUNCTION);
4420
4421 /*
4422 * If the expression is still a function call of a single
4423 * function, we can get the real name of the function.
4424 * Otherwise, punt. (Even if it was a single function call
4425 * originally, the optimizer could have simplified it away.)
4426 */
4427 if (list_length(fscan->functions) == 1)
4428 {
4429 RangeTblFunction *rtfunc = (RangeTblFunction *) linitial(fscan->functions);
4430
4431 if (IsA(rtfunc->funcexpr, FuncExpr))
4432 {
4433 FuncExpr *funcexpr = (FuncExpr *) rtfunc->funcexpr;
4434 Oid funcid = funcexpr->funcid;
4435
4436 objectname = get_func_name(funcid);
4437 if (es->verbose)
4438 namespace = get_namespace_name_or_temp(get_func_namespace(funcid));
4439 }
4440 }
4441 objecttag = "Function Name";
4442 }
4443 break;
4444 case T_TableFuncScan:
4445 {
4446 TableFunc *tablefunc = ((TableFuncScan *) plan)->tablefunc;
4447
4448 Assert(rte->rtekind == RTE_TABLEFUNC);
4449 switch (tablefunc->functype)
4450 {
4451 case TFT_XMLTABLE:
4452 objectname = "xmltable";
4453 break;
4454 case TFT_JSON_TABLE:
4455 objectname = "json_table";
4456 break;
4457 default:
4458 elog(ERROR, "invalid TableFunc type %d",
4459 (int) tablefunc->functype);
4460 }
4461 objecttag = "Table Function Name";
4462 }
4463 break;
4464 case T_ValuesScan:
4465 Assert(rte->rtekind == RTE_VALUES);
4466 break;
4467 case T_CteScan:
4468 /* Assert it's on a non-self-reference CTE */
4469 Assert(rte->rtekind == RTE_CTE);
4470 Assert(!rte->self_reference);
4471 objectname = rte->ctename;
4472 objecttag = "CTE Name";
4473 break;
4474 case T_NamedTuplestoreScan:
4475 Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
4476 objectname = rte->enrname;
4477 objecttag = "Tuplestore Name";
4478 break;
4479 case T_WorkTableScan:
4480 /* Assert it's on a self-reference CTE */
4481 Assert(rte->rtekind == RTE_CTE);
4482 Assert(rte->self_reference);
4483 objectname = rte->ctename;
4484 objecttag = "CTE Name";
4485 break;
4486 default:
4487 break;
4488 }
4489
4490 if (es->format == EXPLAIN_FORMAT_TEXT)
4491 {
4492 appendStringInfoString(es->str, " on");
4493 if (namespace != NULL)
4494 appendStringInfo(es->str, " %s.%s", quote_identifier(namespace),
4495 quote_identifier(objectname));
4496 else if (objectname != NULL)
4497 appendStringInfo(es->str, " %s", quote_identifier(objectname));
4498 if (objectname == NULL || strcmp(refname, objectname) != 0)
4499 appendStringInfo(es->str, " %s", quote_identifier(refname));
4500 }
4501 else
4502 {
4503 if (objecttag != NULL && objectname != NULL)
4504 ExplainPropertyText(objecttag, objectname, es);
4505 if (namespace != NULL)
4506 ExplainPropertyText("Schema", namespace, es);
4507 ExplainPropertyText("Alias", refname, es);
4508 }
4509 }
4510
4511 /*
4512 * Show extra information for a ModifyTable node
4513 *
4514 * We have three objectives here. First, if there's more than one target
4515 * table or it's different from the nominal target, identify the actual
4516 * target(s). Second, give FDWs a chance to display extra info about foreign
4517 * targets. Third, show information about ON CONFLICT.
4518 */
4519 static void
4520 show_modifytable_info(ModifyTableState *mtstate, List *ancestors,
4521 ExplainState *es)
4522 {
4523 ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
4524 const char *operation;
4525 const char *foperation;
4526 bool labeltargets;
4527 bool nopruning;
4528 int j;
4529 List *idxNames = NIL;
4530 ListCell *lst;
4531
4532 switch (node->operation)
4533 {
4534 case CMD_INSERT:
4535 operation = "Insert";
4536 foperation = "Foreign Insert";
4537 break;
4538 case CMD_UPDATE:
4539 operation = "Update";
4540 foperation = "Foreign Update";
4541 break;
4542 case CMD_DELETE:
4543 operation = "Delete";
4544 foperation = "Foreign Delete";
4545 break;
4546 case CMD_MERGE:
4547 operation = "Merge";
4548 /* XXX unsupported for now, but avoid compiler noise */
4549 foperation = "Foreign Merge";
4550 break;
4551 default:
4552 operation = "???";
4553 foperation = "Foreign ???";
4554 break;
4555 }
4556
4557 /*
4558 * Should we explicitly label target relations?
4559 *
4560 * If there's only one target relation, do not list it if it's the
4561 * relation named in the query, or if it has been pruned. (Normally
4562 * mtstate->resultRelInfo doesn't include pruned relations, but a single
4563 * pruned target relation may be present, if all other target relations
4564 * have been pruned. See ExecInitModifyTable().)
4565 */
4566 labeltargets = (mtstate->mt_nrels > 1 ||
4567 (mtstate->mt_nrels == 1 &&
4568 mtstate->resultRelInfo[0].ri_RangeTableIndex != node->nominalRelation &&
4569 bms_is_member(mtstate->resultRelInfo[0].ri_RangeTableIndex,
4570 mtstate->ps.state->es_unpruned_relids)));
4571
4572 if (labeltargets)
4573 ExplainOpenGroup("Target Tables", "Target Tables", false, es);
4574
4575 /*
4576 * node->fdwPrivLists is parallel to node->resultRelations, in the
4577 * original pre-pruning order. If no result relations were pruned, the
4578 * entries in mtstate->resultRelInfo[] are in that same order and can be
4579 * matched to fdwPrivLists positionally; otherwise we have to look each
4580 * one up by range table index below. This test is loop-invariant, so
4581 * compute it once here.
4582 */
4583 nopruning = (list_length(node->resultRelations) == mtstate->mt_nrels);
4584
4585 for (j = 0; j < mtstate->mt_nrels; j++)
4586 {
4587 ResultRelInfo *resultRelInfo = mtstate->resultRelInfo + j;
4588 FdwRoutine *fdwroutine = resultRelInfo->ri_FdwRoutine;
4589
4590 if (labeltargets)
4591 {
4592 /* Open a group for this target */
4593 ExplainOpenGroup("Target Table", NULL, true, es);
4594
4595 /*
4596 * In text mode, decorate each target with operation type, so that
4597 * ExplainTargetRel's output of " on foo" will read nicely.
4598 */
4599 if (es->format == EXPLAIN_FORMAT_TEXT)
4600 {
4601 ExplainIndentText(es);
4602 appendStringInfoString(es->str,
4603 fdwroutine ? foperation : operation);
4604 }
4605
4606 /* Identify target */
4607 ExplainTargetRel((Plan *) node,
4608 resultRelInfo->ri_RangeTableIndex,
4609 es);
4610
4611 if (es->format == EXPLAIN_FORMAT_TEXT)
4612 {
4613 appendStringInfoChar(es->str, '\n');
4614 es->indent++;
4615 }
4616 }
4617
4618 /* Give FDW a chance if needed */
4619 if (!resultRelInfo->ri_usesFdwDirectModify &&
4620 fdwroutine != NULL &&
4621 fdwroutine->ExplainForeignModify != NULL)
4622 {
4623 List *fdw_private;
4624
4625 /*
4626 * Find this relation's fdw_private: index fdwPrivLists directly
4627 * when nothing was pruned, else match by range table index.
4628 */
4629 if (nopruning)
4630 fdw_private = (List *) list_nth(node->fdwPrivLists, j);
4631 else
4632 {
4633 Index rti = resultRelInfo->ri_RangeTableIndex;
4634 ListCell *lc1;
4635 ListCell *lc2;
4636
4637 fdw_private = NIL;
4638 forboth(lc1, node->resultRelations, lc2, node->fdwPrivLists)
4639 {
4640 if (lfirst_int(lc1) == (int) rti)
4641 {
4642 fdw_private = (List *) lfirst(lc2);
4643 break;
4644 }
4645 }
4646 }
4647
4648 fdwroutine->ExplainForeignModify(mtstate,
4649 resultRelInfo,
4650 fdw_private,
4651 j,
4652 es);
4653 }
4654
4655 if (labeltargets)
4656 {
4657 /* Undo the indentation we added in text format */
4658 if (es->format == EXPLAIN_FORMAT_TEXT)
4659 es->indent--;
4660
4661 /* Close the group */
4662 ExplainCloseGroup("Target Table", NULL, true, es);
4663 }
4664 }
4665
4666 /* Gather names of ON CONFLICT arbiter indexes */
4667 foreach(lst, node->arbiterIndexes)
4668 {
4669 char *indexname = get_rel_name(lfirst_oid(lst));
4670
4671 idxNames = lappend(idxNames, indexname);
4672 }
4673
4674 if (node->onConflictAction != ONCONFLICT_NONE)
4675 {
4676 ExplainPropertyText("Conflict Resolution",
4677 node->onConflictAction == ONCONFLICT_NOTHING ?
4678 "NOTHING" : "UPDATE",
4679 es);
4680
4681 /*
4682 * Don't display arbiter indexes at all when DO NOTHING variant
4683 * implicitly ignores all conflicts
4684 */
4685 if (idxNames)
4686 ExplainPropertyList("Conflict Arbiter Indexes", idxNames, es);
4687
4688 /* ON CONFLICT DO UPDATE WHERE qual is specially displayed */
4689 if (node->onConflictWhere)
4690 {
4691 show_upper_qual((List *) node->onConflictWhere, "Conflict Filter",
4692 &mtstate->ps, ancestors, es);
4693 show_instrumentation_count("Rows Removed by Conflict Filter", 1, &mtstate->ps, es);
4694 }
4695
4696 /* EXPLAIN ANALYZE display of actual outcome for each tuple proposed */
4697 if (es->analyze && mtstate->ps.instrument)
4698 {
4699 double total;
4700 double insert_path;
4701 double other_path;
4702
4703 InstrEndLoop(outerPlanState(mtstate)->instrument);
4704
4705 /* count the number of source rows */
4706 total = outerPlanState(mtstate)->instrument->ntuples;
4707 other_path = mtstate->ps.instrument->ntuples2;
4708 insert_path = total - other_path;
4709
4710 ExplainPropertyFloat("Tuples Inserted", NULL,
4711 insert_path, 0, es);
4712 ExplainPropertyFloat("Conflicting Tuples", NULL,
4713 other_path, 0, es);
4714 }
4715 }
4716 else if (node->operation == CMD_MERGE)
4717 {
4718 /* EXPLAIN ANALYZE display of tuples processed */
4719 if (es->analyze && mtstate->ps.instrument)
4720 {
4721 double total;
4722 double insert_path;
4723 double update_path;
4724 double delete_path;
4725 double skipped_path;
4726
4727 InstrEndLoop(outerPlanState(mtstate)->instrument);
4728
4729 /* count the number of source rows */
4730 total = outerPlanState(mtstate)->instrument->ntuples;
4731 insert_path = mtstate->mt_merge_inserted;
4732 update_path = mtstate->mt_merge_updated;
4733 delete_path = mtstate->mt_merge_deleted;
4734 skipped_path = total - insert_path - update_path - delete_path;
4735 Assert(skipped_path >= 0);
4736
4737 if (es->format == EXPLAIN_FORMAT_TEXT)
4738 {
4739 if (total > 0)
4740 {
4741 ExplainIndentText(es);
4742 appendStringInfoString(es->str, "Tuples:");
4743 if (insert_path > 0)
4744 appendStringInfo(es->str, " inserted=%.0f", insert_path);
4745 if (update_path > 0)
4746 appendStringInfo(es->str, " updated=%.0f", update_path);
4747 if (delete_path > 0)
4748 appendStringInfo(es->str, " deleted=%.0f", delete_path);
4749 if (skipped_path > 0)
4750 appendStringInfo(es->str, " skipped=%.0f", skipped_path);
4751 appendStringInfoChar(es->str, '\n');
4752 }
4753 }
4754 else
4755 {
4756 ExplainPropertyFloat("Tuples Inserted", NULL, insert_path, 0, es);
4757 ExplainPropertyFloat("Tuples Updated", NULL, update_path, 0, es);
4758 ExplainPropertyFloat("Tuples Deleted", NULL, delete_path, 0, es);
4759 ExplainPropertyFloat("Tuples Skipped", NULL, skipped_path, 0, es);
4760 }
4761 }
4762 }
4763
4764 if (labeltargets)
4765 ExplainCloseGroup("Target Tables", "Target Tables", false, es);
4766 }
4767
4768 /*
4769 * Explain the constituent plans of an Append, MergeAppend,
4770 * BitmapAnd, or BitmapOr node.
4771 *
4772 * The ancestors list should already contain the immediate parent of these
4773 * plans.
4774 */
4775 static void
4776 ExplainMemberNodes(PlanState **planstates, int nplans,
4777 List *ancestors, ExplainState *es)
4778 {
4779 int j;
4780
4781 for (j = 0; j < nplans; j++)
4782 ExplainNode(planstates[j], ancestors,
4783 "Member", NULL, es);
4784 }
4785
4786 /*
4787 * Report about any pruned subnodes of an Append or MergeAppend node.
4788 *
4789 * nplans indicates the number of live subplans.
4790 * nchildren indicates the original number of subnodes in the Plan;
4791 * some of these may have been pruned by the run-time pruning code.
4792 */
4793 static void
4794 ExplainMissingMembers(int nplans, int nchildren, ExplainState *es)
4795 {
4796 if (nplans < nchildren || es->format != EXPLAIN_FORMAT_TEXT)
4797 ExplainPropertyInteger("Subplans Removed", NULL,
4798 nchildren - nplans, es);
4799 }
4800
4801 /*
4802 * Explain a list of SubPlans (or initPlans, which also use SubPlan nodes).
4803 *
4804 * The ancestors list should already contain the immediate parent of these
4805 * SubPlans.
4806 */
4807 static void
4808 ExplainSubPlans(List *plans, List *ancestors,
4809 const char *relationship, ExplainState *es)
4810 {
4811 ListCell *lst;
4812
4813 foreach(lst, plans)
4814 {
4815 SubPlanState *sps = (SubPlanState *) lfirst(lst);
4816 SubPlan *sp = sps->subplan;
4817
4818 /*
4819 * There can be multiple SubPlan nodes referencing the same physical
4820 * subplan (same plan_id, which is its index in PlannedStmt.subplans).
4821 * We should print a subplan only once, so track which ones we already
4822 * printed. This state must be global across the plan tree, since the
4823 * duplicate nodes could be in different plan nodes, eg both a bitmap
4824 * indexscan's indexqual and its parent heapscan's recheck qual. (We
4825 * do not worry too much about which plan node we show the subplan as
4826 * attached to in such cases.)
4827 */
4828 if (bms_is_member(sp->plan_id, es->printed_subplans))
4829 continue;
4830 es->printed_subplans = bms_add_member(es->printed_subplans,
4831 sp->plan_id);
4832
4833 /*
4834 * Treat the SubPlan node as an ancestor of the plan node(s) within
4835 * it, so that ruleutils.c can find the referents of subplan
4836 * parameters.
4837 */
4838 ancestors = lcons(sp, ancestors);
4839
4840 ExplainNode(sps->planstate, ancestors,
4841 relationship, sp->plan_name, es);
4842
4843 ancestors = list_delete_first(ancestors);
4844 }
4845 }
4846
4847 /*
4848 * Explain a list of children of a CustomScan.
4849 */
4850 static void
4851 ExplainCustomChildren(CustomScanState *css, List *ancestors, ExplainState *es)
4852 {
4853 ListCell *cell;
4854 const char *label =
4855 (list_length(css->custom_ps) != 1 ? "children" : "child");
4856
4857 foreach(cell, css->custom_ps)
4858 ExplainNode((PlanState *) lfirst(cell), ancestors, label, NULL, es);
4859 }
4860
4861 /*
4862 * Create a per-plan-node workspace for collecting per-worker data.
4863 *
4864 * Output related to each worker will be temporarily "set aside" into a
4865 * separate buffer, which we'll merge into the main output stream once
4866 * we've processed all data for the plan node. This makes it feasible to
4867 * generate a coherent sub-group of fields for each worker, even though the
4868 * code that produces the fields is in several different places in this file.
4869 * Formatting of such a set-aside field group is managed by
4870 * ExplainOpenSetAsideGroup and ExplainSaveGroup/ExplainRestoreGroup.
4871 */
4872 static ExplainWorkersState *
4873 ExplainCreateWorkersState(int num_workers)
4874 {
4875 ExplainWorkersState *wstate;
4876
4877 wstate = (ExplainWorkersState *) palloc(sizeof(ExplainWorkersState));
4878 wstate->num_workers = num_workers;
4879 wstate->worker_inited = (bool *) palloc0(num_workers * sizeof(bool));
4880 wstate->worker_str = (StringInfoData *)
4881 palloc0(num_workers * sizeof(StringInfoData));
4882 wstate->worker_state_save = (int *) palloc(num_workers * sizeof(int));
4883 return wstate;
4884 }
4885
4886 /*
4887 * Begin or resume output into the set-aside group for worker N.
4888 */
4889 static void
4890 ExplainOpenWorker(int n, ExplainState *es)
4891 {
4892 ExplainWorkersState *wstate = es->workers_state;
4893
4894 Assert(wstate);
4895 Assert(n >= 0 && n < wstate->num_workers);
4896
4897 /* Save prior output buffer pointer */
4898 wstate->prev_str = es->str;
4899
4900 if (!wstate->worker_inited[n])
4901 {
4902 /* First time through, so create the buffer for this worker */
4903 initStringInfo(&wstate->worker_str[n]);
4904 es->str = &wstate->worker_str[n];
4905
4906 /*
4907 * Push suitable initial formatting state for this worker's field
4908 * group. We allow one extra logical nesting level, since this group
4909 * will eventually be wrapped in an outer "Workers" group.
4910 */
4911 ExplainOpenSetAsideGroup("Worker", NULL, true, 2, es);
4912
4913 /*
4914 * In non-TEXT formats we always emit a "Worker Number" field, even if
4915 * there's no other data for this worker.
4916 */
4917 if (es->format != EXPLAIN_FORMAT_TEXT)
4918 ExplainPropertyInteger("Worker Number", NULL, n, es);
4919
4920 wstate->worker_inited[n] = true;
4921 }
4922 else
4923 {
4924 /* Resuming output for a worker we've already emitted some data for */
4925 es->str = &wstate->worker_str[n];
4926
4927 /* Restore formatting state saved by last ExplainCloseWorker() */
4928 ExplainRestoreGroup(es, 2, &wstate->worker_state_save[n]);
4929 }
4930
4931 /*
4932 * In TEXT format, prefix the first output line for this worker with
4933 * "Worker N:". Then, any additional lines should be indented one more
4934 * stop than the "Worker N" line is.
4935 */
4936 if (es->format == EXPLAIN_FORMAT_TEXT)
4937 {
4938 if (es->str->len == 0)
4939 {
4940 ExplainIndentText(es);
4941 appendStringInfo(es->str, "Worker %d: ", n);
4942 }
4943
4944 es->indent++;
4945 }
4946 }
4947
4948 /*
4949 * End output for worker N --- must pair with previous ExplainOpenWorker call
4950 */
4951 static void
4952 ExplainCloseWorker(int n, ExplainState *es)
4953 {
4954 ExplainWorkersState *wstate = es->workers_state;
4955
4956 Assert(wstate);
4957 Assert(n >= 0 && n < wstate->num_workers);
4958 Assert(wstate->worker_inited[n]);
4959
4960 /*
4961 * Save formatting state in case we do another ExplainOpenWorker(), then
4962 * pop the formatting stack.
4963 */
4964 ExplainSaveGroup(es, 2, &wstate->worker_state_save[n]);
4965
4966 /*
4967 * In TEXT format, if we didn't actually produce any output line(s) then
4968 * truncate off the partial line emitted by ExplainOpenWorker. (This is
4969 * to avoid bogus output if, say, show_buffer_usage chooses not to print
4970 * anything for the worker.) Also fix up the indent level.
4971 */
4972 if (es->format == EXPLAIN_FORMAT_TEXT)
4973 {
4974 while (es->str->len > 0 && es->str->data[es->str->len - 1] != '\n')
4975 es->str->data[--(es->str->len)] = '\0';
4976
4977 es->indent--;
4978 }
4979
4980 /* Restore prior output buffer pointer */
4981 es->str = wstate->prev_str;
4982 }
4983
4984 /*
4985 * Print per-worker info for current node, then free the ExplainWorkersState.
4986 */
4987 static void
4988 ExplainFlushWorkersState(ExplainState *es)
4989 {
4990 ExplainWorkersState *wstate = es->workers_state;
4991
4992 ExplainOpenGroup("Workers", "Workers", false, es);
4993 for (int i = 0; i < wstate->num_workers; i++)
4994 {
4995 if (wstate->worker_inited[i])
4996 {
4997 /* This must match previous ExplainOpenSetAsideGroup call */
4998 ExplainOpenGroup("Worker", NULL, true, es);
4999 appendStringInfoString(es->str, wstate->worker_str[i].data);
5000 ExplainCloseGroup("Worker", NULL, true, es);
5001
5002 pfree(wstate->worker_str[i].data);
5003 }
5004 }
5005 ExplainCloseGroup("Workers", "Workers", false, es);
5006
5007 pfree(wstate->worker_inited);
5008 pfree(wstate->worker_str);
5009 pfree(wstate->worker_state_save);
5010 pfree(wstate);
5011 }