PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
auto_explain.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * auto_explain.c
4 *
5 *
6 * Copyright (c) 2008-2025, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * contrib/auto_explain/auto_explain.c
10 *
11 *-------------------------------------------------------------------------
12 */
13#include "postgres.h"
14
15#include <limits.h>
16
17#include "access/parallel.h"
18#include "commands/explain.h"
21#include "common/pg_prng.h"
22#include "executor/instrument.h"
23#include "utils/guc.h"
24
26 .name = "auto_explain",
27 .version = PG_VERSION
28);
29
30/* GUC variables */
31static int auto_explain_log_min_duration = -1; /* msec or -1 */
32static int auto_explain_log_parameter_max_length = -1; /* bytes or -1 */
33static bool auto_explain_log_analyze = false;
34static bool auto_explain_log_verbose = false;
35static bool auto_explain_log_buffers = false;
36static bool auto_explain_log_wal = false;
37static bool auto_explain_log_triggers = false;
38static bool auto_explain_log_timing = true;
39static bool auto_explain_log_settings = false;
43static double auto_explain_sample_rate = 1;
44
45static const struct config_enum_entry format_options[] = {
46 {"text", EXPLAIN_FORMAT_TEXT, false},
47 {"xml", EXPLAIN_FORMAT_XML, false},
48 {"json", EXPLAIN_FORMAT_JSON, false},
49 {"yaml", EXPLAIN_FORMAT_YAML, false},
50 {NULL, 0, false}
51};
52
53static const struct config_enum_entry loglevel_options[] = {
54 {"debug5", DEBUG5, false},
55 {"debug4", DEBUG4, false},
56 {"debug3", DEBUG3, false},
57 {"debug2", DEBUG2, false},
58 {"debug1", DEBUG1, false},
59 {"debug", DEBUG2, true},
60 {"info", INFO, false},
61 {"notice", NOTICE, false},
62 {"warning", WARNING, false},
63 {"log", LOG, false},
64 {NULL, 0, false}
65};
66
67/* Current nesting depth of ExecutorRun calls */
68static int nesting_level = 0;
69
70/* Is the current top-level query to be sampled? */
71static bool current_query_sampled = false;
72
73#define auto_explain_enabled() \
74 (auto_explain_log_min_duration >= 0 && \
75 (nesting_level == 0 || auto_explain_log_nested_statements) && \
76 current_query_sampled)
77
78/* Saved hook values */
83
84static void explain_ExecutorStart(QueryDesc *queryDesc, int eflags);
85static void explain_ExecutorRun(QueryDesc *queryDesc,
86 ScanDirection direction,
87 uint64 count);
88static void explain_ExecutorFinish(QueryDesc *queryDesc);
89static void explain_ExecutorEnd(QueryDesc *queryDesc);
90
91
92/*
93 * Module load callback
94 */
95void
97{
98 /* Define custom GUC variables. */
99 DefineCustomIntVariable("auto_explain.log_min_duration",
100 "Sets the minimum execution time above which plans will be logged.",
101 "-1 disables logging plans. 0 means log all plans.",
103 -1,
104 -1, INT_MAX,
105 PGC_SUSET,
107 NULL,
108 NULL,
109 NULL);
110
111 DefineCustomIntVariable("auto_explain.log_parameter_max_length",
112 "Sets the maximum length of query parameter values to log.",
113 "-1 means log values in full.",
115 -1,
116 -1, INT_MAX,
117 PGC_SUSET,
119 NULL,
120 NULL,
121 NULL);
122
123 DefineCustomBoolVariable("auto_explain.log_analyze",
124 "Use EXPLAIN ANALYZE for plan logging.",
125 NULL,
127 false,
128 PGC_SUSET,
129 0,
130 NULL,
131 NULL,
132 NULL);
133
134 DefineCustomBoolVariable("auto_explain.log_settings",
135 "Log modified configuration parameters affecting query planning.",
136 NULL,
138 false,
139 PGC_SUSET,
140 0,
141 NULL,
142 NULL,
143 NULL);
144
145 DefineCustomBoolVariable("auto_explain.log_verbose",
146 "Use EXPLAIN VERBOSE for plan logging.",
147 NULL,
149 false,
150 PGC_SUSET,
151 0,
152 NULL,
153 NULL,
154 NULL);
155
156 DefineCustomBoolVariable("auto_explain.log_buffers",
157 "Log buffers usage.",
158 NULL,
160 false,
161 PGC_SUSET,
162 0,
163 NULL,
164 NULL,
165 NULL);
166
167 DefineCustomBoolVariable("auto_explain.log_wal",
168 "Log WAL usage.",
169 NULL,
171 false,
172 PGC_SUSET,
173 0,
174 NULL,
175 NULL,
176 NULL);
177
178 DefineCustomBoolVariable("auto_explain.log_triggers",
179 "Include trigger statistics in plans.",
180 "This has no effect unless log_analyze is also set.",
182 false,
183 PGC_SUSET,
184 0,
185 NULL,
186 NULL,
187 NULL);
188
189 DefineCustomEnumVariable("auto_explain.log_format",
190 "EXPLAIN format to be used for plan logging.",
191 NULL,
195 PGC_SUSET,
196 0,
197 NULL,
198 NULL,
199 NULL);
200
201 DefineCustomEnumVariable("auto_explain.log_level",
202 "Log level for the plan.",
203 NULL,
205 LOG,
207 PGC_SUSET,
208 0,
209 NULL,
210 NULL,
211 NULL);
212
213 DefineCustomBoolVariable("auto_explain.log_nested_statements",
214 "Log nested statements.",
215 NULL,
217 false,
218 PGC_SUSET,
219 0,
220 NULL,
221 NULL,
222 NULL);
223
224 DefineCustomBoolVariable("auto_explain.log_timing",
225 "Collect timing data, not just row counts.",
226 NULL,
228 true,
229 PGC_SUSET,
230 0,
231 NULL,
232 NULL,
233 NULL);
234
235 DefineCustomRealVariable("auto_explain.sample_rate",
236 "Fraction of queries to process.",
237 NULL,
239 1.0,
240 0.0,
241 1.0,
242 PGC_SUSET,
243 0,
244 NULL,
245 NULL,
246 NULL);
247
248 MarkGUCPrefixReserved("auto_explain");
249
250 /* Install hooks. */
259}
260
261/*
262 * ExecutorStart hook: start up logging if needed
263 */
264static void
265explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
266{
267 /*
268 * At the beginning of each top-level statement, decide whether we'll
269 * sample this statement. If nested-statement explaining is enabled,
270 * either all nested statements will be explained or none will.
271 *
272 * When in a parallel worker, we should do nothing, which we can implement
273 * cheaply by pretending we decided not to sample the current statement.
274 * If EXPLAIN is active in the parent session, data will be collected and
275 * reported back to the parent, and it's no business of ours to interfere.
276 */
277 if (nesting_level == 0)
278 {
281 else
282 current_query_sampled = false;
283 }
284
286 {
287 /* Enable per-node instrumentation iff log_analyze is required. */
289 {
292 else
298 }
299 }
300
302 prev_ExecutorStart(queryDesc, eflags);
303 else
304 standard_ExecutorStart(queryDesc, eflags);
305
307 {
308 /*
309 * Set up to track total elapsed time in ExecutorRun. Make sure the
310 * space is allocated in the per-query context so it will go away at
311 * ExecutorEnd.
312 */
313 if (queryDesc->totaltime == NULL)
314 {
315 MemoryContext oldcxt;
316
317 oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
318 queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL, false);
319 MemoryContextSwitchTo(oldcxt);
320 }
321 }
322}
323
324/*
325 * ExecutorRun hook: all we need do is track nesting depth
326 */
327static void
329 uint64 count)
330{
332 PG_TRY();
333 {
335 prev_ExecutorRun(queryDesc, direction, count);
336 else
337 standard_ExecutorRun(queryDesc, direction, count);
338 }
339 PG_FINALLY();
340 {
342 }
343 PG_END_TRY();
344}
345
346/*
347 * ExecutorFinish hook: all we need do is track nesting depth
348 */
349static void
351{
353 PG_TRY();
354 {
356 prev_ExecutorFinish(queryDesc);
357 else
358 standard_ExecutorFinish(queryDesc);
359 }
360 PG_FINALLY();
361 {
363 }
364 PG_END_TRY();
365}
366
367/*
368 * ExecutorEnd hook: log results if needed
369 */
370static void
372{
373 if (queryDesc->totaltime && auto_explain_enabled())
374 {
375 MemoryContext oldcxt;
376 double msec;
377
378 /*
379 * Make sure we operate in the per-query context, so any cruft will be
380 * discarded later during ExecutorEnd.
381 */
382 oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
383
384 /*
385 * Make sure stats accumulation is done. (Note: it's okay if several
386 * levels of hook all do this.)
387 */
388 InstrEndLoop(queryDesc->totaltime);
389
390 /* Log plan if duration is exceeded. */
391 msec = queryDesc->totaltime->total * 1000.0;
393 {
395
399 es->wal = (es->analyze && auto_explain_log_wal);
401 es->summary = es->analyze;
402 /* No support for MEMORY */
403 /* es->memory = false; */
406
408 ExplainQueryText(es, queryDesc);
410 ExplainPrintPlan(es, queryDesc);
412 ExplainPrintTriggers(es, queryDesc);
413 if (es->costs)
414 ExplainPrintJITSummary(es, queryDesc);
416
417 /* Remove last line break */
418 if (es->str->len > 0 && es->str->data[es->str->len - 1] == '\n')
419 es->str->data[--es->str->len] = '\0';
420
421 /* Fix JSON to output an object */
423 {
424 es->str->data[0] = '{';
425 es->str->data[es->str->len - 1] = '}';
426 }
427
428 /*
429 * Note: we rely on the existing logging of context or
430 * debug_query_string to identify just which statement is being
431 * reported. This isn't ideal but trying to do it here would
432 * often result in duplication.
433 */
435 (errmsg("duration: %.3f ms plan:\n%s",
436 msec, es->str->data),
437 errhidestmt(true)));
438 }
439
440 MemoryContextSwitchTo(oldcxt);
441 }
442
444 prev_ExecutorEnd(queryDesc);
445 else
446 standard_ExecutorEnd(queryDesc);
447}
static ExecutorRun_hook_type prev_ExecutorRun
Definition: auto_explain.c:80
static int auto_explain_log_min_duration
Definition: auto_explain.c:31
static bool auto_explain_log_analyze
Definition: auto_explain.c:33
static void explain_ExecutorEnd(QueryDesc *queryDesc)
Definition: auto_explain.c:371
void _PG_init(void)
Definition: auto_explain.c:96
static bool auto_explain_log_wal
Definition: auto_explain.c:36
#define auto_explain_enabled()
Definition: auto_explain.c:73
static double auto_explain_sample_rate
Definition: auto_explain.c:43
static bool auto_explain_log_nested_statements
Definition: auto_explain.c:42
static int auto_explain_log_parameter_max_length
Definition: auto_explain.c:32
static bool auto_explain_log_verbose
Definition: auto_explain.c:34
static void explain_ExecutorFinish(QueryDesc *queryDesc)
Definition: auto_explain.c:350
static int nesting_level
Definition: auto_explain.c:68
PG_MODULE_MAGIC_EXT(.name="auto_explain",.version=PG_VERSION)
static bool current_query_sampled
Definition: auto_explain.c:71
static void explain_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: auto_explain.c:328
static void explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: auto_explain.c:265
static ExecutorStart_hook_type prev_ExecutorStart
Definition: auto_explain.c:79
static const struct config_enum_entry loglevel_options[]
Definition: auto_explain.c:53
static bool auto_explain_log_timing
Definition: auto_explain.c:38
static int auto_explain_log_format
Definition: auto_explain.c:40
static bool auto_explain_log_buffers
Definition: auto_explain.c:35
static bool auto_explain_log_triggers
Definition: auto_explain.c:37
static const struct config_enum_entry format_options[]
Definition: auto_explain.c:45
static ExecutorEnd_hook_type prev_ExecutorEnd
Definition: auto_explain.c:82
static int auto_explain_log_level
Definition: auto_explain.c:41
static ExecutorFinish_hook_type prev_ExecutorFinish
Definition: auto_explain.c:81
static bool auto_explain_log_settings
Definition: auto_explain.c:39
uint64_t uint64
Definition: c.h:503
int errhidestmt(bool hide_stmt)
Definition: elog.c:1433
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define LOG
Definition: elog.h:31
#define DEBUG3
Definition: elog.h:28
#define PG_TRY(...)
Definition: elog.h:371
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
#define PG_END_TRY(...)
Definition: elog.h:396
#define DEBUG1
Definition: elog.h:30
#define NOTICE
Definition: elog.h:35
#define PG_FINALLY(...)
Definition: elog.h:388
#define INFO
Definition: elog.h:34
#define ereport(elevel,...)
Definition: elog.h:149
#define DEBUG5
Definition: elog.h:26
#define DEBUG4
Definition: elog.h:27
ExecutorEnd_hook_type ExecutorEnd_hook
Definition: execMain.c:71
ExecutorFinish_hook_type ExecutorFinish_hook
Definition: execMain.c:70
ExecutorStart_hook_type ExecutorStart_hook
Definition: execMain.c:68
void standard_ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:142
ExecutorRun_hook_type ExecutorRun_hook
Definition: execMain.c:69
void standard_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:308
void standard_ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:476
void standard_ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:416
void(* ExecutorFinish_hook_type)(QueryDesc *queryDesc)
Definition: executor.h:85
void(* ExecutorRun_hook_type)(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: executor.h:79
void(* ExecutorStart_hook_type)(QueryDesc *queryDesc, int eflags)
Definition: executor.h:75
void(* ExecutorEnd_hook_type)(QueryDesc *queryDesc)
Definition: executor.h:89
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:65
void ExplainPrintJITSummary(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:879
void ExplainQueryText(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:1063
void ExplainPrintPlan(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:759
void ExplainQueryParameters(ExplainState *es, ParamListInfo params, int maxlen)
Definition: explain.c:1078
void ExplainPrintTriggers(ExplainState *es, QueryDesc *queryDesc)
Definition: explain.c:836
void ExplainEndOutput(ExplainState *es)
void ExplainBeginOutput(ExplainState *es)
ExplainState * NewExplainState(void)
Definition: explain_state.c:61
@ EXPLAIN_FORMAT_XML
Definition: explain_state.h:30
@ EXPLAIN_FORMAT_YAML
Definition: explain_state.h:32
@ EXPLAIN_FORMAT_TEXT
Definition: explain_state.h:29
@ EXPLAIN_FORMAT_JSON
Definition: explain_state.h:31
void DefineCustomRealVariable(const char *name, const char *short_desc, const char *long_desc, double *valueAddr, double bootValue, double minValue, double maxValue, GucContext context, int flags, GucRealCheckHook check_hook, GucRealAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5189
void DefineCustomEnumVariable(const char *name, const char *short_desc, const char *long_desc, int *valueAddr, int bootValue, const struct config_enum_entry *options, GucContext context, int flags, GucEnumCheckHook check_hook, GucEnumAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5244
void DefineCustomBoolVariable(const char *name, const char *short_desc, const char *long_desc, bool *valueAddr, bool bootValue, GucContext context, int flags, GucBoolCheckHook check_hook, GucBoolAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5133
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5280
void DefineCustomIntVariable(const char *name, const char *short_desc, const char *long_desc, int *valueAddr, int bootValue, int minValue, int maxValue, GucContext context, int flags, GucIntCheckHook check_hook, GucIntAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5159
#define GUC_UNIT_MS
Definition: guc.h:239
@ PGC_SUSET
Definition: guc.h:78
#define GUC_UNIT_BYTE
Definition: guc.h:236
#define IsParallelWorker()
Definition: parallel.h:60
void InstrEndLoop(Instrumentation *instr)
Definition: instrument.c:140
Instrumentation * InstrAlloc(int n, int instrument_options, bool async_mode)
Definition: instrument.c:31
@ INSTRUMENT_ALL
Definition: instrument.h:66
@ INSTRUMENT_TIMER
Definition: instrument.h:62
@ INSTRUMENT_BUFFERS
Definition: instrument.h:63
@ INSTRUMENT_WAL
Definition: instrument.h:65
@ INSTRUMENT_ROWS
Definition: instrument.h:64
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
ScanDirection
Definition: sdir.h:25
MemoryContext es_query_cxt
Definition: execnodes.h:706
StringInfo str
Definition: explain_state.h:46
ExplainFormat format
Definition: explain_state.h:59
ParamListInfo params
Definition: execdesc.h:42
int instrument_options
Definition: execdesc.h:44
EState * estate
Definition: execdesc.h:48
struct Instrumentation * totaltime
Definition: execdesc.h:55
Definition: guc.h:174
const char * name