PostgreSQL Source Code git master
explain.h File Reference
Include dependency graph for explain.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef void(* ExplainOneQuery_hook_type) (Query *query, int cursorOptions, IntoClause *into, struct ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
 
typedef void(* explain_per_plan_hook_type) (PlannedStmt *plannedstmt, IntoClause *into, struct ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
 
typedef void(* explain_per_node_hook_type) (PlanState *planstate, List *ancestors, const char *relationship, const char *plan_name, struct ExplainState *es)
 
typedef const char *(* explain_get_index_name_hook_type) (Oid indexId)
 

Functions

void ExplainQuery (ParseState *pstate, ExplainStmt *stmt, ParamListInfo params, DestReceiver *dest)
 
void standard_ExplainOneQuery (Query *query, int cursorOptions, IntoClause *into, struct ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
 
TupleDesc ExplainResultDesc (ExplainStmt *stmt)
 
void ExplainOneUtility (Node *utilityStmt, IntoClause *into, struct ExplainState *es, ParseState *pstate, ParamListInfo params)
 
void ExplainOnePlan (PlannedStmt *plannedstmt, IntoClause *into, struct ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, const instr_time *planduration, const BufferUsage *bufusage, const MemoryContextCounters *mem_counters)
 
void ExplainPrintPlan (struct ExplainState *es, QueryDesc *queryDesc)
 
void ExplainPrintTriggers (struct ExplainState *es, QueryDesc *queryDesc)
 
void ExplainPrintJITSummary (struct ExplainState *es, QueryDesc *queryDesc)
 
void ExplainQueryText (struct ExplainState *es, QueryDesc *queryDesc)
 
void ExplainQueryParameters (struct ExplainState *es, ParamListInfo params, int maxlen)
 

Variables

PGDLLIMPORT ExplainOneQuery_hook_type ExplainOneQuery_hook
 
PGDLLIMPORT explain_per_plan_hook_type explain_per_plan_hook
 
PGDLLIMPORT explain_per_node_hook_type explain_per_node_hook
 
PGDLLIMPORT explain_get_index_name_hook_type explain_get_index_name_hook
 

Typedef Documentation

◆ explain_get_index_name_hook_type

typedef const char *(* explain_get_index_name_hook_type) (Oid indexId)

Definition at line 49 of file explain.h.

◆ explain_per_node_hook_type

typedef void(* explain_per_node_hook_type) (PlanState *planstate, List *ancestors, const char *relationship, const char *plan_name, struct ExplainState *es)

Definition at line 41 of file explain.h.

◆ explain_per_plan_hook_type

typedef void(* explain_per_plan_hook_type) (PlannedStmt *plannedstmt, IntoClause *into, struct ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)

Definition at line 32 of file explain.h.

◆ ExplainOneQuery_hook_type

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

Definition at line 22 of file explain.h.

Function Documentation

◆ ExplainOnePlan()

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

Definition at line 494 of file explain.c.

499{
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 */
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)
544 else if (es->serialize != EXPLAIN_SERIALIZE_NONE)
546 else
548
549 /* Create a QueryDesc for the query */
550 queryDesc = CreateQueryDesc(plannedstmt, queryString,
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)
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)
575 else
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 */
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 {
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 */
646 ExplainPrintSerialize(es, &serializeMetrics);
647
648 /* Allow plugins to print additional information */
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
664
665 /* We need a CCI just in case query expanded to multiple plans */
666 if (es->analyze)
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}
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:375
DestReceiver * CreateIntoRelDestReceiver(IntoClause *intoClause)
Definition: createas.c:440
DestReceiver * None_Receiver
Definition: dest.c:96
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:467
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:407
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:123
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:298
#define EXEC_FLAG_EXPLAIN_GENERIC
Definition: executor.h:66
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
static bool peek_buffer_usage(ExplainState *es, const BufferUsage *usage)
Definition: explain.c:4050
void ExplainPrintJITSummary(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:879
static double elapsed_time(instr_time *starttime)
Definition: explain.c:1167
explain_per_plan_hook_type explain_per_plan_hook
Definition: explain.c:56
static void show_memory_counters(ExplainState *es, const MemoryContextCounters *mem_counters)
Definition: explain.c:4302
void ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:759
static void ExplainPrintSerialize(ExplainState *es, SerializeMetrics *metrics)
Definition: explain.c:1003
void ExplainPrintTriggers(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:836
static void show_buffer_usage(ExplainState *es, const BufferUsage *usage)
Definition: explain.c:4090
SerializeMetrics GetSerializationMetrics(DestReceiver *dest)
Definition: explain_dr.c:299
DestReceiver * CreateExplainSerializeDestReceiver(ExplainState *es)
Definition: explain_dr.c:274
void ExplainOpenGroup(const char *objtype, const char *labelname, bool labeled, ExplainState *es)
void ExplainIndentText(ExplainState *es)
void ExplainPropertyFloat(const char *qlabel, const char *unit, double value, int ndigits, ExplainState *es)
void ExplainCloseGroup(const char *objtype, const char *labelname, bool labeled, ExplainState *es)
@ EXPLAIN_SERIALIZE_NONE
Definition: explain_state.h:22
@ EXPLAIN_FORMAT_TEXT
Definition: explain_state.h:29
Assert(PointerIsAligned(start, uint64))
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:122
#define INSTR_TIME_GET_DOUBLE(t)
Definition: instr_time.h:188
@ INSTRUMENT_TIMER
Definition: instrument.h:62
@ INSTRUMENT_BUFFERS
Definition: instrument.h:63
@ INSTRUMENT_WAL
Definition: instrument.h:65
@ INSTRUMENT_ROWS
Definition: instrument.h:64
@ CMD_UTILITY
Definition: nodes.h:276
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:106
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:68
ScanDirection
Definition: sdir.h:25
@ NoMovementScanDirection
Definition: sdir.h:27
@ ForwardScanDirection
Definition: sdir.h:28
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:731
void PopActiveSnapshot(void)
Definition: snapmgr.c:762
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:719
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:787
#define InvalidSnapshot
Definition: snapshot.h:119
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
StringInfo str
Definition: explain_state.h:46
ExplainFormat format
Definition: explain_state.h:59
ExplainSerializeOption serialize
Definition: explain_state.h:58
bool skipData
Definition: primnodes.h:171
CmdType commandType
Definition: plannodes.h:53
void CommandCounterIncrement(void)
Definition: xact.c:1100

References ExplainState::analyze, appendStringInfoString(), Assert(), ExplainState::buffers, CMD_UTILITY, CommandCounterIncrement(), PlannedStmt::commandType, ExplainState::costs, CreateExplainSerializeDestReceiver(), CreateIntoRelDestReceiver(), CreateQueryDesc(), generate_unaccent_rules::dest, elapsed_time(), EXEC_FLAG_EXPLAIN_GENERIC, EXEC_FLAG_EXPLAIN_ONLY, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), EXPLAIN_FORMAT_TEXT, explain_per_plan_hook, EXPLAIN_SERIALIZE_NONE, ExplainCloseGroup(), ExplainIndentText(), ExplainOpenGroup(), ExplainPrintJITSummary(), ExplainPrintPlan(), ExplainPrintSerialize(), ExplainPrintTriggers(), ExplainPropertyFloat(), ExplainState::format, ForwardScanDirection, FreeQueryDesc(), ExplainState::generic, GetActiveSnapshot(), GetIntoRelEFlags(), GetSerializationMetrics(), ExplainState::indent, INSTR_TIME_GET_DOUBLE, INSTR_TIME_SET_CURRENT, INSTRUMENT_BUFFERS, INSTRUMENT_ROWS, INSTRUMENT_TIMER, INSTRUMENT_WAL, InvalidSnapshot, NoMovementScanDirection, None_Receiver, peek_buffer_usage(), PopActiveSnapshot(), PushCopiedSnapshot(), ExplainState::serialize, show_buffer_usage(), show_memory_counters(), IntoClause::skipData, ExplainState::str, ExplainState::summary, ExplainState::timing, UpdateActiveSnapshotCommandId(), and ExplainState::wal.

Referenced by ExplainExecuteQuery(), and standard_ExplainOneQuery().

◆ ExplainOneUtility()

void ExplainOneUtility ( Node utilityStmt,
IntoClause into,
struct ExplainState es,
ParseState pstate,
ParamListInfo  params 
)

Definition at line 390 of file explain.c.

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);
427 (*post_parse_analyze_hook) (pstate, ctas_query, jstate);
428 rewritten = QueryRewrite(ctas_query);
429 Assert(list_length(rewritten) == 1);
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);
453 (*post_parse_analyze_hook) (pstate, dcs_query, jstate);
454
455 rewritten = QueryRewrite(dcs_query);
456 Assert(list_length(rewritten) == 1);
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)
475 "Utility statements have no plan structure\n");
476 else
477 ExplainDummyGroup("Utility Statement", NULL, es);
478 }
479}
void ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into, ExplainState *es, ParseState *pstate, ParamListInfo params)
Definition: prepare.c:571
bool CreateTableAsRelExists(CreateTableAsStmt *ctas)
Definition: createas.c:393
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
static void ExplainOneQuery(Query *query, int cursorOptions, IntoClause *into, ExplainState *es, ParseState *pstate, ParamListInfo params)
Definition: explain.c:293
void ExplainDummyGroup(const char *objtype, const char *labelname, ExplainState *es)
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define copyObject(obj)
Definition: nodes.h:230
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
@ OBJECT_MATVIEW
Definition: parsenodes.h:2340
@ OBJECT_TABLE
Definition: parsenodes.h:2358
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3385
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:59
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:95
JumbleState * JumbleQuery(Query *query)
List * QueryRewrite(Query *parsetree)
IntoClause * into
Definition: parsenodes.h:3988
ObjectType objtype
Definition: parsenodes.h:3989
Definition: pg_list.h:54

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

Referenced by ExplainExecuteQuery(), and ExplainOneQuery().

◆ ExplainPrintJITSummary()

void ExplainPrintJITSummary ( struct ExplainState es,
QueryDesc queryDesc 
)

Definition at line 879 of file explain.c.

880{
881 JitInstrumentation ji = {0};
882
883 if (!(queryDesc->estate->es_jit_flags & PGJIT_PERFORM))
884 return;
885
886 /*
887 * Work with a copy instead of modifying the leader state, since this
888 * function may be called twice
889 */
890 if (queryDesc->estate->es_jit)
891 InstrJitAgg(&ji, &queryDesc->estate->es_jit->instr);
892
893 /* If this process has done JIT in parallel workers, merge stats */
894 if (queryDesc->estate->es_jit_worker_instr)
895 InstrJitAgg(&ji, queryDesc->estate->es_jit_worker_instr);
896
897 ExplainPrintJIT(es, queryDesc->estate->es_jit_flags, &ji);
898}
static void ExplainPrintJIT(ExplainState *es, int jit_flags, JitInstrumentation *ji)
Definition: explain.c:905
void InstrJitAgg(JitInstrumentation *dst, JitInstrumentation *add)
Definition: jit.c:182
#define PGJIT_PERFORM
Definition: jit.h:20
struct JitContext * es_jit
Definition: execnodes.h:760
struct JitInstrumentation * es_jit_worker_instr
Definition: execnodes.h:761
int es_jit_flags
Definition: execnodes.h:759
JitInstrumentation instr
Definition: jit.h:62
EState * estate
Definition: execdesc.h:48

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

Referenced by explain_ExecutorEnd(), and ExplainOnePlan().

◆ ExplainPrintPlan()

void ExplainPrintPlan ( struct ExplainState es,
QueryDesc queryDesc 
)

Definition at line 759 of file explain.c.

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);
772 es->rtable_names);
773 es->printed_subplans = NULL;
774 es->rtable_size = list_length(es->rtable);
775 foreach(lc, es->rtable)
776 {
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 {
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 */
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 != UINT64CONST(0) &&
816 {
817 /*
818 * Output the queryid as an int64 rather than a uint64 so we match
819 * what would be seen in the BIGINT pg_stat_statements.queryid column.
820 */
821 ExplainPropertyInteger("Query Identifier", NULL, (int64)
822 queryDesc->plannedstmt->queryId, es);
823 }
824}
int64_t int64
Definition: c.h:499
#define UINT64CONST(x)
Definition: c.h:517
#define outerPlanState(node)
Definition: execnodes.h:1252
static void ExplainNode(PlanState *planstate, List *ancestors, const char *relationship, const char *plan_name, ExplainState *es)
Definition: explain.c:1355
static bool ExplainPreScanNode(PlanState *planstate, Bitmapset **rels_used)
Definition: explain.c:1186
static void ExplainPrintSettings(ExplainState *es)
Definition: explain.c:689
void ExplainPropertyInteger(const char *qlabel, const char *unit, int64 value, ExplainState *es)
struct parser_state ps
@ RTE_GROUP
Definition: parsenodes.h:1037
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
@ COMPUTE_QUERY_ID_REGRESS
Definition: queryjumble.h:77
int compute_query_id
List * deparse_context_for_plan_tree(PlannedStmt *pstmt, List *rtable_names)
Definition: ruleutils.c:3753
List * select_rtable_names_for_explain(List *rtable, Bitmapset *rels_used)
Definition: ruleutils.c:3855
Bitmapset * printed_subplans
Definition: explain_state.h:68
List * rtable_names
Definition: explain_state.h:66
PlannedStmt * pstmt
Definition: explain_state.h:64
List * deparse_cxt
Definition: explain_state.h:67
List * rtable
Definition: plannodes.h:91
uint64 queryId
Definition: plannodes.h:56
PlannedStmt * plannedstmt
Definition: execdesc.h:37
PlanState * planstate
Definition: execdesc.h:49
RTEKind rtekind
Definition: parsenodes.h:1061

References Assert(), compute_query_id, COMPUTE_QUERY_ID_REGRESS, deparse_context_for_plan_tree(), ExplainState::deparse_cxt, ExplainNode(), ExplainPreScanNode(), ExplainPrintSettings(), ExplainPropertyInteger(), ExplainState::hide_workers, IsA, lfirst_node, list_length(), NIL, outerPlanState, QueryDesc::plannedstmt, QueryDesc::planstate, ExplainState::printed_subplans, ps, ExplainState::pstmt, PlannedStmt::queryId, ExplainState::rtable, PlannedStmt::rtable, ExplainState::rtable_names, ExplainState::rtable_size, RTE_GROUP, RangeTblEntry::rtekind, select_rtable_names_for_explain(), UINT64CONST, and ExplainState::verbose.

Referenced by explain_ExecutorEnd(), and ExplainOnePlan().

◆ ExplainPrintTriggers()

void ExplainPrintTriggers ( struct ExplainState es,
QueryDesc queryDesc 
)

Definition at line 836 of file explain.c.

837{
838 ResultRelInfo *rInfo;
839 bool show_relname;
840 List *resultrels;
841 List *routerels;
842 List *targrels;
843 ListCell *l;
844
845 resultrels = queryDesc->estate->es_opened_result_relations;
846 routerels = queryDesc->estate->es_tuple_routing_result_relations;
847 targrels = queryDesc->estate->es_trig_target_relations;
848
849 ExplainOpenGroup("Triggers", "Triggers", false, es);
850
851 show_relname = (list_length(resultrels) > 1 ||
852 routerels != NIL || targrels != NIL);
853 foreach(l, resultrels)
854 {
855 rInfo = (ResultRelInfo *) lfirst(l);
856 report_triggers(rInfo, show_relname, es);
857 }
858
859 foreach(l, routerels)
860 {
861 rInfo = (ResultRelInfo *) lfirst(l);
862 report_triggers(rInfo, show_relname, es);
863 }
864
865 foreach(l, targrels)
866 {
867 rInfo = (ResultRelInfo *) lfirst(l);
868 report_triggers(rInfo, show_relname, es);
869 }
870
871 ExplainCloseGroup("Triggers", "Triggers", false, es);
872}
static void report_triggers(ResultRelInfo *rInfo, bool show_relname, ExplainState *es)
Definition: explain.c:1096
#define lfirst(lc)
Definition: pg_list.h:172
List * es_tuple_routing_result_relations
Definition: execnodes.h:694
List * es_trig_target_relations
Definition: execnodes.h:697
List * es_opened_result_relations
Definition: execnodes.h:684

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

Referenced by explain_ExecutorEnd(), and ExplainOnePlan().

◆ ExplainQuery()

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

Definition at line 176 of file explain.c.

178{
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
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 */
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 {
224 CURSOR_OPT_PARALLEL_OK, NULL, es,
225 pstate, params);
226
227 /* Separate plans with an appropriate separator */
228 if (lnext(rewritten, l) != NULL)
230 }
231 }
232
233 /* emit closing boilerplate */
235 Assert(es->indent == 0);
236
237 /* output tuples */
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}
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
void end_tup_output(TupOutputState *tstate)
Definition: execTuples.c:2522
void do_text_output_multiline(TupOutputState *tstate, const char *txt)
Definition: execTuples.c:2492
TupOutputState * begin_tup_output_tupdesc(DestReceiver *dest, TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2444
#define do_text_output_oneline(tstate, str_to_emit)
Definition: executor.h:622
TupleDesc ExplainResultDesc(ExplainStmt *stmt)
Definition: explain.c:254
void ExplainSeparatePlans(ExplainState *es)
void ExplainEndOutput(ExplainState *es)
void ExplainBeginOutput(ExplainState *es)
ExplainState * NewExplainState(void)
Definition: explain_state.c:61
void ParseExplainOptionList(ExplainState *es, List *options, ParseState *pstate)
Definition: explain_state.c:77
#define stmt
Definition: indent_codes.h:59
void pfree(void *pointer)
Definition: mcxt.c:1528
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343

References appendStringInfoString(), Assert(), begin_tup_output_tupdesc(), castNode, CURSOR_OPT_PARALLEL_OK, StringInfoData::data, generate_unaccent_rules::dest, do_text_output_multiline(), do_text_output_oneline, end_tup_output(), EXPLAIN_FORMAT_TEXT, ExplainBeginOutput(), ExplainEndOutput(), ExplainOneQuery(), ExplainResultDesc(), ExplainSeparatePlans(), ExplainState::format, ExplainState::indent, IsQueryIdEnabled(), JumbleQuery(), lfirst_node, lnext(), NewExplainState(), NIL, ParseExplainOptionList(), pfree(), post_parse_analyze_hook, QueryRewrite(), stmt, ExplainState::str, and TTSOpsVirtual.

Referenced by standard_ProcessUtility().

◆ ExplainQueryParameters()

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

Definition at line 1078 of file explain.c.

1079{
1080 char *str;
1081
1082 /* This check is consistent with errdetail_params() */
1083 if (params == NULL || params->numParams <= 0 || maxlen == 0)
1084 return;
1085
1086 str = BuildParamLogString(params, NULL, maxlen);
1087 if (str && str[0] != '\0')
1088 ExplainPropertyText("Query Parameters", str, es);
1089}
void ExplainPropertyText(const char *qlabel, const char *value, ExplainState *es)
const char * str
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition: params.c:335

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

Referenced by explain_ExecutorEnd().

◆ ExplainQueryText()

void ExplainQueryText ( struct ExplainState es,
QueryDesc queryDesc 
)

Definition at line 1063 of file explain.c.

1064{
1065 if (queryDesc->sourceText)
1066 ExplainPropertyText("Query Text", queryDesc->sourceText, es);
1067}
const char * sourceText
Definition: execdesc.h:38

References ExplainPropertyText(), and QueryDesc::sourceText.

Referenced by explain_ExecutorEnd().

◆ ExplainResultDesc()

TupleDesc ExplainResultDesc ( ExplainStmt stmt)

Definition at line 254 of file explain.c.

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}
int16 AttrNumber
Definition: attnum.h:21
char * defGetString(DefElem *def)
Definition: define.c:35
unsigned int Oid
Definition: postgres_ext.h:30
char * defname
Definition: parsenodes.h:826
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:175
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:835

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

Referenced by ExplainQuery(), and UtilityTupleDescriptor().

◆ standard_ExplainOneQuery()

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

Definition at line 318 of file explain.c.

322{
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 */
343 "explain analyze planner context",
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}
void ExplainOnePlan(PlannedStmt *plannedstmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, const instr_time *planduration, const BufferUsage *bufusage, const MemoryContextCounters *mem_counters)
Definition: explain.c:494
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:181
BufferUsage pgBufferUsage
Definition: instrument.c:20
void BufferUsageAccumDiff(BufferUsage *dst, const BufferUsage *add, const BufferUsage *sub)
Definition: instrument.c:248
void MemoryContextMemConsumed(MemoryContext context, MemoryContextCounters *consumed)
Definition: mcxt.c:786
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
#define plan(x)
Definition: pg_regress.c:161
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:882

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ExplainState::buffers, BufferUsageAccumDiff(), CurrentMemoryContext, ExplainOnePlan(), INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, ExplainState::memory, MemoryContextMemConsumed(), MemoryContextSwitchTo(), pg_plan_query(), pgBufferUsage, and plan.

Referenced by ExplainOneQuery().

Variable Documentation

◆ explain_get_index_name_hook

PGDLLIMPORT explain_get_index_name_hook_type explain_get_index_name_hook
extern

Definition at line 53 of file explain.c.

Referenced by explain_get_index_name().

◆ explain_per_node_hook

PGDLLIMPORT explain_per_node_hook_type explain_per_node_hook
extern

Definition at line 57 of file explain.c.

Referenced by _PG_init(), and ExplainNode().

◆ explain_per_plan_hook

PGDLLIMPORT explain_per_plan_hook_type explain_per_plan_hook
extern

Definition at line 56 of file explain.c.

Referenced by _PG_init(), and ExplainOnePlan().

◆ ExplainOneQuery_hook

PGDLLIMPORT ExplainOneQuery_hook_type ExplainOneQuery_hook
extern

Definition at line 50 of file explain.c.

Referenced by ExplainOneQuery().