PostgreSQL Source Code git master
plancache.h
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * plancache.h
4 * Plan cache definitions.
5 *
6 * See plancache.c for comments.
7 *
8 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
10 *
11 * src/include/utils/plancache.h
12 *
13 *-------------------------------------------------------------------------
14 */
15#ifndef PLANCACHE_H
16#define PLANCACHE_H
17
18#include "access/tupdesc.h"
19#include "lib/ilist.h"
20#include "nodes/params.h"
21#include "tcop/cmdtag.h"
23#include "utils/resowner.h"
24
25
26/* Forward declarations, to avoid including parsenodes.h here */
27struct Query;
28struct RawStmt;
29
30/* possible values for plan_cache_mode */
31typedef enum
32{
37
38/* GUC parameter */
40
41/* Optional callback to editorialize on rewritten parse trees */
42typedef void (*PostRewriteHook) (List *querytree_list, void *arg);
43
44#define CACHEDPLANSOURCE_MAGIC 195726186
45#define CACHEDPLAN_MAGIC 953717834
46#define CACHEDEXPR_MAGIC 838275847
47
48/*
49 * CachedPlanSource (which might better have been called CachedQuery)
50 * represents a SQL query that we expect to use multiple times. It stores the
51 * query source text, the source parse tree, and the analyzed-and-rewritten
52 * query tree, as well as adjunct data. Cache invalidation can happen as a
53 * result of DDL affecting objects used by the query. In that case we discard
54 * the analyzed-and-rewritten query tree, and rebuild it when next needed.
55 *
56 * There are two ways in which the source query can be represented: either
57 * as a raw parse tree, or as an analyzed-but-not-rewritten parse tree.
58 * In the latter case we expect that cache invalidation need not affect
59 * the parse-analysis results, only the rewriting and planning steps.
60 * Only one of raw_parse_tree and analyzed_parse_tree can be non-NULL.
61 * (If both are NULL, the CachedPlanSource represents an empty query.)
62 * Note that query_string is typically just an empty string when the
63 * source query is an analyzed parse tree; also, param_types, num_params,
64 * parserSetup, and parserSetupArg will not be used.
65 *
66 * An actual execution plan, represented by CachedPlan, is derived from the
67 * CachedPlanSource when we need to execute the query. The plan could be
68 * either generic (usable with any set of plan parameters) or custom (for a
69 * specific set of parameters). plancache.c contains the logic that decides
70 * which way to do it for any particular execution. If we are using a generic
71 * cached plan then it is meant to be re-used across multiple executions, so
72 * callers must always treat CachedPlans as read-only.
73 *
74 * Once successfully built and "saved", CachedPlanSources typically live
75 * for the life of the backend, although they can be dropped explicitly.
76 * CachedPlans are reference-counted and go away automatically when the last
77 * reference is dropped. A CachedPlan can outlive the CachedPlanSource it
78 * was created from.
79 *
80 * An "unsaved" CachedPlanSource can be used for generating plans, but it
81 * lives in transient storage and will not be updated in response to sinval
82 * events.
83 *
84 * CachedPlans made from saved CachedPlanSources are likewise in permanent
85 * storage, so to avoid memory leaks, the reference-counted references to them
86 * must be held in permanent data structures or ResourceOwners. CachedPlans
87 * made from unsaved CachedPlanSources are in children of the caller's
88 * memory context, so references to them should not be longer-lived than
89 * that context. (Reference counting is somewhat pro forma in that case,
90 * though it may be useful if the CachedPlan can be discarded early.)
91 *
92 * A CachedPlanSource has two associated memory contexts: one that holds the
93 * struct itself, the query source text and the source parse tree, and another
94 * context that holds the rewritten query tree and associated data. This
95 * allows the query tree to be discarded easily when it is invalidated.
96 *
97 * Some callers wish to use the CachedPlan API even with one-shot queries
98 * that have no reason to be saved at all. We therefore support a "oneshot"
99 * variant that does no data copying or invalidation checking. In this case
100 * there are no separate memory contexts: the CachedPlanSource struct and
101 * all subsidiary data live in the caller's CurrentMemoryContext, and there
102 * is no way to free memory short of clearing that entire context. A oneshot
103 * plan is always treated as unsaved.
104 */
105typedef struct CachedPlanSource
106{
107 int magic; /* should equal CACHEDPLANSOURCE_MAGIC */
108 struct RawStmt *raw_parse_tree; /* output of raw_parser(), or NULL */
109 struct Query *analyzed_parse_tree; /* analyzed parse tree, or NULL */
110 const char *query_string; /* source text of query */
111 CommandTag commandTag; /* command tag for query */
112 Oid *param_types; /* array of parameter type OIDs, or NULL */
113 int num_params; /* length of param_types array */
114 ParserSetupHook parserSetup; /* alternative parameter spec method */
116 PostRewriteHook postRewrite; /* see SetPostRewriteHook */
118 int cursor_options; /* cursor options used for planning */
119 bool fixed_result; /* disallow change in result tupdesc? */
120 TupleDesc resultDesc; /* result type; NULL = doesn't return tuples */
121 MemoryContext context; /* memory context holding all above */
122 /* These fields describe the current analyzed-and-rewritten query tree: */
123 List *query_list; /* list of Query nodes, or NIL if not valid */
124 List *relationOids; /* OIDs of relations the queries depend on */
125 List *invalItems; /* other dependencies, as PlanInvalItems */
126 struct SearchPathMatcher *search_path; /* search_path used for parsing
127 * and planning */
128 MemoryContext query_context; /* context holding the above, or NULL */
129 Oid rewriteRoleId; /* Role ID we did rewriting for */
130 bool rewriteRowSecurity; /* row_security used during rewrite */
131 bool dependsOnRLS; /* is rewritten query specific to the above? */
132 /* If we have a generic plan, this is a reference-counted link to it: */
133 struct CachedPlan *gplan; /* generic plan, or NULL if not valid */
134 /* Some state flags: */
135 bool is_oneshot; /* is it a "oneshot" plan? */
136 bool is_complete; /* has CompleteCachedPlan been done? */
137 bool is_saved; /* has CachedPlanSource been "saved"? */
138 bool is_valid; /* is the query_list currently valid? */
139 int generation; /* increments each time we create a plan */
140 /* If CachedPlanSource has been saved, it is a member of a global list */
141 dlist_node node; /* list link, if is_saved */
142 /* State kept to help decide whether to use custom or generic plans: */
143 double generic_cost; /* cost of generic plan, or -1 if not known */
144 double total_custom_cost; /* total cost of custom plans so far */
145 int64 num_custom_plans; /* # of custom plans included in total */
146 int64 num_generic_plans; /* # of generic plans */
148
149/*
150 * CachedPlan represents an execution plan derived from a CachedPlanSource.
151 * The reference count includes both the link from the parent CachedPlanSource
152 * (if any), and any active plan executions, so the plan can be discarded
153 * exactly when refcount goes to zero. Both the struct itself and the
154 * subsidiary data live in the context denoted by the context field.
155 * This makes it easy to free a no-longer-needed cached plan. (However,
156 * if is_oneshot is true, the context does not belong solely to the CachedPlan
157 * so no freeing is possible.)
158 */
159typedef struct CachedPlan
160{
161 int magic; /* should equal CACHEDPLAN_MAGIC */
162 List *stmt_list; /* list of PlannedStmts */
163 bool is_oneshot; /* is it a "oneshot" plan? */
164 bool is_saved; /* is CachedPlan in a long-lived context? */
165 bool is_valid; /* is the stmt_list currently valid? */
166 Oid planRoleId; /* Role ID the plan was created for */
167 bool dependsOnRole; /* is plan specific to that role? */
168 TransactionId saved_xmin; /* if valid, replan when TransactionXmin
169 * changes from this value */
170 int generation; /* parent's generation number for this plan */
171 int refcount; /* count of live references to this struct */
172 MemoryContext context; /* context containing this CachedPlan */
174
175/*
176 * CachedExpression is a low-overhead mechanism for caching the planned form
177 * of standalone scalar expressions. While such expressions are not usually
178 * subject to cache invalidation events, that can happen, for example because
179 * of replacement of a SQL function that was inlined into the expression.
180 * The plancache takes care of storing the expression tree and marking it
181 * invalid if a cache invalidation occurs, but the caller must notice the
182 * !is_valid status and discard the obsolete expression without reusing it.
183 * We do not store the original parse tree, only the planned expression;
184 * this is an optimization based on the assumption that we usually will not
185 * need to replan for the life of the session.
186 */
187typedef struct CachedExpression
188{
189 int magic; /* should equal CACHEDEXPR_MAGIC */
190 Node *expr; /* planned form of expression */
191 bool is_valid; /* is the expression still valid? */
192 /* remaining fields should be treated as private to plancache.c: */
193 List *relationOids; /* OIDs of relations the expr depends on */
194 List *invalItems; /* other dependencies, as PlanInvalItems */
195 MemoryContext context; /* context containing this CachedExpression */
196 dlist_node node; /* link in global list of CachedExpressions */
198
199
200extern void InitPlanCache(void);
201extern void ResetPlanCache(void);
202
204
205extern CachedPlanSource *CreateCachedPlan(struct RawStmt *raw_parse_tree,
206 const char *query_string,
207 CommandTag commandTag);
208extern CachedPlanSource *CreateCachedPlanForQuery(struct Query *analyzed_parse_tree,
209 const char *query_string,
210 CommandTag commandTag);
211extern CachedPlanSource *CreateOneShotCachedPlan(struct RawStmt *raw_parse_tree,
212 const char *query_string,
213 CommandTag commandTag);
214extern void CompleteCachedPlan(CachedPlanSource *plansource,
215 List *querytree_list,
216 MemoryContext querytree_context,
217 Oid *param_types,
218 int num_params,
219 ParserSetupHook parserSetup,
220 void *parserSetupArg,
221 int cursor_options,
222 bool fixed_result);
223extern void SetPostRewriteHook(CachedPlanSource *plansource,
224 PostRewriteHook postRewrite,
225 void *postRewriteArg);
226
227extern void SaveCachedPlan(CachedPlanSource *plansource);
228extern void DropCachedPlan(CachedPlanSource *plansource);
229
230extern void CachedPlanSetParentContext(CachedPlanSource *plansource,
231 MemoryContext newcontext);
232
234
235extern bool CachedPlanIsValid(CachedPlanSource *plansource);
236
238 QueryEnvironment *queryEnv);
239
240extern CachedPlan *GetCachedPlan(CachedPlanSource *plansource,
241 ParamListInfo boundParams,
242 ResourceOwner owner,
243 QueryEnvironment *queryEnv);
245
248 ResourceOwner owner);
249extern bool CachedPlanIsSimplyValid(CachedPlanSource *plansource,
251 ResourceOwner owner);
252
254extern void FreeCachedExpression(CachedExpression *cexpr);
255
256#endif /* PLANCACHE_H */
#define PGDLLIMPORT
Definition: c.h:1291
int64_t int64
Definition: c.h:499
uint32 TransactionId
Definition: c.h:623
CommandTag
Definition: cmdtag.h:23
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
void * arg
#define plan(x)
Definition: pg_regress.c:161
void(* PostRewriteHook)(List *querytree_list, void *arg)
Definition: plancache.h:42
void CachedPlanSetParentContext(CachedPlanSource *plansource, MemoryContext newcontext)
Definition: plancache.c:1610
bool CachedPlanIsValid(CachedPlanSource *plansource)
Definition: plancache.c:1742
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:574
struct CachedExpression CachedExpression
bool CachedPlanAllowsSimpleValidityCheck(CachedPlanSource *plansource, CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1448
void FreeCachedExpression(CachedExpression *cexpr)
Definition: plancache.c:1849
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:530
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:391
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, ResourceOwner owner, QueryEnvironment *queryEnv)
Definition: plancache.c:1280
CachedExpression * GetCachedExpression(Node *expr)
Definition: plancache.c:1792
bool CachedPlanIsSimplyValid(CachedPlanSource *plansource, CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1563
CachedPlanSource * CreateOneShotCachedPlan(struct RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:298
void SetPostRewriteHook(CachedPlanSource *plansource, PostRewriteHook postRewrite, void *postRewriteArg)
Definition: plancache.c:505
CachedPlanSource * CreateCachedPlanForQuery(struct Query *analyzed_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:263
CachedPlanSource * CreateCachedPlan(struct RawStmt *raw_parse_tree, const char *query_string, CommandTag commandTag)
Definition: plancache.c:183
PGDLLIMPORT int plan_cache_mode
Definition: plancache.c:138
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1755
CachedPlanSource * CopyCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:1648
void ReleaseCachedPlan(CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1403
void InitPlanCache(void)
Definition: plancache.c:146
PlanCacheMode
Definition: plancache.h:32
@ PLAN_CACHE_MODE_FORCE_CUSTOM_PLAN
Definition: plancache.h:35
@ PLAN_CACHE_MODE_FORCE_GENERIC_PLAN
Definition: plancache.h:34
@ PLAN_CACHE_MODE_AUTO
Definition: plancache.h:33
struct CachedPlanSource CachedPlanSource
void ReleaseAllPlanCacheRefsInOwner(ResourceOwner owner)
Definition: plancache.c:2347
void ResetPlanCache(void)
Definition: plancache.c:2300
struct CachedPlan CachedPlan
unsigned int Oid
Definition: postgres_ext.h:30
List * relationOids
Definition: plancache.h:193
MemoryContext context
Definition: plancache.h:195
dlist_node node
Definition: plancache.h:196
List * invalItems
Definition: plancache.h:194
dlist_node node
Definition: plancache.h:141
struct CachedPlan * gplan
Definition: plancache.h:133
PostRewriteHook postRewrite
Definition: plancache.h:116
struct Query * analyzed_parse_tree
Definition: plancache.h:109
struct SearchPathMatcher * search_path
Definition: plancache.h:126
MemoryContext query_context
Definition: plancache.h:128
CommandTag commandTag
Definition: plancache.h:111
double total_custom_cost
Definition: plancache.h:144
MemoryContext context
Definition: plancache.h:121
List * invalItems
Definition: plancache.h:125
const char * query_string
Definition: plancache.h:110
ParserSetupHook parserSetup
Definition: plancache.h:114
struct RawStmt * raw_parse_tree
Definition: plancache.h:108
TupleDesc resultDesc
Definition: plancache.h:120
int64 num_custom_plans
Definition: plancache.h:145
int64 num_generic_plans
Definition: plancache.h:146
bool rewriteRowSecurity
Definition: plancache.h:130
List * query_list
Definition: plancache.h:123
void * postRewriteArg
Definition: plancache.h:117
List * relationOids
Definition: plancache.h:124
double generic_cost
Definition: plancache.h:143
void * parserSetupArg
Definition: plancache.h:115
bool is_valid
Definition: plancache.h:165
TransactionId saved_xmin
Definition: plancache.h:168
int generation
Definition: plancache.h:170
Oid planRoleId
Definition: plancache.h:166
MemoryContext context
Definition: plancache.h:172
int refcount
Definition: plancache.h:171
List * stmt_list
Definition: plancache.h:162
bool is_oneshot
Definition: plancache.h:163
bool dependsOnRole
Definition: plancache.h:167
bool is_saved
Definition: plancache.h:164
Definition: pg_list.h:54
Definition: nodes.h:135