LCOV - code coverage report
Current view: top level - contrib/auto_explain - auto_explain.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 0 106 0.0 %
Date: 2019-09-19 16:06:56 Functions: 0 7 0.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * auto_explain.c
       4             :  *
       5             :  *
       6             :  * Copyright (c) 2008-2019, 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"
      19             : #include "executor/instrument.h"
      20             : #include "jit/jit.h"
      21             : #include "utils/guc.h"
      22             : 
      23           0 : PG_MODULE_MAGIC;
      24             : 
      25             : /* GUC variables */
      26             : static int  auto_explain_log_min_duration = -1; /* msec or -1 */
      27             : static bool auto_explain_log_analyze = false;
      28             : static bool auto_explain_log_verbose = false;
      29             : static bool auto_explain_log_buffers = false;
      30             : static bool auto_explain_log_triggers = false;
      31             : static bool auto_explain_log_timing = true;
      32             : static bool auto_explain_log_settings = false;
      33             : static int  auto_explain_log_format = EXPLAIN_FORMAT_TEXT;
      34             : static int  auto_explain_log_level = LOG;
      35             : static bool auto_explain_log_nested_statements = false;
      36             : static double auto_explain_sample_rate = 1;
      37             : 
      38             : static const struct config_enum_entry format_options[] = {
      39             :     {"text", EXPLAIN_FORMAT_TEXT, false},
      40             :     {"xml", EXPLAIN_FORMAT_XML, false},
      41             :     {"json", EXPLAIN_FORMAT_JSON, false},
      42             :     {"yaml", EXPLAIN_FORMAT_YAML, false},
      43             :     {NULL, 0, false}
      44             : };
      45             : 
      46             : static const struct config_enum_entry loglevel_options[] = {
      47             :     {"debug5", DEBUG5, false},
      48             :     {"debug4", DEBUG4, false},
      49             :     {"debug3", DEBUG3, false},
      50             :     {"debug2", DEBUG2, false},
      51             :     {"debug1", DEBUG1, false},
      52             :     {"debug", DEBUG2, true},
      53             :     {"info", INFO, false},
      54             :     {"notice", NOTICE, false},
      55             :     {"warning", WARNING, false},
      56             :     {"log", LOG, false},
      57             :     {NULL, 0, false}
      58             : };
      59             : 
      60             : /* Current nesting depth of ExecutorRun calls */
      61             : static int  nesting_level = 0;
      62             : 
      63             : /* Is the current top-level query to be sampled? */
      64             : static bool current_query_sampled = false;
      65             : 
      66             : #define auto_explain_enabled() \
      67             :     (auto_explain_log_min_duration >= 0 && \
      68             :      (nesting_level == 0 || auto_explain_log_nested_statements) && \
      69             :      current_query_sampled)
      70             : 
      71             : /* Saved hook values in case of unload */
      72             : static ExecutorStart_hook_type prev_ExecutorStart = NULL;
      73             : static ExecutorRun_hook_type prev_ExecutorRun = NULL;
      74             : static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
      75             : static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
      76             : 
      77             : void        _PG_init(void);
      78             : void        _PG_fini(void);
      79             : 
      80             : static void explain_ExecutorStart(QueryDesc *queryDesc, int eflags);
      81             : static void explain_ExecutorRun(QueryDesc *queryDesc,
      82             :                                 ScanDirection direction,
      83             :                                 uint64 count, bool execute_once);
      84             : static void explain_ExecutorFinish(QueryDesc *queryDesc);
      85             : static void explain_ExecutorEnd(QueryDesc *queryDesc);
      86             : 
      87             : 
      88             : /*
      89             :  * Module load callback
      90             :  */
      91             : void
      92           0 : _PG_init(void)
      93             : {
      94             :     /* Define custom GUC variables. */
      95           0 :     DefineCustomIntVariable("auto_explain.log_min_duration",
      96             :                             "Sets the minimum execution time above which plans will be logged.",
      97             :                             "Zero prints all plans. -1 turns this feature off.",
      98             :                             &auto_explain_log_min_duration,
      99             :                             -1,
     100             :                             -1, INT_MAX,
     101             :                             PGC_SUSET,
     102             :                             GUC_UNIT_MS,
     103             :                             NULL,
     104             :                             NULL,
     105             :                             NULL);
     106             : 
     107           0 :     DefineCustomBoolVariable("auto_explain.log_analyze",
     108             :                              "Use EXPLAIN ANALYZE for plan logging.",
     109             :                              NULL,
     110             :                              &auto_explain_log_analyze,
     111             :                              false,
     112             :                              PGC_SUSET,
     113             :                              0,
     114             :                              NULL,
     115             :                              NULL,
     116             :                              NULL);
     117             : 
     118           0 :     DefineCustomBoolVariable("auto_explain.log_settings",
     119             :                              "Log modified configuration parameters affecting query planning.",
     120             :                              NULL,
     121             :                              &auto_explain_log_settings,
     122             :                              false,
     123             :                              PGC_SUSET,
     124             :                              0,
     125             :                              NULL,
     126             :                              NULL,
     127             :                              NULL);
     128             : 
     129           0 :     DefineCustomBoolVariable("auto_explain.log_verbose",
     130             :                              "Use EXPLAIN VERBOSE for plan logging.",
     131             :                              NULL,
     132             :                              &auto_explain_log_verbose,
     133             :                              false,
     134             :                              PGC_SUSET,
     135             :                              0,
     136             :                              NULL,
     137             :                              NULL,
     138             :                              NULL);
     139             : 
     140           0 :     DefineCustomBoolVariable("auto_explain.log_buffers",
     141             :                              "Log buffers usage.",
     142             :                              NULL,
     143             :                              &auto_explain_log_buffers,
     144             :                              false,
     145             :                              PGC_SUSET,
     146             :                              0,
     147             :                              NULL,
     148             :                              NULL,
     149             :                              NULL);
     150             : 
     151           0 :     DefineCustomBoolVariable("auto_explain.log_triggers",
     152             :                              "Include trigger statistics in plans.",
     153             :                              "This has no effect unless log_analyze is also set.",
     154             :                              &auto_explain_log_triggers,
     155             :                              false,
     156             :                              PGC_SUSET,
     157             :                              0,
     158             :                              NULL,
     159             :                              NULL,
     160             :                              NULL);
     161             : 
     162           0 :     DefineCustomEnumVariable("auto_explain.log_format",
     163             :                              "EXPLAIN format to be used for plan logging.",
     164             :                              NULL,
     165             :                              &auto_explain_log_format,
     166             :                              EXPLAIN_FORMAT_TEXT,
     167             :                              format_options,
     168             :                              PGC_SUSET,
     169             :                              0,
     170             :                              NULL,
     171             :                              NULL,
     172             :                              NULL);
     173             : 
     174           0 :     DefineCustomEnumVariable("auto_explain.log_level",
     175             :                              "Log level for the plan.",
     176             :                              NULL,
     177             :                              &auto_explain_log_level,
     178             :                              LOG,
     179             :                              loglevel_options,
     180             :                              PGC_SUSET,
     181             :                              0,
     182             :                              NULL,
     183             :                              NULL,
     184             :                              NULL);
     185             : 
     186           0 :     DefineCustomBoolVariable("auto_explain.log_nested_statements",
     187             :                              "Log nested statements.",
     188             :                              NULL,
     189             :                              &auto_explain_log_nested_statements,
     190             :                              false,
     191             :                              PGC_SUSET,
     192             :                              0,
     193             :                              NULL,
     194             :                              NULL,
     195             :                              NULL);
     196             : 
     197           0 :     DefineCustomBoolVariable("auto_explain.log_timing",
     198             :                              "Collect timing data, not just row counts.",
     199             :                              NULL,
     200             :                              &auto_explain_log_timing,
     201             :                              true,
     202             :                              PGC_SUSET,
     203             :                              0,
     204             :                              NULL,
     205             :                              NULL,
     206             :                              NULL);
     207             : 
     208           0 :     DefineCustomRealVariable("auto_explain.sample_rate",
     209             :                              "Fraction of queries to process.",
     210             :                              NULL,
     211             :                              &auto_explain_sample_rate,
     212             :                              1.0,
     213             :                              0.0,
     214             :                              1.0,
     215             :                              PGC_SUSET,
     216             :                              0,
     217             :                              NULL,
     218             :                              NULL,
     219             :                              NULL);
     220             : 
     221           0 :     EmitWarningsOnPlaceholders("auto_explain");
     222             : 
     223             :     /* Install hooks. */
     224           0 :     prev_ExecutorStart = ExecutorStart_hook;
     225           0 :     ExecutorStart_hook = explain_ExecutorStart;
     226           0 :     prev_ExecutorRun = ExecutorRun_hook;
     227           0 :     ExecutorRun_hook = explain_ExecutorRun;
     228           0 :     prev_ExecutorFinish = ExecutorFinish_hook;
     229           0 :     ExecutorFinish_hook = explain_ExecutorFinish;
     230           0 :     prev_ExecutorEnd = ExecutorEnd_hook;
     231           0 :     ExecutorEnd_hook = explain_ExecutorEnd;
     232           0 : }
     233             : 
     234             : /*
     235             :  * Module unload callback
     236             :  */
     237             : void
     238           0 : _PG_fini(void)
     239             : {
     240             :     /* Uninstall hooks. */
     241           0 :     ExecutorStart_hook = prev_ExecutorStart;
     242           0 :     ExecutorRun_hook = prev_ExecutorRun;
     243           0 :     ExecutorFinish_hook = prev_ExecutorFinish;
     244           0 :     ExecutorEnd_hook = prev_ExecutorEnd;
     245           0 : }
     246             : 
     247             : /*
     248             :  * ExecutorStart hook: start up logging if needed
     249             :  */
     250             : static void
     251           0 : explain_ExecutorStart(QueryDesc *queryDesc, int eflags)
     252             : {
     253             :     /*
     254             :      * At the beginning of each top-level statement, decide whether we'll
     255             :      * sample this statement.  If nested-statement explaining is enabled,
     256             :      * either all nested statements will be explained or none will.
     257             :      *
     258             :      * When in a parallel worker, we should do nothing, which we can implement
     259             :      * cheaply by pretending we decided not to sample the current statement.
     260             :      * If EXPLAIN is active in the parent session, data will be collected and
     261             :      * reported back to the parent, and it's no business of ours to interfere.
     262             :      */
     263           0 :     if (nesting_level == 0)
     264             :     {
     265           0 :         if (auto_explain_log_min_duration >= 0 && !IsParallelWorker())
     266           0 :             current_query_sampled = (random() < auto_explain_sample_rate *
     267             :                                      ((double) MAX_RANDOM_VALUE + 1));
     268             :         else
     269           0 :             current_query_sampled = false;
     270             :     }
     271             : 
     272           0 :     if (auto_explain_enabled())
     273             :     {
     274             :         /* Enable per-node instrumentation iff log_analyze is required. */
     275           0 :         if (auto_explain_log_analyze && (eflags & EXEC_FLAG_EXPLAIN_ONLY) == 0)
     276             :         {
     277           0 :             if (auto_explain_log_timing)
     278           0 :                 queryDesc->instrument_options |= INSTRUMENT_TIMER;
     279             :             else
     280           0 :                 queryDesc->instrument_options |= INSTRUMENT_ROWS;
     281           0 :             if (auto_explain_log_buffers)
     282           0 :                 queryDesc->instrument_options |= INSTRUMENT_BUFFERS;
     283             :         }
     284             :     }
     285             : 
     286           0 :     if (prev_ExecutorStart)
     287           0 :         prev_ExecutorStart(queryDesc, eflags);
     288             :     else
     289           0 :         standard_ExecutorStart(queryDesc, eflags);
     290             : 
     291           0 :     if (auto_explain_enabled())
     292             :     {
     293             :         /*
     294             :          * Set up to track total elapsed time in ExecutorRun.  Make sure the
     295             :          * space is allocated in the per-query context so it will go away at
     296             :          * ExecutorEnd.
     297             :          */
     298           0 :         if (queryDesc->totaltime == NULL)
     299             :         {
     300             :             MemoryContext oldcxt;
     301             : 
     302           0 :             oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
     303           0 :             queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL);
     304           0 :             MemoryContextSwitchTo(oldcxt);
     305             :         }
     306             :     }
     307           0 : }
     308             : 
     309             : /*
     310             :  * ExecutorRun hook: all we need do is track nesting depth
     311             :  */
     312             : static void
     313           0 : explain_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction,
     314             :                     uint64 count, bool execute_once)
     315             : {
     316           0 :     nesting_level++;
     317           0 :     PG_TRY();
     318             :     {
     319           0 :         if (prev_ExecutorRun)
     320           0 :             prev_ExecutorRun(queryDesc, direction, count, execute_once);
     321             :         else
     322           0 :             standard_ExecutorRun(queryDesc, direction, count, execute_once);
     323           0 :         nesting_level--;
     324             :     }
     325           0 :     PG_CATCH();
     326             :     {
     327           0 :         nesting_level--;
     328           0 :         PG_RE_THROW();
     329             :     }
     330           0 :     PG_END_TRY();
     331           0 : }
     332             : 
     333             : /*
     334             :  * ExecutorFinish hook: all we need do is track nesting depth
     335             :  */
     336             : static void
     337           0 : explain_ExecutorFinish(QueryDesc *queryDesc)
     338             : {
     339           0 :     nesting_level++;
     340           0 :     PG_TRY();
     341             :     {
     342           0 :         if (prev_ExecutorFinish)
     343           0 :             prev_ExecutorFinish(queryDesc);
     344             :         else
     345           0 :             standard_ExecutorFinish(queryDesc);
     346           0 :         nesting_level--;
     347             :     }
     348           0 :     PG_CATCH();
     349             :     {
     350           0 :         nesting_level--;
     351           0 :         PG_RE_THROW();
     352             :     }
     353           0 :     PG_END_TRY();
     354           0 : }
     355             : 
     356             : /*
     357             :  * ExecutorEnd hook: log results if needed
     358             :  */
     359             : static void
     360           0 : explain_ExecutorEnd(QueryDesc *queryDesc)
     361             : {
     362           0 :     if (queryDesc->totaltime && auto_explain_enabled())
     363             :     {
     364             :         double      msec;
     365             : 
     366             :         /*
     367             :          * Make sure stats accumulation is done.  (Note: it's okay if several
     368             :          * levels of hook all do this.)
     369             :          */
     370           0 :         InstrEndLoop(queryDesc->totaltime);
     371             : 
     372             :         /* Log plan if duration is exceeded. */
     373           0 :         msec = queryDesc->totaltime->total * 1000.0;
     374           0 :         if (msec >= auto_explain_log_min_duration)
     375             :         {
     376           0 :             ExplainState *es = NewExplainState();
     377             : 
     378           0 :             es->analyze = (queryDesc->instrument_options && auto_explain_log_analyze);
     379           0 :             es->verbose = auto_explain_log_verbose;
     380           0 :             es->buffers = (es->analyze && auto_explain_log_buffers);
     381           0 :             es->timing = (es->analyze && auto_explain_log_timing);
     382           0 :             es->summary = es->analyze;
     383           0 :             es->format = auto_explain_log_format;
     384           0 :             es->settings = auto_explain_log_settings;
     385             : 
     386           0 :             ExplainBeginOutput(es);
     387           0 :             ExplainQueryText(es, queryDesc);
     388           0 :             ExplainPrintPlan(es, queryDesc);
     389           0 :             if (es->analyze && auto_explain_log_triggers)
     390           0 :                 ExplainPrintTriggers(es, queryDesc);
     391           0 :             if (es->costs)
     392           0 :                 ExplainPrintJITSummary(es, queryDesc);
     393           0 :             ExplainEndOutput(es);
     394             : 
     395             :             /* Remove last line break */
     396           0 :             if (es->str->len > 0 && es->str->data[es->str->len - 1] == '\n')
     397           0 :                 es->str->data[--es->str->len] = '\0';
     398             : 
     399             :             /* Fix JSON to output an object */
     400           0 :             if (auto_explain_log_format == EXPLAIN_FORMAT_JSON)
     401             :             {
     402           0 :                 es->str->data[0] = '{';
     403           0 :                 es->str->data[es->str->len - 1] = '}';
     404             :             }
     405             : 
     406             :             /*
     407             :              * Note: we rely on the existing logging of context or
     408             :              * debug_query_string to identify just which statement is being
     409             :              * reported.  This isn't ideal but trying to do it here would
     410             :              * often result in duplication.
     411             :              */
     412           0 :             ereport(auto_explain_log_level,
     413             :                     (errmsg("duration: %.3f ms  plan:\n%s",
     414             :                             msec, es->str->data),
     415             :                      errhidestmt(true)));
     416             : 
     417           0 :             pfree(es->str->data);
     418             :         }
     419             :     }
     420             : 
     421           0 :     if (prev_ExecutorEnd)
     422           0 :         prev_ExecutorEnd(queryDesc);
     423             :     else
     424           0 :         standard_ExecutorEnd(queryDesc);
     425           0 : }

Generated by: LCOV version 1.13