pg_stat_statements: Fix toplevel tracking across nesting levels

pg_stat_statements decides whether a query is toplevel from the
nesting level at the time each hook runs.  A QueryDesc can outlive the
level it started at.  For example, a cursor's query starts at level 1,
inside DECLARE, but if the cursor is closed implicitly at COMMIT,
ExecutorEnd runs at level 0.  The entry created for the query at parse
analysis has toplevel = false, so ExecutorEnd misses it and stores a
duplicate with the raw query text and toplevel = true.

The same happens with track = top when another extension such as
auto_explain requests query instrumentation.  ExecutorEnd stores the
query even though ExecutorStart did not track it.

PGSS is upgraded to save the nesting level in the extension state of the
QueryDesc when ExecutorStart() tracks a query.  ExecutorEnd() then uses
it in place of the current level and skips the query if no state was
saved.

For now, only the nesting level is tracked in the private extension
state attached to QueryDesc by PGSS.  auto_explain is not touched
either.  All these pieces are left as future improvements.

No backpatch is done, due to the ABI changes required in QueryDesc.
This relies on the work done previously in e5d5d1ad1e3a.

Reported-by: Gaurav Singh <[email protected]>
Author: Sami Imseih <[email protected]>
Author: Michael Paquier <[email protected]>
Discussion: 
https://postgr.es/m/CAEcQ1bZrgwKsauC=03otebklk77zc_hynjhtp3oudpxs++u...@mail.gmail.com
Discussion: 
https://postgr.es/m/caa5rz0v281uwsudcfry8bymsrdm4j6pahfzqg_9r+i7zwbt...@mail.gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/23bf901fa5306b245e23ace52e5a6777ea08bed6

Modified Files
--------------
.../pg_stat_statements/expected/level_tracking.out | 25 +++++++++++++
contrib/pg_stat_statements/pg_stat_statements.c    | 43 +++++++++++++++++++++-
contrib/pg_stat_statements/sql/level_tracking.sql  | 11 ++++++
src/tools/pgindent/typedefs.list                   |  1 +
4 files changed, 78 insertions(+), 2 deletions(-)

Reply via email to