pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Michael Paquier <michael@paquier.xyz>
To: Gaurav Singh <gaurav.singh@yugabyte.com>
Cc: Sami Imseih <samimseih.pg@gmail.com>
Cc: pgsql-bugs@lists.postgresql.org
Subject: Re: pg_stat_statements stores WITH HOLD cursor query with literals
Date: Fri, 23 Oct 2026 14:19:32 +0900
Message-ID: <atruZFUdH40HVUJh@paquier.xyz> (raw)
In-Reply-To: <atl-hB3haQF62tlN@paquier.xyz>
References: <CAEcQ1bZrgwKsauC=03otebkLk77Zc_hYNjhTP3OUdpXs++u+BA@mail.gmail.com>
	<CAN12+YLPn65OFk+POCnLo1QJ=n3Gooz6Bsz_VsF2uh5c45iuPQ@mail.gmail.com>
	<CAEcQ1bZJUzjxe-tSOU25T3XtMEL3YyC4ESjk9k+KVAHRvyhtAQ@mail.gmail.com>
	<CAN12+Y+KwJc8HH9BRzyfuG9vcU-=4vv_gc2BQ24sGpmxZi9Caw@mail.gmail.com>
	<CAN12+YL7jf5_04Lme1Qaf2=_JuMAKAoCQiSY7-4__Svfc4igBA@mail.gmail.com>
	<CAEcQ1bYf03gGvvZWXCTv2L198zNArFrVoNDNQWecJ_7YmfE6UA@mail.gmail.com>
	<CAN12+YJdyb6zRHU+3owvBpKxgqB-tweRjjhUUTa5TyDn433GRw@mail.gmail.com>
	<CAEcQ1bZ0oW_RaNFAo6S9COOLnhdskx=z6p285WALq10QgVpYBA@mail.gmail.com>
	<atl-hB3haQF62tlN@paquier.xyz>

On Thu, Oct 22, 2026 at 12:09:56PM +0900, Michael Paquier wrote:
> We have a similar concept for ExplainState with its extension_state
> indexed by GetExplainExtensionId() based on an extension name.
> Perhaps we should do something similar for QueryDesc?  That would take
> care of the conflicting states across extensions at least, giving
> extensions way to store in the QueryDesc what they want.  Here, that's
> the nesting_level that you want to track *only* in PGSS and have no
> other extensions meddle with it.

This was itching me, so I have looked at what it would look like,
finishing with the attached set of two patches:
- One to introduce a backend-side facility to give for extensions a
way to plug in custom data into QueryDesc.
- The second patch is a refactored v2, that makes use of the new
infra.

That feels rather neat.  This facility could be extended to other
things, like auto_explain perhaps?
--
Michael

Attachments: download all (3 files, .tar.gz)

v3-0001-Add-custom-extension-states-to-QueryDesc.patch (text/plain, 6.5K) download From 416354866d1379793da8d95e754b676c933228e9 Mon Sep 17 00:00:00 2001 From: Michael Paquier <michael@paquier.xyz> Date: Fri, 23 Oct 2026 14:05:23 +0900 Subject: [PATCH v3 1/2] Add custom extension states to QueryDesc Extensions sometimes need to carry private data from one executor hook to another for a given query. ExecutorEnd() can run in a different context than ExecutorStart(), so backend-wide variables cannot be used for that. This commit adds a way for loadable modules to attach private state to a QueryDesc, modeled on the extension state of PlannerGlobal, PlannerInfo, RelOptInfo and ExplainState. GetQueryDescExtensionId() maps an extension name to a backend-local ID. SetQueryDescExtensionState() and GetQueryDescExtensionState() store and fetch an opaque pointer for that ID. The array of pointers is allocated in the memory context of the QueryDesc, and is freed by FreeQueryDesc(). What the pointers refer to is owned by the extensions. There are no users of this facility yet. A follow-up commit will make use of it. Author: Michael Paquier <michael@paquier.xyz> Discussion: https://postgr.es/m/ --- src/include/executor/execdesc.h | 29 ++++++++++ src/backend/tcop/pquery.c | 95 ++++++++++++++++++++++++++++++++- 2 files changed, 123 insertions(+), 1 deletion(-) diff --git a/src/include/executor/execdesc.h b/src/include/executor/execdesc.h index 37c2576e4bc9..b83efbd3315a 100644 --- a/src/include/executor/execdesc.h +++ b/src/include/executor/execdesc.h @@ -55,6 +55,10 @@ typedef struct QueryDesc /* This field is allocated by ExecutorStart if needed */ struct Instrumentation *query_instr; /* query level instrumentation */ + + /* Private state of extensions; see GetQueryDescExtensionId() */ + void **extension_state; + int extension_state_allocated; } QueryDesc; /* in pquery.c */ @@ -69,4 +73,29 @@ extern QueryDesc *CreateQueryDesc(PlannedStmt *plannedstmt, extern void FreeQueryDesc(QueryDesc *qdesc); +/* + * Loadable modules can attach private state to a QueryDesc. Get an integer + * ID for the module with GetQueryDescExtensionId(), which returns the same ID + * for the same name within a backend, and use it with the functions below. + * The state lives as long as the QueryDesc, and is not touched by core + * otherwise, so the module is responsible for what it points to. + */ +extern int GetQueryDescExtensionId(const char *extension_name); +extern void SetQueryDescExtensionState(QueryDesc *qdesc, int extension_id, + void *opaque); + +/* + * Get extension-specific state from a QueryDesc, or NULL if none was set. + */ +static inline void * +GetQueryDescExtensionState(QueryDesc *qdesc, int extension_id) +{ + Assert(extension_id >= 0); + + if (extension_id >= qdesc->extension_state_allocated) + return NULL; + + return qdesc->extension_state[extension_id]; +} + #endif /* EXECDESC_H */ diff --git a/src/backend/tcop/pquery.c b/src/backend/tcop/pquery.c index fa2ef20f178a..a94550544cec 100644 --- a/src/backend/tcop/pquery.c +++ b/src/backend/tcop/pquery.c @@ -23,6 +23,7 @@ #include "executor/tstoreReceiver.h" #include "miscadmin.h" #include "pg_trace.h" +#include "port/pg_bitutils.h" #include "tcop/pquery.h" #include "tcop/utility.h" #include "utils/memutils.h" @@ -97,6 +98,10 @@ CreateQueryDesc(PlannedStmt *plannedstmt, /* not yet executed */ qd->already_executed = false; + /* no extension state yet */ + qd->extension_state = NULL; + qd->extension_state_allocated = 0; + return qd; } @@ -113,10 +118,98 @@ FreeQueryDesc(QueryDesc *qdesc) UnregisterSnapshot(qdesc->snapshot); UnregisterSnapshot(qdesc->crosscheck_snapshot); - /* Only the QueryDesc itself need be freed */ + /* + * Free the array of extension state pointers. What these point to is + * owned by the extensions. + */ + if (qdesc->extension_state != NULL) + pfree(qdesc->extension_state); + + /* Free the QueryDesc itself */ pfree(qdesc); } +static const char **QueryDescExtensionNameArray = NULL; +static int QueryDescExtensionNamesAssigned = 0; +static int QueryDescExtensionNamesAllocated = 0; + +/* + * Map the name of an extension to an integer ID, to be used with + * SetQueryDescExtensionState() and GetQueryDescExtensionState(). + * + * Within the lifetime of a particular backend, the same name will be mapped + * to the same ID every time. IDs are not stable across backends. + */ +int +GetQueryDescExtensionId(const char *extension_name) +{ + /* Search for an existing extension by this name; if found, return ID. */ + for (int i = 0; i < QueryDescExtensionNamesAssigned; ++i) + if (strcmp(QueryDescExtensionNameArray[i], extension_name) == 0) + return i; + + /* If there is no array yet, create one. */ + if (QueryDescExtensionNameArray == NULL) + { + QueryDescExtensionNamesAllocated = 16; + QueryDescExtensionNameArray = (const char **) + MemoryContextAlloc(TopMemoryContext, + QueryDescExtensionNamesAllocated + * sizeof(char *)); + } + + /* If there's an array but it's currently full, expand it. */ + if (QueryDescExtensionNamesAssigned >= QueryDescExtensionNamesAllocated) + { + int i = pg_nextpower2_32(QueryDescExtensionNamesAssigned + 1); + + QueryDescExtensionNameArray = + repalloc_array(QueryDescExtensionNameArray, const char *, i); + QueryDescExtensionNamesAllocated = i; + } + + /* Assign and return new ID. The name is copied, to be on the safe side. */ + QueryDescExtensionNameArray[QueryDescExtensionNamesAssigned] = + MemoryContextStrdup(TopMemoryContext, extension_name); + return QueryDescExtensionNamesAssigned++; +} + +/* + * Store extension-specific state into a QueryDesc. + * + * The array of pointers is allocated in the memory context of the QueryDesc, + * and is freed by FreeQueryDesc(). + */ +void +SetQueryDescExtensionState(QueryDesc *qdesc, int extension_id, void *opaque) +{ + Assert(extension_id >= 0); + + /* If there is no array yet, create one. */ + if (qdesc->extension_state == NULL) + { + qdesc->extension_state_allocated = + Max(4, pg_nextpower2_32(extension_id + 1)); + qdesc->extension_state = + MemoryContextAllocZero(GetMemoryChunkContext(qdesc), + qdesc->extension_state_allocated + * sizeof(void *)); + } + + /* If there's an array but it's currently full, expand it. */ + if (extension_id >= qdesc->extension_state_allocated) + { + int i = pg_nextpower2_32(extension_id + 1); + + qdesc->extension_state = + repalloc0_array(qdesc->extension_state, void *, + qdesc->extension_state_allocated, i); + qdesc->extension_state_allocated = i; + } + + qdesc->extension_state[extension_id] = opaque; +} + /* * ProcessQuery -- 2.56.0
v3-0002-pg_stat_statements-Fix-toplevel-tracking-across-n.patch (text/plain, 9.0K) download From 715a60ffd8e849da453afe9830d187f2f8ac3c32 Mon Sep 17 00:00:00 2001 From: Michael Paquier <michael@paquier.xyz> Date: Fri, 23 Oct 2026 14:17:39 +0900 Subject: [PATCH v3 2/2] 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. No backpatch is done, due to the ABI changes required. Reported-by: Gaurav Singh <gaurav.singh@yugabyte.com> Author: Sami Imseih <samimseih@gmail.com> Author: Michael Paquier <michael@paquier.xyz> Discussion: https://postgr.es/m/CAEcQ1bZrgwKsauC=03otebkLk77Zc_hYNjhTP3OUdpXs++u+BA@mail.gmail.com Discussion: https://postgr.es/m/CAA5RZ0v281uwSudcFrY8BymSRDM4J6PAHfzqg_9R+i7zWbTb2A@mail.gmail.com --- .../expected/level_tracking.out | 25 +++++++++++ .../pg_stat_statements/pg_stat_statements.c | 43 ++++++++++++++++++- .../pg_stat_statements/sql/level_tracking.sql | 11 +++++ src/tools/pgindent/typedefs.list | 1 + 4 files changed, 78 insertions(+), 2 deletions(-) diff --git a/contrib/pg_stat_statements/expected/level_tracking.out b/contrib/pg_stat_statements/expected/level_tracking.out index 832d65e97cad..ccebf8b29604 100644 --- a/contrib/pg_stat_statements/expected/level_tracking.out +++ b/contrib/pg_stat_statements/expected/level_tracking.out @@ -1151,6 +1151,31 @@ SELECT toplevel, calls, query FROM pg_stat_statements t | 1 | SELECT pg_stat_statements_reset() IS NOT NULL AS t (7 rows) +-- DECLARE CURSOR, all-level tracking with implicit close. +SET pg_stat_statements.track = 'all'; +SELECT pg_stat_statements_reset() IS NOT NULL AS t; + t +--- + t +(1 row) + +BEGIN; +DECLARE FOOCUR CURSOR FOR SELECT * FROM stats_track_tab WHERE x = 1; +FETCH FORWARD 1 FROM foocur; + x +--- +(0 rows) + +COMMIT; +SELECT toplevel, calls, query FROM pg_stat_statements + WHERE query LIKE 'DECLARE FOOCUR%' + ORDER BY query COLLATE "C", toplevel; + toplevel | calls | query +----------+-------+----------------------------------------------------------------------- + t | 1 | DECLARE FOOCUR CURSOR FOR SELECT * FROM stats_track_tab WHERE x = $1 + f | 1 | DECLARE FOOCUR CURSOR FOR SELECT * FROM stats_track_tab WHERE x = $1; +(2 rows) + -- DECLARE CURSOR, top-level tracking. SET pg_stat_statements.track = 'top'; SELECT pg_stat_statements_reset() IS NOT NULL AS t; diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c index 4562222c9fcf..8db4b3d6e24b 100644 --- a/contrib/pg_stat_statements/pg_stat_statements.c +++ b/contrib/pg_stat_statements/pg_stat_statements.c @@ -274,6 +274,19 @@ static const ShmemCallbacks pgss_shmem_callbacks = { /* Current nesting depth of planner/ExecutorRun/ProcessUtility calls */ static int nesting_level = 0; +/* + * State saved in a QueryDesc at ExecutorStart, for use at ExecutorEnd. A + * query may end at a different nesting level than the one it started at, + * for example a cursor declared in a transaction and closed at COMMIT. + */ +typedef struct pgssQueryState +{ + int nesting_level; /* nesting level at ExecutorStart */ +} pgssQueryState; + +/* ID of pg_stat_statements for QueryDesc extension state */ +static int pgss_queryDesc_id = -1; + /* Saved hook values */ static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL; static planner_hook_type prev_planner_hook = NULL; @@ -356,6 +369,7 @@ static void pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString, DestReceiver *dest, QueryCompletion *qc); static void pgss_store(const char *query, int64 queryId, int query_location, int query_len, + bool toplevel, pgssStoreKind kind, double total_time, uint64 rows, const BufferUsage *bufusage, @@ -474,6 +488,11 @@ _PG_init(void) */ RegisterShmemCallbacks(&pgss_shmem_callbacks); + /* + * Get an ID to store state in QueryDesc. + */ + pgss_queryDesc_id = GetQueryDescExtensionId("pg_stat_statements"); + /* * Install hooks. */ @@ -866,6 +885,7 @@ pgss_post_parse_analyze(ParseState *pstate, Query *query, const JumbleState *jst query->queryId, query->stmt_location, query->stmt_len, + nesting_level == 0, PGSS_INVALID, 0, 0, @@ -948,6 +968,7 @@ pgss_planner(Query *parse, parse->queryId, parse->stmt_location, parse->stmt_len, + nesting_level == 0, PGSS_PLAN, INSTR_TIME_GET_MILLISEC(duration), 0, @@ -992,6 +1013,8 @@ pgss_planner(Query *parse, static void pgss_ExecutorStart(QueryDesc *queryDesc, int eflags) { + pgssQueryState *qstate; + /* * If query has queryId zero, don't track it. This prevents double * counting of optimizable statements that are directly contained in @@ -1001,6 +1024,12 @@ pgss_ExecutorStart(QueryDesc *queryDesc, int eflags) { /* Request all summary instrumentation, i.e. timing, buffers and WAL */ queryDesc->query_instr_options |= INSTRUMENT_ALL; + + /* Remember the nesting level for ExecutorEnd */ + qstate = MemoryContextAlloc(GetMemoryChunkContext(queryDesc), + sizeof(pgssQueryState)); + qstate->nesting_level = nesting_level; + SetQueryDescExtensionState(queryDesc, pgss_queryDesc_id, qstate); } if (prev_ExecutorStart) @@ -1058,14 +1087,22 @@ static void pgss_ExecutorEnd(QueryDesc *queryDesc) { int64 queryId = queryDesc->plannedstmt->queryId; + pgssQueryState *qstate = GetQueryDescExtensionState(queryDesc, + pgss_queryDesc_id); + /* + * Use the nesting level saved at ExecutorStart, if available, since the + * query may end at a different level (e.g. a cursor closed at COMMIT). + */ if (queryId != INT64CONST(0) && queryDesc->query_instr && - pgss_enabled(nesting_level)) + qstate != NULL && + pgss_enabled(qstate->nesting_level)) { pgss_store(queryDesc->sourceText, queryId, queryDesc->plannedstmt->stmt_location, queryDesc->plannedstmt->stmt_len, + qstate->nesting_level == 0, PGSS_EXEC, INSTR_TIME_GET_MILLISEC(queryDesc->query_instr->total), queryDesc->estate->es_total_processed, @@ -1202,6 +1239,7 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString, saved_queryId, saved_stmt_location, saved_stmt_len, + nesting_level == 0, PGSS_EXEC, INSTR_TIME_GET_MILLISEC(duration), rows, @@ -1267,6 +1305,7 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString, static void pgss_store(const char *query, int64 queryId, int query_location, int query_len, + bool toplevel, pgssStoreKind kind, double total_time, uint64 rows, const BufferUsage *bufusage, @@ -1310,7 +1349,7 @@ pgss_store(const char *query, int64 queryId, key.userid = GetUserId(); key.dbid = MyDatabaseId; key.queryid = queryId; - key.toplevel = (nesting_level == 0); + key.toplevel = toplevel; /* Lookup the hash table entry with shared lock. */ LWLockAcquire(&pgss->lock.lock, LW_SHARED); diff --git a/contrib/pg_stat_statements/sql/level_tracking.sql b/contrib/pg_stat_statements/sql/level_tracking.sql index 003efb8184b1..cc14a9808dd5 100644 --- a/contrib/pg_stat_statements/sql/level_tracking.sql +++ b/contrib/pg_stat_statements/sql/level_tracking.sql @@ -262,6 +262,17 @@ COMMIT; SELECT toplevel, calls, query FROM pg_stat_statements ORDER BY query COLLATE "C"; +-- DECLARE CURSOR, all-level tracking with implicit close. +SET pg_stat_statements.track = 'all'; +SELECT pg_stat_statements_reset() IS NOT NULL AS t; +BEGIN; +DECLARE FOOCUR CURSOR FOR SELECT * FROM stats_track_tab WHERE x = 1; +FETCH FORWARD 1 FROM foocur; +COMMIT; +SELECT toplevel, calls, query FROM pg_stat_statements + WHERE query LIKE 'DECLARE FOOCUR%' + ORDER BY query COLLATE "C", toplevel; + -- DECLARE CURSOR, top-level tracking. SET pg_stat_statements.track = 'top'; SELECT pg_stat_statements_reset() IS NOT NULL AS t; diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index a7a8dbdd23f7..cfef572df80f 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -4124,6 +4124,7 @@ pgsql_thing_t pgssEntry pgssGlobalStats pgssHashKey +pgssQueryState pgssSharedState pgssStoreKind pgssVersion -- 2.56.0
signature.asc (application/pgp-signature, 832B) download

view thread (18+ messages)  latest in thread

Message-ID: <atruZFUdH40HVUJh@paquier.xyz>
Permalink:  ../atruZFUdH40HVUJh@paquier.xyz/
Also on:    postgresql.org/message-id/atruZFUdH40HVUJh@paquier.xyz

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-bugs@postgresql.org
  Cc: michael@paquier.xyz, gaurav.singh@yugabyte.com, samimseih.pg@gmail.com
  Subject: Re: pg_stat_statements stores WITH HOLD cursor query with literals
  In-Reply-To: <atruZFUdH40HVUJh@paquier.xyz>
  References: <CAEcQ1bZrgwKsauC=03otebkLk77Zc_hYNjhTP3OUdpXs++u+BA@mail.gmail.com> <CAN12+YLPn65OFk+POCnLo1QJ=n3Gooz6Bsz_VsF2uh5c45iuPQ@mail.gmail.com> <CAEcQ1bZJUzjxe-tSOU25T3XtMEL3YyC4ESjk9k+KVAHRvyhtAQ@mail.gmail.com> <CAN12+Y+KwJc8HH9BRzyfuG9vcU-=4vv_gc2BQ24sGpmxZi9Caw@mail.gmail.com> <CAN12+YL7jf5_04Lme1Qaf2=_JuMAKAoCQiSY7-4__Svfc4igBA@mail.gmail.com> <CAEcQ1bYf03gGvvZWXCTv2L198zNArFrVoNDNQWecJ_7YmfE6UA@mail.gmail.com> <CAN12+YJdyb6zRHU+3owvBpKxgqB-tweRjjhUUTa5TyDn433GRw@mail.gmail.com> <CAEcQ1bZ0oW_RaNFAo6S9COOLnhdskx=z6p285WALq10QgVpYBA@mail.gmail.com> <atl-hB3haQF62tlN@paquier.xyz> <atruZFUdH40HVUJh@paquier.xyz>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox