1 /*-------------------------------------------------------------------------
2  *
3  * plancache.h
4  *	  Plan cache definitions.
5  *
6  * See plancache.c for comments.
7  *
8  * Portions Copyright (c) 1996-2016, 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 "nodes/params.h"
20 
21 #define CACHEDPLANSOURCE_MAGIC		195726186
22 #define CACHEDPLAN_MAGIC			953717834
23 
24 /*
25  * CachedPlanSource (which might better have been called CachedQuery)
26  * represents a SQL query that we expect to use multiple times.  It stores
27  * the query source text, the raw parse tree, and the analyzed-and-rewritten
28  * query tree, as well as adjunct data.  Cache invalidation can happen as a
29  * result of DDL affecting objects used by the query.  In that case we discard
30  * the analyzed-and-rewritten query tree, and rebuild it when next needed.
31  *
32  * An actual execution plan, represented by CachedPlan, is derived from the
33  * CachedPlanSource when we need to execute the query.  The plan could be
34  * either generic (usable with any set of plan parameters) or custom (for a
35  * specific set of parameters).  plancache.c contains the logic that decides
36  * which way to do it for any particular execution.  If we are using a generic
37  * cached plan then it is meant to be re-used across multiple executions, so
38  * callers must always treat CachedPlans as read-only.
39  *
40  * Once successfully built and "saved", CachedPlanSources typically live
41  * for the life of the backend, although they can be dropped explicitly.
42  * CachedPlans are reference-counted and go away automatically when the last
43  * reference is dropped.  A CachedPlan can outlive the CachedPlanSource it
44  * was created from.
45  *
46  * An "unsaved" CachedPlanSource can be used for generating plans, but it
47  * lives in transient storage and will not be updated in response to sinval
48  * events.
49  *
50  * CachedPlans made from saved CachedPlanSources are likewise in permanent
51  * storage, so to avoid memory leaks, the reference-counted references to them
52  * must be held in permanent data structures or ResourceOwners.  CachedPlans
53  * made from unsaved CachedPlanSources are in children of the caller's
54  * memory context, so references to them should not be longer-lived than
55  * that context.  (Reference counting is somewhat pro forma in that case,
56  * though it may be useful if the CachedPlan can be discarded early.)
57  *
58  * A CachedPlanSource has two associated memory contexts: one that holds the
59  * struct itself, the query source text and the raw parse tree, and another
60  * context that holds the rewritten query tree and associated data.  This
61  * allows the query tree to be discarded easily when it is invalidated.
62  *
63  * Some callers wish to use the CachedPlan API even with one-shot queries
64  * that have no reason to be saved at all.  We therefore support a "oneshot"
65  * variant that does no data copying or invalidation checking.  In this case
66  * there are no separate memory contexts: the CachedPlanSource struct and
67  * all subsidiary data live in the caller's CurrentMemoryContext, and there
68  * is no way to free memory short of clearing that entire context.  A oneshot
69  * plan is always treated as unsaved.
70  *
71  * Note: the string referenced by commandTag is not subsidiary storage;
72  * it is assumed to be a compile-time-constant string.  As with portals,
73  * commandTag shall be NULL if and only if the original query string (before
74  * rewriting) was an empty string.
75  */
76 typedef struct CachedPlanSource
77 {
78 	int			magic;			/* should equal CACHEDPLANSOURCE_MAGIC */
79 	Node	   *raw_parse_tree; /* output of raw_parser(), or NULL */
80 	const char *query_string;	/* source text of query */
81 	const char *commandTag;		/* command tag (a constant!), or NULL */
82 	Oid		   *param_types;	/* array of parameter type OIDs, or NULL */
83 	int			num_params;		/* length of param_types array */
84 	ParserSetupHook parserSetup;	/* alternative parameter spec method */
85 	void	   *parserSetupArg;
86 	int			cursor_options; /* cursor options used for planning */
87 	bool		fixed_result;	/* disallow change in result tupdesc? */
88 	TupleDesc	resultDesc;		/* result type; NULL = doesn't return tuples */
89 	MemoryContext context;		/* memory context holding all above */
90 	/* These fields describe the current analyzed-and-rewritten query tree: */
91 	List	   *query_list;		/* list of Query nodes, or NIL if not valid */
92 	List	   *relationOids;	/* OIDs of relations the queries depend on */
93 	List	   *invalItems;		/* other dependencies, as PlanInvalItems */
94 	struct OverrideSearchPath *search_path;		/* search_path used for
95 												 * parsing and planning */
96 	MemoryContext query_context;	/* context holding the above, or NULL */
97 	Oid			rewriteRoleId;	/* Role ID we did rewriting for */
98 	bool		rewriteRowSecurity;		/* row_security used during rewrite */
99 	bool		dependsOnRLS;	/* is rewritten query specific to the above? */
100 	/* If we have a generic plan, this is a reference-counted link to it: */
101 	struct CachedPlan *gplan;	/* generic plan, or NULL if not valid */
102 	/* Some state flags: */
103 	bool		is_oneshot;		/* is it a "oneshot" plan? */
104 	bool		is_complete;	/* has CompleteCachedPlan been done? */
105 	bool		is_saved;		/* has CachedPlanSource been "saved"? */
106 	bool		is_valid;		/* is the query_list currently valid? */
107 	int			generation;		/* increments each time we create a plan */
108 	/* If CachedPlanSource has been saved, it is a member of a global list */
109 	struct CachedPlanSource *next_saved;		/* list link, if so */
110 	/* State kept to help decide whether to use custom or generic plans: */
111 	double		generic_cost;	/* cost of generic plan, or -1 if not known */
112 	double		total_custom_cost;		/* total cost of custom plans so far */
113 	int			num_custom_plans;		/* number of plans included in total */
114 } CachedPlanSource;
115 
116 /*
117  * CachedPlan represents an execution plan derived from a CachedPlanSource.
118  * The reference count includes both the link from the parent CachedPlanSource
119  * (if any), and any active plan executions, so the plan can be discarded
120  * exactly when refcount goes to zero.  Both the struct itself and the
121  * subsidiary data live in the context denoted by the context field.
122  * This makes it easy to free a no-longer-needed cached plan.  (However,
123  * if is_oneshot is true, the context does not belong solely to the CachedPlan
124  * so no freeing is possible.)
125  */
126 typedef struct CachedPlan
127 {
128 	int			magic;			/* should equal CACHEDPLAN_MAGIC */
129 	List	   *stmt_list;		/* list of statement nodes (PlannedStmts and
130 								 * bare utility statements) */
131 	bool		is_oneshot;		/* is it a "oneshot" plan? */
132 	bool		is_saved;		/* is CachedPlan in a long-lived context? */
133 	bool		is_valid;		/* is the stmt_list currently valid? */
134 	Oid			planRoleId;		/* Role ID the plan was created for */
135 	bool		dependsOnRole;	/* is plan specific to that role? */
136 	TransactionId saved_xmin;	/* if valid, replan when TransactionXmin
137 								 * changes from this value */
138 	int			generation;		/* parent's generation number for this plan */
139 	int			refcount;		/* count of live references to this struct */
140 	MemoryContext context;		/* context containing this CachedPlan */
141 } CachedPlan;
142 
143 
144 extern void InitPlanCache(void);
145 extern void ResetPlanCache(void);
146 
147 extern CachedPlanSource *CreateCachedPlan(Node *raw_parse_tree,
148 				 const char *query_string,
149 				 const char *commandTag);
150 extern CachedPlanSource *CreateOneShotCachedPlan(Node *raw_parse_tree,
151 						const char *query_string,
152 						const char *commandTag);
153 extern void CompleteCachedPlan(CachedPlanSource *plansource,
154 				   List *querytree_list,
155 				   MemoryContext querytree_context,
156 				   Oid *param_types,
157 				   int num_params,
158 				   ParserSetupHook parserSetup,
159 				   void *parserSetupArg,
160 				   int cursor_options,
161 				   bool fixed_result);
162 
163 extern void SaveCachedPlan(CachedPlanSource *plansource);
164 extern void DropCachedPlan(CachedPlanSource *plansource);
165 
166 extern void CachedPlanSetParentContext(CachedPlanSource *plansource,
167 						   MemoryContext newcontext);
168 
169 extern CachedPlanSource *CopyCachedPlan(CachedPlanSource *plansource);
170 
171 extern bool CachedPlanIsValid(CachedPlanSource *plansource);
172 
173 extern List *CachedPlanGetTargetList(CachedPlanSource *plansource);
174 
175 extern CachedPlan *GetCachedPlan(CachedPlanSource *plansource,
176 			  ParamListInfo boundParams,
177 			  bool useResOwner);
178 extern void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner);
179 
180 #endif   /* PLANCACHE_H */
181